Release 4.69
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blob9c544ee515a8001a12a60ab944857f7f77fddf65
1 ;;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.69a
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.69a"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 ;;; The custom variables
102 (defgroup org nil
103 "Outline-based notes management and organizer."
104 :tag "Org"
105 :group 'outlines
106 :group 'hypermedia
107 :group 'calendar)
109 (defgroup org-startup nil
110 "Options concerning startup of Org-mode."
111 :tag "Org Startup"
112 :group 'org)
114 (defcustom org-startup-folded t
115 "Non-nil means, entering Org-mode will switch to OVERVIEW.
116 This can also be configured on a per-file basis by adding one of
117 the following lines anywhere in the buffer:
119 #+STARTUP: fold
120 #+STARTUP: nofold
121 #+STARTUP: content"
122 :group 'org-startup
123 :type '(choice
124 (const :tag "nofold: show all" nil)
125 (const :tag "fold: overview" t)
126 (const :tag "content: all headlines" content)))
128 (defcustom org-startup-truncated t
129 "Non-nil means, entering Org-mode will set `truncate-lines'.
130 This is useful since some lines containing links can be very long and
131 uninteresting. Also tables look terrible when wrapped."
132 :group 'org-startup
133 :type 'boolean)
135 (defcustom org-startup-align-all-tables nil
136 "Non-nil means, align all tables when visiting a file.
137 This is useful when the column width in tables is forced with <N> cookies
138 in table fields. Such tables will look correct only after the first re-align.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
141 #+STARTUP: align
142 #+STARTUP: noalign"
143 :group 'org-startup
144 :type 'boolean)
146 (defcustom org-insert-mode-line-in-empty-file nil
147 "Non-nil means insert the first line setting Org-mode in empty files.
148 When the function `org-mode' is called interactively in an empty file, this
149 normally means that the file name does not automatically trigger Org-mode.
150 To ensure that the file will always be in Org-mode in the future, a
151 line enforcing Org-mode will be inserted into the buffer, if this option
152 has been set."
153 :group 'org-startup
154 :type 'boolean)
156 (defcustom org-CUA-compatible nil
157 "Non-nil means use alternative key bindings for S-<cursor movement>.
158 Org-mode used S-<cursor movement> for changing timestamps and priorities.
159 S-<cursor movement> is also used for example by `CUA-mode' to select text.
160 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
161 alternative bindings. Setting this variable to t will replace the following
162 keys both in Org-mode and in the Org-agenda buffer.
164 S-RET -> C-S-RET
165 S-up -> M-p
166 S-down -> M-n
167 S-left -> M--
168 S-right -> M-+
170 If you do not like the alternative keys, take a look at the variable
171 `org-disputed-keys'.
173 This option is only relevant at load-time of Org-mode, and must be set
174 *before* org.el is loaded. Changing it requires a restart of Emacs to
175 become effective."
176 :group 'org-startup
177 :type 'boolean)
179 (defvar org-disputed-keys
180 '((S-up [(shift up)] [(meta ?p)])
181 (S-down [(shift down)] [(meta ?n)])
182 (S-left [(shift left)] [(meta ?-)])
183 (S-right [(shift right)] [(meta ?+)])
184 (S-return [(shift return)] [(control shift return)]))
185 "Keys for which Org-mode and other modes compete.
186 This is an alist, cars are symbols for lookup, 1st element is the default key,
187 second element will be used when `org-CUA-compatible' is t.")
189 (defun org-key (key)
190 "Select a key according to `org-CUA-compatible'."
191 (nth (if org-CUA-compatible 2 1)
192 (or (assq key org-disputed-keys)
193 (error "Invalid Key %s in `org-key'" key))))
195 (defcustom org-ellipsis nil
196 "The ellipsis to use in the Org-mode outline.
197 When nil, just use the standard three dots. When a string, use that instead,
198 and just in Org-mode (which will then use its own display table).
199 Changing this requires executing `M-x org-mode' in a buffer to become
200 effective."
201 :group 'org-startup
202 :type '(choice (const :tag "Default" nil)
203 (string :tag "String" :value "...#")))
205 (defvar org-display-table nil
206 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
208 (defgroup org-keywords nil
209 "Keywords in Org-mode."
210 :tag "Org Keywords"
211 :group 'org)
213 (defcustom org-deadline-string "DEADLINE:"
214 "String to mark deadline entries.
215 A deadline is this string, followed by a time stamp. Should be a word,
216 terminated by a colon. You can insert a schedule keyword and
217 a timestamp with \\[org-deadline].
218 Changes become only effective after restarting Emacs."
219 :group 'org-keywords
220 :type 'string)
222 (defcustom org-scheduled-string "SCHEDULED:"
223 "String to mark scheduled TODO entries.
224 A schedule is this string, followed by a time stamp. Should be a word,
225 terminated by a colon. You can insert a schedule keyword and
226 a timestamp with \\[org-schedule].
227 Changes become only effective after restarting Emacs."
228 :group 'org-keywords
229 :type 'string)
231 (defcustom org-closed-string "CLOSED:"
232 "String used as the prefix for timestamps logging closing a TODO entry."
233 :group 'org-keywords
234 :type 'string)
236 (defcustom org-clock-string "CLOCK:"
237 "String used as prefix for timestamps clocking work hours on an item."
238 :group 'org-keywords
239 :type 'string)
241 (defcustom org-comment-string "COMMENT"
242 "Entries starting with this keyword will never be exported.
243 An entry can be toggled between COMMENT and normal with
244 \\[org-toggle-comment].
245 Changes become only effective after restarting Emacs."
246 :group 'org-keywords
247 :type 'string)
249 (defcustom org-quote-string "QUOTE"
250 "Entries starting with this keyword will be exported in fixed-width font.
251 Quoting applies only to the text in the entry following the headline, and does
252 not extend beyond the next headline, even if that is lower level.
253 An entry can be toggled between QUOTE and normal with
254 \\[org-toggle-fixed-width-section]."
255 :group 'org-keywords
256 :type 'string)
258 (defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
259 "Regular expression for specifying repeated events.
260 After a match, group 1 contains the repeat expression.")
262 (defgroup org-structure nil
263 "Options concerning the general structure of Org-mode files."
264 :tag "Org Structure"
265 :group 'org)
267 (defgroup org-reveal-location nil
268 "Options about how to make context of a location visible."
269 :tag "Org Reveal Location"
270 :group 'org-structure)
272 (defcustom org-show-hierarchy-above '((default . t))
273 "Non-nil means, show full hierarchy when revealing a location.
274 Org-mode often shows locations in an org-mode file which might have
275 been invisible before. When this is set, the hierarchy of headings
276 above the exposed location is shown.
277 Turning this off for example for sparse trees makes them very compact.
278 Instead of t, this can also be an alist specifying this option for different
279 contexts. Valid contexts are
280 agenda when exposing an entry from the agenda
281 org-goto when using the command `org-goto' on key C-c C-j
282 occur-tree when using the command `org-occur' on key C-c /
283 tags-tree when constructing a sparse tree based on tags matches
284 link-search when exposing search matches associated with a link
285 mark-goto when exposing the jump goal of a mark
286 bookmark-jump when exposing a bookmark location
287 isearch when exiting from an incremental search
288 default default for all contexts not set explicitly"
289 :group 'org-reveal-location
290 :type '(choice
291 (const :tag "Always" t)
292 (const :tag "Never" nil)
293 (repeat :greedy t :tag "Individual contexts"
294 (cons
295 (choice :tag "Context"
296 (const agenda)
297 (const org-goto)
298 (const occur-tree)
299 (const tags-tree)
300 (const link-search)
301 (const mark-goto)
302 (const bookmark-jump)
303 (const isearch)
304 (const default))
305 (boolean)))))
307 (defcustom org-show-following-heading '((default . t))
308 "Non-nil means, show following heading when revealing a location.
309 Org-mode often shows locations in an org-mode file which might have
310 been invisible before. When this is set, the heading following the
311 match is shown.
312 Turning this off for example for sparse trees makes them very compact,
313 but makes it harder to edit the location of the match. In such a case,
314 use the command \\[org-reveal] to show more context.
315 Instead of t, this can also be an alist specifying this option for different
316 contexts. See `org-show-hierarchy-above' for valid contexts."
317 :group 'org-reveal-location
318 :type '(choice
319 (const :tag "Always" t)
320 (const :tag "Never" nil)
321 (repeat :greedy t :tag "Individual contexts"
322 (cons
323 (choice :tag "Context"
324 (const agenda)
325 (const org-goto)
326 (const occur-tree)
327 (const tags-tree)
328 (const link-search)
329 (const mark-goto)
330 (const bookmark-jump)
331 (const isearch)
332 (const default))
333 (boolean)))))
335 (defcustom org-show-siblings '((default . nil) (isearch t))
336 "Non-nil means, show all sibling heading when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the sibling of the current entry
339 heading are all made visible. If `org-show-hierarchy-above' is t,
340 the same happens on each level of the hierarchy above the current entry.
342 By default this is on for the isearch context, off for all other contexts.
343 Turning this off for example for sparse trees makes them very compact,
344 but makes it harder to edit the location of the match. In such a case,
345 use the command \\[org-reveal] to show more context.
346 Instead of t, this can also be an alist specifying this option for different
347 contexts. See `org-show-hierarchy-above' for valid contexts."
348 :group 'org-reveal-location
349 :type '(choice
350 (const :tag "Always" t)
351 (const :tag "Never" nil)
352 (repeat :greedy t :tag "Individual contexts"
353 (cons
354 (choice :tag "Context"
355 (const agenda)
356 (const org-goto)
357 (const occur-tree)
358 (const tags-tree)
359 (const link-search)
360 (const mark-goto)
361 (const bookmark-jump)
362 (const isearch)
363 (const default))
364 (boolean)))))
366 (defgroup org-cycle nil
367 "Options concerning visibility cycling in Org-mode."
368 :tag "Org Cycle"
369 :group 'org-structure)
371 (defcustom org-cycle-global-at-bob t
372 "Cycle globally if cursor is at beginning of buffer and not at a headline.
373 This makes it possible to do global cycling without having to use S-TAB or
374 C-u TAB. For this special case to work, the first line of the buffer
375 must not be a headline - it may be empty ot some other text. When used in
376 this way, `org-cycle-hook' is disables temporarily, to make sure the
377 cursor stays at the beginning of the buffer.
378 When this option is nil, don't do anything special at the beginning
379 of the buffer."
380 :group 'org-cycle
381 :type 'boolean)
383 (defcustom org-cycle-emulate-tab t
384 "Where should `org-cycle' emulate TAB.
385 nil Never
386 white Only in completely white lines
387 whitestart Only at the beginning of lines, before the first non-white char.
388 t Everywhere except in headlines
389 If TAB is used in a place where it does not emulate TAB, the current subtree
390 visibility is cycled."
391 :group 'org-cycle
392 :type '(choice (const :tag "Never" nil)
393 (const :tag "Only in completely white lines" white)
394 (const :tag "Before first char in a line" whitestart)
395 (const :tag "Everywhere except in headlines" t)
398 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
399 org-optimize-window-after-visibility-change)
400 "Hook that is run after `org-cycle' has changed the buffer visibility.
401 The function(s) in this hook must accept a single argument which indicates
402 the new state that was set by the most recent `org-cycle' command. The
403 argument is a symbol. After a global state change, it can have the values
404 `overview', `content', or `all'. After a local state change, it can have
405 the values `folded', `children', or `subtree'."
406 :group 'org-cycle
407 :type 'hook)
410 (defgroup org-edit-structure nil
411 "Options concerning structure editing in Org-mode."
412 :tag "Org Edit Structure"
413 :group 'org-structure)
415 (defcustom org-odd-levels-only nil
416 "Non-nil means, skip even levels and only use odd levels for the outline.
417 This has the effect that two stars are being added/taken away in
418 promotion/demotion commands. It also influences how levels are
419 handled by the exporters.
420 Changing it requires restart of `font-lock-mode' to become effective
421 for fontification also in regions already fontified.
422 You may also set this on a per-file basis by adding one of the following
423 lines to the buffer:
425 #+STARTUP: odd
426 #+STARTUP: oddeven"
427 :group 'org-edit-structure
428 :group 'org-font-lock
429 :type 'boolean)
431 (defcustom org-adapt-indentation t
432 "Non-nil means, adapt indentation when promoting and demoting.
433 When this is set and the *entire* text in an entry is indented, the
434 indentation is increased by one space in a demotion command, and
435 decreased by one in a promotion command. If any line in the entry
436 body starts at column 0, indentation is not changed at all."
437 :group 'org-edit-structure
438 :type 'boolean)
440 (defcustom org-blank-before-new-entry '((heading . nil)
441 (plain-list-item . nil))
442 "Should `org-insert-heading' leave a blank line before new heading/item?
443 The value is an alist, with `heading' and `plain-list-item' as car,
444 and a boolean flag as cdr."
445 :group 'org-edit-structure
446 :type '(list
447 (cons (const heading) (boolean))
448 (cons (const plain-list-item) (boolean))))
450 (defcustom org-insert-heading-hook nil
451 "Hook being run after inserting a new heading."
452 :group 'org-edit-structure
453 :type 'boolean)
455 (defcustom org-enable-fixed-width-editor t
456 "Non-nil means, lines starting with \":\" are treated as fixed-width.
457 This currently only means, they are never auto-wrapped.
458 When nil, such lines will be treated like ordinary lines.
459 See also the QUOTE keyword."
460 :group 'org-edit-structure
461 :type 'boolean)
463 (defgroup org-sparse-trees nil
464 "Options concerning sparse trees in Org-mode."
465 :tag "Org Sparse Trees"
466 :group 'org-structure)
468 (defcustom org-highlight-sparse-tree-matches t
469 "Non-nil means, highlight all matches that define a sparse tree.
470 The highlights will automatically disappear the next time the buffer is
471 changed by an edit command."
472 :group 'org-sparse-trees
473 :type 'boolean)
475 (defcustom org-remove-highlights-with-change t
476 "Non-nil means, any change to the buffer will remove temporary highlights.
477 Such highlights are created by `org-occur' and `org-clock-display'.
478 When nil, `C-c C-c needs to be used to get rid of the highlights.
479 The highlights created by `org-preview-latex-fragment' always need
480 `C-c C-c' to be removed."
481 :group 'org-sparse-trees
482 :group 'org-time
483 :type 'boolean)
486 (defcustom org-occur-hook '(org-first-headline-recenter)
487 "Hook that is run after `org-occur' has constructed a sparse tree.
488 This can be used to recenter the window to show as much of the structure
489 as possible."
490 :group 'org-sparse-trees
491 :type 'hook)
493 (defgroup org-plain-lists nil
494 "Options concerning plain lists in Org-mode."
495 :tag "Org Plain lists"
496 :group 'org-structure)
498 (defcustom org-cycle-include-plain-lists nil
499 "Non-nil means, include plain lists into visibility cycling.
500 This means that during cycling, plain list items will *temporarily* be
501 interpreted as outline headlines with a level given by 1000+i where i is the
502 indentation of the bullet. In all other operations, plain list items are
503 not seen as headlines. For example, you cannot assign a TODO keyword to
504 such an item."
505 :group 'org-plain-lists
506 :type 'boolean)
508 (defcustom org-plain-list-ordered-item-terminator t
509 "The character that makes a line with leading number an ordered list item.
510 Valid values are ?. and ?\). To get both terminators, use t. While
511 ?. may look nicer, it creates the danger that a line with leading
512 number may be incorrectly interpreted as an item. ?\) therefore is
513 the safe choice."
514 :group 'org-plain-lists
515 :type '(choice (const :tag "dot like in \"2.\"" ?.)
516 (const :tag "paren like in \"2)\"" ?\))
517 (const :tab "both" t)))
519 (defcustom org-auto-renumber-ordered-lists t
520 "Non-nil means, automatically renumber ordered plain lists.
521 Renumbering happens when the sequence have been changed with
522 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
523 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
524 :group 'org-plain-lists
525 :type 'boolean)
527 (defcustom org-provide-checkbox-statistics t
528 "Non-nil means, update checkbox statistics after insert and toggle.
529 When this is set, checkbox statistics is updated each time you either insert
530 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
531 with \\[org-ctrl-c-ctrl-c\\]."
532 :group 'org-plain-lists
533 :type 'boolean)
535 (defgroup org-archive nil
536 "Options concerning archiving in Org-mode."
537 :tag "Org Archive"
538 :group 'org-structure)
540 (defcustom org-archive-tag "ARCHIVE"
541 "The tag that marks a subtree as archived.
542 An archived subtree does not open during visibility cycling, and does
543 not contribute to the agenda listings."
544 :group 'org-archive
545 :group 'org-keywords
546 :type 'string)
548 (defcustom org-agenda-skip-archived-trees t
549 "Non-nil means, the agenda will skip any items located in archived trees.
550 An archived tree is a tree marked with the tag ARCHIVE."
551 :group 'org-archive
552 :group 'org-agenda-skip
553 :type 'boolean)
555 (defcustom org-cycle-open-archived-trees nil
556 "Non-nil means, `org-cycle' will open archived trees.
557 An archived tree is a tree marked with the tag ARCHIVE.
558 When nil, archived trees will stay folded. You can still open them with
559 normal outline commands like `show-all', but not with the cycling commands."
560 :group 'org-archive
561 :group 'org-cycle
562 :type 'boolean)
564 (defcustom org-sparse-tree-open-archived-trees nil
565 "Non-nil means sparse tree construction shows matches in archived trees.
566 When nil, matches in these trees are highlighted, but the trees are kept in
567 collapsed state."
568 :group 'org-archive
569 :group 'org-sparse-trees
570 :type 'boolean)
572 (defcustom org-archive-location "%s_archive::"
573 "The location where subtrees should be archived.
574 This string consists of two parts, separated by a double-colon.
576 The first part is a file name - when omitted, archiving happens in the same
577 file. %s will be replaced by the current file name (without directory part).
578 Archiving to a different file is useful to keep archived entries from
579 contributing to the Org-mode Agenda.
581 The part after the double colon is a headline. The archived entries will be
582 filed under that headline. When omitted, the subtrees are simply filed away
583 at the end of the file, as top-level entries.
585 Here are a few examples:
586 \"%s_archive::\"
587 If the current file is Projects.org, archive in file
588 Projects.org_archive, as top-level trees. This is the default.
590 \"::* Archived Tasks\"
591 Archive in the current file, under the top-level headline
592 \"* Archived Tasks\".
594 \"~/org/archive.org::\"
595 Archive in file ~/org/archive.org (absolute path), as top-level trees.
597 \"basement::** Finished Tasks\"
598 Archive in file ./basement (relative path), as level 3 trees
599 below the level 2 heading \"** Finished Tasks\".
601 You may set this option on a per-file basis by adding to the buffer a
602 line like
604 #+ARCHIVE: basement::** Finished Tasks"
605 :group 'org-archive
606 :type 'string)
608 (defcustom org-archive-mark-done t
609 "Non-nil means, mark entries as DONE when they are moved to the archive file."
610 :group 'org-archive
611 :type 'boolean)
613 (defcustom org-archive-stamp-time t
614 "Non-nil means, add a time stamp to entries moved to an archive file.
615 The time stamp will be added directly after the TODO state keyword in the
616 first line, so it is probably best to use this in combinations with
617 `org-archive-mark-done'."
618 :group 'org-archive
619 :type 'boolean)
621 (defgroup org-table nil
622 "Options concerning tables in Org-mode."
623 :tag "Org Table"
624 :group 'org)
626 (defcustom org-enable-table-editor 'optimized
627 "Non-nil means, lines starting with \"|\" are handled by the table editor.
628 When nil, such lines will be treated like ordinary lines.
630 When equal to the symbol `optimized', the table editor will be optimized to
631 do the following:
632 - Automatic overwrite mode in front of whitespace in table fields.
633 This makes the structure of the table stay in tact as long as the edited
634 field does not exceed the column width.
635 - Minimize the number of realigns. Normally, the table is aligned each time
636 TAB or RET are pressed to move to another field. With optimization this
637 happens only if changes to a field might have changed the column width.
638 Optimization requires replacing the functions `self-insert-command',
639 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
640 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
641 very good at guessing when a re-align will be necessary, but you can always
642 force one with \\[org-ctrl-c-ctrl-c].
644 If you would like to use the optimized version in Org-mode, but the
645 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
647 This variable can be used to turn on and off the table editor during a session,
648 but in order to toggle optimization, a restart is required.
650 See also the variable `org-table-auto-blank-field'."
651 :group 'org-table
652 :type '(choice
653 (const :tag "off" nil)
654 (const :tag "on" t)
655 (const :tag "on, optimized" optimized)))
657 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
658 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
659 In the optimized version, the table editor takes over all simple keys that
660 normally just insert a character. In tables, the characters are inserted
661 in a way to minimize disturbing the table structure (i.e. in overwrite mode
662 for empty fields). Outside tables, the correct binding of the keys is
663 restored.
665 The default for this option is t if the optimized version is also used in
666 Org-mode. See the variable `org-enable-table-editor' for details. Changing
667 this variable requires a restart of Emacs to become effective."
668 :group 'org-table
669 :type 'boolean)
671 (defcustom orgtbl-radio-table-templates
672 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
673 % END RECEIVE ORGTBL %n
674 \\begin{comment}
675 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
676 | | |
677 \\end{comment}\n")
678 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
679 @c END RECEIVE ORGTBL %n
680 @ignore
681 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
682 | | |
683 @end ignore\n")
684 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
685 <!-- END RECEIVE ORGTBL %n -->
686 <!--
687 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
688 | | |
689 -->\n"))
690 "Templates for radio tables in different major modes.
691 All occurrences of %n in a template will be replaced with the name of the
692 table, obtained by prompting the user."
693 :group 'org-table
694 :type '(repeat
695 (list (symbol :tag "Major mode")
696 (string :tag "Format"))))
698 (defgroup org-table-settings nil
699 "Settings for tables in Org-mode."
700 :tag "Org Table Settings"
701 :group 'org-table)
703 (defcustom org-table-default-size "5x2"
704 "The default size for newly created tables, Columns x Rows."
705 :group 'org-table-settings
706 :type 'string)
708 (defcustom org-table-number-regexp
709 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
710 "Regular expression for recognizing numbers in table columns.
711 If a table column contains mostly numbers, it will be aligned to the
712 right. If not, it will be aligned to the left.
714 The default value of this option is a regular expression which allows
715 anything which looks remotely like a number as used in scientific
716 context. For example, all of the following will be considered a
717 number:
718 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
720 Other options offered by the customize interface are more restrictive."
721 :group 'org-table-settings
722 :type '(choice
723 (const :tag "Positive Integers"
724 "^[0-9]+$")
725 (const :tag "Integers"
726 "^[-+]?[0-9]+$")
727 (const :tag "Floating Point Numbers"
728 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
729 (const :tag "Floating Point Number or Integer"
730 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
731 (const :tag "Exponential, Floating point, Integer"
732 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
733 (const :tag "Very General Number-Like, including hex"
734 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
735 (string :tag "Regexp:")))
737 (defcustom org-table-number-fraction 0.5
738 "Fraction of numbers in a column required to make the column align right.
739 In a column all non-white fields are considered. If at least this
740 fraction of fields is matched by `org-table-number-fraction',
741 alignment to the right border applies."
742 :group 'org-table-settings
743 :type 'number)
745 (defgroup org-table-editing nil
746 "Bahavior of tables during editing in Org-mode."
747 :tag "Org Table Editing"
748 :group 'org-table)
750 (defcustom org-table-automatic-realign t
751 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
752 When nil, aligning is only done with \\[org-table-align], or after column
753 removal/insertion."
754 :group 'org-table-editing
755 :type 'boolean)
757 (defcustom org-table-auto-blank-field t
758 "Non-nil means, automatically blank table field when starting to type into it.
759 This only happens when typing immediately after a field motion
760 command (TAB, S-TAB or RET).
761 Only relevant when `org-enable-table-editor' is equal to `optimized'."
762 :group 'org-table-editing
763 :type 'boolean)
765 (defcustom org-table-tab-jumps-over-hlines t
766 "Non-nil means, tab in the last column of a table with jump over a hline.
767 If a horizontal separator line is following the current line,
768 `org-table-next-field' can either create a new row before that line, or jump
769 over the line. When this option is nil, a new line will be created before
770 this line."
771 :group 'org-table-editing
772 :type 'boolean)
774 (defcustom org-table-tab-recognizes-table.el t
775 "Non-nil means, TAB will automatically notice a table.el table.
776 When it sees such a table, it moves point into it and - if necessary -
777 calls `table-recognize-table'."
778 :group 'org-table-editing
779 :type 'boolean)
781 (defgroup org-table-calculation nil
782 "Options concerning tables in Org-mode."
783 :tag "Org Table Calculation"
784 :group 'org-table)
786 (defcustom org-table-use-standard-references t
787 "Should org-mode work with table refrences like B3 instead of @3$2?
788 Possible values are:
789 nil never use them
790 from accept as input, do not present for editing
791 t: accept as input and present for editing"
792 :group 'org-table-calculation
793 :type '(choice
794 (const :tag "Never, don't even check unser input for them" nil)
795 (const :tag "Always, both as user input, and when editing" t)
796 (const :tag "Conver user input, don't offerr during editing" 'from)))
798 (defcustom org-table-copy-increment t
799 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
800 :group 'org-table-calculation
801 :type 'boolean)
803 (defcustom org-calc-default-modes
804 '(calc-internal-prec 12
805 calc-float-format (float 5)
806 calc-angle-mode deg
807 calc-prefer-frac nil
808 calc-symbolic-mode nil
809 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
810 calc-display-working-message t
812 "List with Calc mode settings for use in calc-eval for table formulas.
813 The list must contain alternating symbols (Calc modes variables and values).
814 Don't remove any of the default settings, just change the values. Org-mode
815 relies on the variables to be present in the list."
816 :group 'org-table-calculation
817 :type 'plist)
819 (defcustom org-table-formula-evaluate-inline t
820 "Non-nil means, TAB and RET evaluate a formula in current table field.
821 If the current field starts with an equal sign, it is assumed to be a formula
822 which should be evaluated as described in the manual and in the documentation
823 string of the command `org-table-eval-formula'. This feature requires the
824 Emacs calc package.
825 When this variable is nil, formula calculation is only available through
826 the command \\[org-table-eval-formula]."
827 :group 'org-table-calculation
828 :type 'boolean)
830 (defcustom org-table-formula-use-constants t
831 "Non-nil means, interpret constants in formulas in tables.
832 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
833 by the value given in `org-table-formula-constants', or by a value obtained
834 from the `constants.el' package."
835 :group 'org-table-calculation
836 :type 'boolean)
838 ;; FIXME this is also a variable that makes Org-mode files non-portable
839 ;; Maybe I should have a #+ options for constants?
840 (defcustom org-table-formula-constants nil
841 "Alist with constant names and values, for use in table formulas.
842 The car of each element is a name of a constant, without the `$' before it.
843 The cdr is the value as a string. For example, if you'd like to use the
844 speed of light in a formula, you would configure
846 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
848 and then use it in an equation like `$1*$c'."
849 :group 'org-table-calculation
850 :type '(repeat
851 (cons (string :tag "name")
852 (string :tag "value"))))
854 (defcustom org-table-allow-automatic-line-recalculation t
855 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
856 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
857 :group 'org-table-calculation
858 :type 'boolean)
860 (defgroup org-link nil
861 "Options concerning links in Org-mode."
862 :tag "Org Link"
863 :group 'org)
865 (defvar org-link-abbrev-alist-local nil
866 "buffer-local version of `org-link-abbrev-alist', which see.
867 The value of this is taken from the #+LINK lines.")
868 (make-variable-buffer-local 'org-link-abbrev-alist-local)
870 (defcustom org-link-abbrev-alist nil
871 "Alist of link abbreviations.
872 The car of each element is a string, to be replaced at the start of a link.
873 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
874 links in Org-mode buffers can have an optional tag after a double colon, e.g.
876 [[linkkey:tag][description]]
878 If REPLACE is a string, the tag will simply be appended to create the link.
879 If the string contains \"%s\", the tag will be inserted there. REPLACE may
880 also be a function that will be called with the tag as the only argument to
881 create the link. See the manual for examples."
882 :group 'org-link
883 :type 'alist)
885 (defcustom org-descriptive-links t
886 "Non-nil means, hide link part and only show description of bracket links.
887 Bracket links are like [[link][descritpion]]. This variable sets the initial
888 state in new org-mode buffers. The setting can then be toggled on a
889 per-buffer basis from the Org->Hyperlinks menu."
890 :group 'org-link
891 :type 'boolean)
893 (defcustom org-link-file-path-type 'adaptive
894 "How the path name in file links should be stored.
895 Valid values are:
897 relative relative to the current directory, i.e. the directory of the file
898 into which the link is being inserted.
899 absolute absolute path, if possible with ~ for home directory.
900 noabbrev absolute path, no abbreviation of home directory.
901 adaptive Use relative path for files in the current directory and sub-
902 directories of it. For other files, use an absolute path."
903 :group 'org-link
904 :type '(choice
905 (const relative)
906 (const absolute)
907 (const noabbrev)
908 (const adaptive)))
910 (defcustom org-activate-links '(bracket angle plain radio tag date)
911 "Types of links that should be activated in Org-mode files.
912 This is a list of symbols, each leading to the activation of a certain link
913 type. In principle, it does not hurt to turn on most link types - there may
914 be a small gain when turning off unused link types. The types are:
916 bracket The recommended [[link][description]] or [[link]] links with hiding.
917 angular Links in angular brackes that may contain whitespace like
918 <bbdb:Carsten Dominik>.
919 plain Plain links in normal text, no whitespace, like http://google.com.
920 radio Text that is matched by a radio target, see manual for details.
921 tag Tag settings in a headline (link to tag search).
922 date Time stamps (link to calendar).
924 Changing this variable requires a restart of Emacs to become effective."
925 :group 'org-link
926 :type '(set (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)))
933 (defgroup org-link-store nil
934 "Options concerning storing links in Org-mode"
935 :tag "Org Store Link"
936 :group 'org-link)
938 (defcustom org-email-link-description-format "Email %c: %.30s"
939 "Format of the description part of a link to an email or usenet message.
940 The following %-excapes will be replaced by corresponding information:
942 %F full \"From\" field
943 %f name, taken from \"From\" field, address if no name
944 %T full \"To\" field
945 %t first name in \"To\" field, address if no name
946 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
947 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
948 %s subject
949 %m message-id.
951 You may use normal field width specification between the % and the letter.
952 This is for example useful to limit the length of the subject.
954 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
955 :group 'org-link-store
956 :type 'string)
958 (defcustom org-from-is-user-regexp
959 (let (r1 r2)
960 (when (and user-mail-address (not (string= user-mail-address "")))
961 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
962 (when (and user-full-name (not (string= user-full-name "")))
963 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
964 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
965 "Regexp mached against the \"From:\" header of an email or usenet message.
966 It should match if the message is from the user him/herself."
967 :group 'org-link-store
968 :type 'regexp)
970 (defcustom org-context-in-file-links t
971 "Non-nil means, file links from `org-store-link' contain context.
972 A search string will be added to the file name with :: as separator and
973 used to find the context when the link is activated by the command
974 `org-open-at-point'.
975 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
976 negates this setting for the duration of the command."
977 :group 'org-link-store
978 :type 'boolean)
980 (defcustom org-keep-stored-link-after-insertion nil
981 "Non-nil means, keep link in list for entire session.
983 The command `org-store-link' adds a link pointing to the current
984 location to an internal list. These links accumulate during a session.
985 The command `org-insert-link' can be used to insert links into any
986 Org-mode file (offering completion for all stored links). When this
987 option is nil, every link which has been inserted once using \\[org-insert-link]
988 will be removed from the list, to make completing the unused links
989 more efficient."
990 :group 'org-link-store
991 :type 'boolean)
993 (defcustom org-usenet-links-prefer-google nil
994 "Non-nil means, `org-store-link' will create web links to Google groups.
995 When nil, Gnus will be used for such links.
996 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
997 negates this setting for the duration of the command."
998 :group 'org-link-store
999 :type 'boolean)
1001 (defgroup org-link-follow nil
1002 "Options concerning following links in Org-mode"
1003 :tag "Org Follow Link"
1004 :group 'org-link)
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-mouse-1-follows-link t
1019 "Non-nil means, mouse-1 on a link will follow the link.
1020 A longer mouse click will still set point. Does not wortk on XEmacs.
1021 Needs to be set before org.el is loaded."
1022 :group 'org-link-follow
1023 :type 'boolean)
1025 (defcustom org-mark-ring-length 4
1026 "Number of different positions to be recorded in the ring
1027 Changing this requires a restart of Emacs to work correctly."
1028 :group 'org-link-follow
1029 :type 'interger)
1031 (defcustom org-link-frame-setup
1032 '((vm . vm-visit-folder-other-frame)
1033 (gnus . gnus-other-frame)
1034 (file . find-file-other-window))
1035 "Setup the frame configuration for following links.
1036 When following a link with Emacs, it may often be useful to display
1037 this link in another window or frame. This variable can be used to
1038 set this up for the different types of links.
1039 For VM, use any of
1040 `vm-visit-folder'
1041 `vm-visit-folder-other-frame'
1042 For Gnus, use any of
1043 `gnus'
1044 `gnus-other-frame'
1045 For FILE, use any of
1046 `find-file'
1047 `find-file-other-window'
1048 `find-file-other-frame'
1049 For the calendar, use the variable `calendar-setup'.
1050 For BBDB, it is currently only possible to display the matches in
1051 another window."
1052 :group 'org-link-follow
1053 :type '(list
1054 (cons (const vm)
1055 (choice
1056 (const vm-visit-folder)
1057 (const vm-visit-folder-other-window)
1058 (const vm-visit-folder-other-frame)))
1059 (cons (const gnus)
1060 (choice
1061 (const gnus)
1062 (const gnus-other-frame)))
1063 (cons (const file)
1064 (choice
1065 (const find-file)
1066 (const find-file-other-window)
1067 (const find-file-other-frame)))))
1069 (defcustom org-display-internal-link-with-indirect-buffer nil
1070 "Non-nil means, use indirect buffer to display infile links.
1071 Activating internal links (from one location in a file to another location
1072 in the same file) normally just jumps to the location. When the link is
1073 activated with a C-u prefix (or with mouse-3), the link is displayed in
1074 another window. When this option is set, the other window actually displays
1075 an indirect buffer clone of the current buffer, to avoid any visibility
1076 changes to the current buffer."
1077 :group 'org-link-follow
1078 :type 'boolean)
1080 (defcustom org-open-non-existing-files nil
1081 "Non-nil means, `org-open-file' will open non-existing files.
1082 When nil, an error will be generated."
1083 :group 'org-link-follow
1084 :type 'boolean)
1086 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1087 "Function and arguments to call for following mailto links.
1088 This is a list with the first element being a lisp function, and the
1089 remaining elements being arguments to the function. In string arguments,
1090 %a will be replaced by the address, and %s will be replaced by the subject
1091 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1092 :group 'org-link-follow
1093 :type '(choice
1094 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1095 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1096 (const :tag "message-mail" (message-mail "%a" "%s"))
1097 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1099 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1100 "Non-nil means, ask for confirmation before executing shell links.
1101 Shell links can be dangerous, just thing about a link
1103 [[shell:rm -rf ~/*][Google Search]]
1105 This link would show up in your Org-mode document as \"Google Search\"
1106 but really it would remove your entire home directory.
1107 Therefore I *definitely* advise against setting this variable to nil.
1108 Just change it to `y-or-n-p' of you want to confirm with a single key press
1109 rather than having to type \"yes\"."
1110 :group 'org-link-follow
1111 :type '(choice
1112 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1113 (const :tag "with y-or-n (faster)" y-or-n-p)
1114 (const :tag "no confirmation (dangerous)" nil)))
1116 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1117 "Non-nil means, ask for confirmation before executing elisp links.
1118 Elisp links can be dangerous, just think about a link
1120 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1122 This link would show up in your Org-mode document as \"Google Search\"
1123 but really it would remove your entire home directory.
1124 Therefore I *definitely* advise against setting this variable to nil.
1125 Just change it to `y-or-n-p' of you want to confirm with a single key press
1126 rather than having to type \"yes\"."
1127 :group 'org-link-follow
1128 :type '(choice
1129 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1130 (const :tag "with y-or-n (faster)" y-or-n-p)
1131 (const :tag "no confirmation (dangerous)" nil)))
1133 (defconst org-file-apps-defaults-gnu
1134 '((remote . emacs)
1135 (t . mailcap))
1136 "Default file applications on a UNIX or GNU/Linux system.
1137 See `org-file-apps'.")
1139 (defconst org-file-apps-defaults-macosx
1140 '((remote . emacs)
1141 (t . "open %s")
1142 ("ps" . "gv %s")
1143 ("ps.gz" . "gv %s")
1144 ("eps" . "gv %s")
1145 ("eps.gz" . "gv %s")
1146 ("dvi" . "xdvi %s")
1147 ("fig" . "xfig %s"))
1148 "Default file applications on a MacOS X system.
1149 The system \"open\" is known as a default, but we use X11 applications
1150 for some files for which the OS does not have a good default.
1151 See `org-file-apps'.")
1153 (defconst org-file-apps-defaults-windowsnt
1154 (list
1155 '(remote . emacs)
1156 (cons t
1157 (list (if (featurep 'xemacs)
1158 'mswindows-shell-execute
1159 'w32-shell-execute)
1160 "open" 'file)))
1161 "Default file applications on a Windows NT system.
1162 The system \"open\" is used for most files.
1163 See `org-file-apps'.")
1165 (defcustom org-file-apps
1167 ("txt" . emacs)
1168 ("tex" . emacs)
1169 ("ltx" . emacs)
1170 ("org" . emacs)
1171 ("el" . emacs)
1172 ("bib" . emacs)
1174 "External applications for opening `file:path' items in a document.
1175 Org-mode uses system defaults for different file types, but
1176 you can use this variable to set the application for a given file
1177 extension. The entries in this list are cons cells where the car identifies
1178 files and the cdr the corresponding command. Possible values for the
1179 file identifier are
1180 \"ext\" A string identifying an extension
1181 `directory' Matches a directory
1182 `remote' Matches a remote file, accessible through tramp or efs.
1183 Remote files most likely should be visited through Emacs
1184 because external applications cannot handle such paths.
1185 t Default for all remaining files
1187 Possible values for the command are:
1188 `emacs' The file will be visited by the current Emacs process.
1189 `default' Use the default application for this file type.
1190 string A command to be executed by a shell; %s will be replaced
1191 by the path to the file.
1192 sexp A Lisp form which will be evaluated. The file path will
1193 be available in the Lisp variable `file'.
1194 For more examples, see the system specific constants
1195 `org-file-apps-defaults-macosx'
1196 `org-file-apps-defaults-windowsnt'
1197 `org-file-apps-defaults-gnu'."
1198 :group 'org-link-follow
1199 :type '(repeat
1200 (cons (choice :value ""
1201 (string :tag "Extension")
1202 (const :tag "Default for unrecognized files" t)
1203 (const :tag "Remote file" remote)
1204 (const :tag "Links to a directory" directory))
1205 (choice :value ""
1206 (const :tag "Visit with Emacs" emacs)
1207 (const :tag "Use system default" default)
1208 (string :tag "Command")
1209 (sexp :tag "Lisp form")))))
1211 (defcustom org-mhe-search-all-folders nil
1212 "Non-nil means, that the search for the mh-message will be extended to
1213 all folders if the message cannot be found in the folder given in the link.
1214 Searching all folders is very efficient with one of the search engines
1215 supported by MH-E, but will be slow with pick."
1216 :group 'org-link-follow
1217 :type 'boolean)
1219 (defgroup org-remember nil
1220 "Options concerning interaction with remember.el."
1221 :tag "Org Remember"
1222 :group 'org)
1224 (defcustom org-directory "~/org"
1225 "Directory with org files.
1226 This directory will be used as default to prompt for org files.
1227 Used by the hooks for remember.el."
1228 :group 'org-remember
1229 :type 'directory)
1231 (defcustom org-default-notes-file "~/.notes"
1232 "Default target for storing notes.
1233 Used by the hooks for remember.el. This can be a string, or nil to mean
1234 the value of `remember-data-file'.
1235 You can set this on a per-template basis with the variable
1236 `org-remember-templates'."
1237 :group 'org-remember
1238 :type '(choice
1239 (const :tag "Default from remember-data-file" nil)
1240 file))
1242 (defcustom org-remember-default-headline ""
1243 "The headline that should be the default location in the notes file.
1244 When filing remember notes, the cursor will start at that position.
1245 You can set this on a per-template basis with the variable
1246 `org-remember-templates'."
1247 :group 'org-remember
1248 :type 'string)
1250 (defcustom org-remember-templates nil
1251 "Templates for the creation of remember buffers.
1252 When nil, just let remember make the buffer.
1253 When not nil, this is a list of 4-element lists. In each entry, the first
1254 element is a character, a unique key to select this template.
1255 The second element is the template. The third element is optional and can
1256 specify a destination file for remember items created with this template.
1257 The default file is given by `org-default-notes-file'. An optional third
1258 element can specify the headline in that file that should be offered
1259 first when the user is asked to file the entry. The default headline is
1260 given in the variable `org-remember-default-headline'.
1262 The template specifies the structure of the remember buffer. It should have
1263 a first line starting with a star, to act as the org-mode headline.
1264 Furthermore, the following %-escapes will be replaced with content:
1266 %^{prompt} prompt the user for a string and replace this sequence with it.
1267 %t time stamp, date only
1268 %T time stamp with date and time
1269 %u, %U like the above, but inactive time stamps
1270 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1271 You may define a prompt like %^{Please specify birthday}t
1272 %n user name (taken from `user-full-name')
1273 %a annotation, normally the link created with org-store-link
1274 %i initial content, the region when remember is called with C-u.
1275 If %i is indented, the entire inserted text will be indented
1276 as well.
1278 %? After completing the template, position cursor here.
1280 Apart from these general escapes, you can access information specific to the
1281 link type that is created. For example, calling `remember' in emails or gnus
1282 will record the author and the subject of the message, which you can access
1283 with %:author and %:subject, respectively. Here is a complete list of what
1284 is recorded for each link type.
1286 Link type | Available information
1287 -------------------+------------------------------------------------------
1288 bbdb | %:type %:name %:company
1289 vm, wl, mh, rmail | %:type %:subject %:message-id
1290 | %:from %:fromname %:fromaddress
1291 | %:to %:toname %:toaddress
1292 | %:fromto (either \"to NAME\" or \"from NAME\")
1293 gnus | %:group, for messages also all email fields
1294 w3, w3m | %:type %:url
1295 info | %:type %:file %:node
1296 calendar | %:type %:date"
1297 :group 'org-remember
1298 :get (lambda (var) ; Make sure all entries have 4 elements
1299 (mapcar (lambda (x)
1300 (cond ((= (length x) 3) (append x '("")))
1301 ((= (length x) 2) (append x '("" "")))
1302 (t x)))
1303 (default-value var)))
1304 :type '(repeat
1305 :tag "enabled"
1306 (list :value (?a "\n" nil nil)
1307 (character :tag "Selection Key")
1308 (string :tag "Template")
1309 (file :tag "Destination file (optional)")
1310 (string :tag "Destination headline (optional)"))))
1312 (defcustom org-reverse-note-order nil
1313 "Non-nil means, store new notes at the beginning of a file or entry.
1314 When nil, new notes will be filed to the end of a file or entry."
1315 :group 'org-remember
1316 :type '(choice
1317 (const :tag "Reverse always" t)
1318 (const :tag "Reverse never" nil)
1319 (repeat :tag "By file name regexp"
1320 (cons regexp boolean))))
1322 (defgroup org-todo nil
1323 "Options concerning TODO items in Org-mode."
1324 :tag "Org TODO"
1325 :group 'org)
1327 (defgroup org-progress nil
1328 "Options concerning Progress logging in Org-mode."
1329 :tag "Org Progress"
1330 :group 'org-time)
1332 (defcustom org-todo-keywords '("TODO" "DONE")
1333 "List of TODO entry keywords.
1334 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1335 considered to mean that the entry is \"done\". All the other mean that
1336 action is required, and will make the entry show up in todo lists, diaries
1337 etc.
1338 The command \\[org-todo] cycles an entry through these states, and an
1339 additional state where no keyword is present. For details about this
1340 cycling, see also the variable `org-todo-interpretation'
1341 Changes become only effective after restarting Emacs.
1343 TODO keywords and interpretation can also be set on a per-file basis with
1344 the special #+SEQ_TODO and #+TYP_TODO lines."
1345 :group 'org-todo
1346 :group 'org-keywords
1347 :type '(repeat (string :tag "Keyword")))
1349 (defvar org-not-done-keywords nil)
1350 (make-variable-buffer-local 'org-not-done-keywords)
1351 (defvar org-done-keywords nil)
1352 (make-variable-buffer-local 'org-done-keywords)
1353 (defvar org-todo-heads nil)
1354 (make-variable-buffer-local 'org-todo-heads)
1355 (defvar org-todo-sets nil)
1356 (make-variable-buffer-local 'org-todo-sets)
1357 (defvar org-todo-kwd-alist nil)
1358 (make-variable-buffer-local 'org-todo-kwd-alist)
1360 (defcustom org-todo-interpretation 'sequence
1361 "Controls how TODO keywords are interpreted.
1362 This variable is only relevant if `org-todo-keywords' contains more than two
1363 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1365 When `sequence', \\[org-todo] will always switch to the next state in the
1366 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1367 to state when executed several times in direct succession. Otherwise, it
1368 switches directly to DONE from any state.
1369 See the manual for more information.
1371 TODO keywords and interpretation can also be set on a per-file basis with
1372 the special #+SEQ_TODO and #+TYP_TODO lines."
1373 :group 'org-todo
1374 :group 'org-keywords
1375 :type '(choice (const sequence)
1376 (const type)))
1378 (defcustom org-after-todo-state-change-hook nil
1379 "Hook which is run after the state of a TODO item was changed.
1380 The new state (a string with a TODO keyword, or nil) is available in the
1381 Lisp variable `state'."
1382 :group 'org-todo
1383 :type 'hook)
1385 (defcustom org-log-done nil
1386 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1387 When the state of an entry is changed from nothing to TODO, remove a previous
1388 closing date.
1390 This can also be a list of symbols indicating under which conditions
1391 the time stamp recording the action should be annotated with a short note.
1392 Valid members of this list are
1394 done Offer to record a note when marking entries done
1395 state Offer to record a note whenever changing the TODO state
1396 of an item. This is only relevant if TODO keywords are
1397 interpreted as sequence, see variable `org-todo-interpretation'.
1398 When `state' is set, this includes tracking `done'.
1399 clock-out Offer to record a note when clocking out of an item.
1401 A separate window will then pop up and allow you to type a note.
1402 After finishing with C-c C-c, the note will be added directly after the
1403 timestamp, as a plain list item. See also the variable
1404 `org-log-note-headings'.
1406 Logging can also be configured on a per-file basis by adding one of
1407 the following lines anywhere in the buffer:
1409 #+STARTUP: logdone
1410 #+STARTUP: nologging
1411 #+STARTUP: lognotedone
1412 #+STARTUP: lognotestate
1413 #+STARTUP: lognoteclock-out"
1414 :group 'org-todo
1415 :group 'org-progress
1416 :type '(choice
1417 (const :tag "off" nil)
1418 (const :tag "on" t)
1419 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1420 (const :tag "when item is marked DONE" done)
1421 (const :tag "when TODO state changes" state)
1422 (const :tag "when clocking out" clock-out))))
1424 (defcustom org-log-note-headings
1425 '((done . "CLOSING NOTE %t")
1426 (state . "State %-12s %t")
1427 (clock-out . ""))
1428 "Headings for notes added when clocking out or closing TODO items.
1429 The value is an alist, with the car being a sympol indicating the note
1430 context, and the cdr is the heading to be used. The heading may also be the
1431 empty string.
1432 %t in the heading will be replaced by a time stamp.
1433 %s will be replaced by the new TODO state, in double quotes.
1434 %u will be replaced by the user name.
1435 %U will be replaced by the full user name."
1436 :group 'org-todo
1437 :group 'org-progress
1438 :type '(list :greedy t
1439 (cons (const :tag "Heading when closing an item" done) string)
1440 (cons (const :tag
1441 "Heading when changing todo state (todo sequence only)"
1442 state) string)
1443 (cons (const :tag "Heading when clocking out" clock-out) string)))
1445 (defcustom org-allow-auto-repeat t
1446 "Non-nil means, find REPEAT cookies in entries and apply them.
1447 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1448 to repeat themselves shifted by a certain amount of time, each time an
1449 entry is marked DONE."
1450 :group 'org-todo
1451 :group 'org-progress
1452 :type 'boolean)
1454 (defcustom org-log-repeat t
1455 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1456 When nil, no note will be taken."
1457 :group 'org-todo
1458 :group 'org-progress
1459 :type 'boolean)
1461 (defgroup org-priorities nil
1462 "Priorities in Org-mode."
1463 :tag "Org Priorities"
1464 :group 'org-todo)
1466 (defcustom org-default-priority ?B
1467 "The default priority of TODO items.
1468 This is the priority an item get if no explicit priority is given."
1469 :group 'org-priorities
1470 :type 'character)
1472 (defcustom org-lowest-priority ?C
1473 "The lowest priority of TODO items. A character like ?A, ?B etc."
1474 :group 'org-priorities
1475 :type 'character)
1477 (defgroup org-time nil
1478 "Options concerning time stamps and deadlines in Org-mode."
1479 :tag "Org Time"
1480 :group 'org)
1482 (defcustom org-insert-labeled-timestamps-at-point nil
1483 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1484 When nil, these labeled time stamps are forces into the second line of an
1485 entry, just after the headline. When scheduling from the global TODO list,
1486 the time stamp will always be forced into the second line."
1487 :group 'org-time
1488 :type 'boolean)
1490 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1491 "Formats for `format-time-string' which are used for time stamps.
1492 It is not recommended to change this constant.")
1494 (defcustom org-time-stamp-rounding-minutes 0
1495 "Number of minutes to round time stamps to upon insertion.
1496 When zero, insert the time unmodified. Useful rounding numbers
1497 should be factors of 60, so for example 5, 10, 15.
1498 When this is not zero, you can still force an exact time-stamp by using
1499 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1500 :group 'org-time
1501 :type 'integer)
1503 (defcustom org-display-custom-times nil
1504 "Non-nil means, overlay custom formats over all time stamps.
1505 The formats are defined through the variable `org-time-stamp-custom-formats'.
1506 To turn this on on a per-file basis, insert anywhere in the file:
1507 #+STARTUP: customtime"
1508 :group 'org-time
1509 :set 'set-default
1510 :type 'sexp)
1511 (make-variable-buffer-local 'org-display-custom-times)
1513 (defcustom org-time-stamp-custom-formats
1514 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1515 "Custom formats for time stamps. See `format-time-string' for the syntax.
1516 These are overlayed over the default ISO format if the variable
1517 `org-display-custom-times' is set."
1518 :group 'org-time
1519 :type 'sexp)
1521 (defun org-time-stamp-format (&optional long inactive)
1522 "Get the right format for a time string."
1523 (let ((f (if long (cdr org-time-stamp-formats)
1524 (car org-time-stamp-formats))))
1525 (if inactive
1526 (concat "[" (substring f 1 -1) "]")
1527 f)))
1529 (defcustom org-deadline-warning-days 30
1530 "No. of days before expiration during which a deadline becomes active.
1531 This variable governs the display in sparse trees and in the agenda."
1532 :group 'org-time
1533 :type 'number)
1535 (defcustom org-popup-calendar-for-date-prompt t
1536 "Non-nil means, pop up a calendar when prompting for a date.
1537 In the calendar, the date can be selected with mouse-1. However, the
1538 minibuffer will also be active, and you can simply enter the date as well.
1539 When nil, only the minibuffer will be available."
1540 :group 'org-time
1541 :type 'boolean)
1543 (defcustom org-calendar-follow-timestamp-change t
1544 "Non-nil means, make the calendar window follow timestamp changes.
1545 When a timestamp is modified and the calendar window is visible, it will be
1546 moved to the new date."
1547 :group 'org-time
1548 :type 'boolean)
1550 (defgroup org-tags nil
1551 "Options concerning tags in Org-mode."
1552 :tag "Org Tags"
1553 :group 'org)
1555 (defcustom org-tag-alist nil
1556 "List of tags allowed in Org-mode files.
1557 When this list is nil, Org-mode will base TAG input on what is already in the
1558 buffer.
1559 The value of this variable is an alist, the car may be (and should) be a
1560 character that is used to select that tag through the fast-tag-selection
1561 interface. See the manual for details."
1562 :group 'org-tags
1563 :type '(repeat
1564 (choice
1565 (cons (string :tag "Tag name")
1566 (character :tag "Access char"))
1567 (const :tag "Start radio group" (:startgroup))
1568 (const :tag "End radio group" (:endgroup)))))
1570 (defcustom org-use-fast-tag-selection 'auto
1571 "Non-nil means, use fast tag selection scheme.
1572 This is a special interface to select and deselect tags with single keys.
1573 When nil, fast selection is never used.
1574 When the symbol `auto', fast selection is used if and only if selection
1575 characters for tags have been configured, either through the variable
1576 `org-tag-alist' or through a #+TAGS line in the buffer.
1577 When t, fast selection is always used and selection keys are assigned
1578 automatically if necessary."
1579 :group 'org-tags
1580 :type '(choice
1581 (const :tag "Always" t)
1582 (const :tag "Never" nil)
1583 (const :tag "When selection characters are configured" 'auto)))
1585 (defcustom org-fast-tag-selection-single-key nil
1586 "Non-nil means, fast tag selection exits after first change.
1587 When nil, you have to press RET to exit it.
1588 During fast tag selection, you can toggle this flag with `C-c'.
1589 This variable can also have the value `expert'. In this case, the window
1590 displaying the tags menu is not even shown, until you press C-c again."
1591 :group 'org-tags
1592 :type '(choice
1593 (const :tag "No" nil)
1594 (const :tag "Yes" t)
1595 (const :tag "Expert" expert)))
1597 (defcustom org-tags-column 48
1598 "The column to which tags should be indented in a headline.
1599 If this number is positive, it specifies the column. If it is negative,
1600 it means that the tags should be flushright to that column. For example,
1601 -79 works well for a normal 80 character screen."
1602 :group 'org-tags
1603 :type 'integer)
1605 (defcustom org-auto-align-tags t
1606 "Non-nil means, realign tags after pro/demotion of TODO state change.
1607 These operations change the length of a headline and therefore shift
1608 the tags around. With this options turned on, after each such operation
1609 the tags are again aligned to `org-tags-column'."
1610 :group 'org-tags
1611 :type 'boolean)
1613 (defcustom org-use-tag-inheritance t
1614 "Non-nil means, tags in levels apply also for sublevels.
1615 When nil, only the tags directly given in a specific line apply there.
1616 If you turn off this option, you very likely want to turn on the
1617 companion option `org-tags-match-list-sublevels'."
1618 :group 'org-tags
1619 :type 'boolean)
1621 (defcustom org-tags-match-list-sublevels nil
1622 "Non-nil means list also sublevels of headlines matching tag search.
1623 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1624 the sublevels of a headline matching a tag search often also match
1625 the same search. Listing all of them can create very long lists.
1626 Setting this variable to nil causes subtrees of a match to be skipped.
1627 This option is off by default, because inheritance in on. If you turn
1628 inheritance off, you very likely want to turn this option on.
1630 As a special case, if the tag search is restricted to TODO items, the
1631 value of this variable is ignored and sublevels are always checked, to
1632 make sure all corresponding TODO items find their way into the list."
1633 :group 'org-tags
1634 :type 'boolean)
1636 (defvar org-tags-history nil
1637 "History of minibuffer reads for tags.")
1638 (defvar org-last-tags-completion-table nil
1639 "The last used completion table for tags.")
1641 (defgroup org-agenda nil
1642 "Options concerning agenda views in Org-mode."
1643 :tag "Org Agenda"
1644 :group 'org)
1646 (defvar org-category nil
1647 "Variable used by org files to set a category for agenda display.
1648 Such files should use a file variable to set it, for example
1650 # -*- mode: org; org-category: \"ELisp\"
1652 or contain a special line
1654 #+CATEGORY: ELisp
1656 If the file does not specify a category, then file's base name
1657 is used instead.")
1658 (make-variable-buffer-local 'org-category)
1660 (defcustom org-agenda-files nil
1661 "The files to be used for agenda display.
1662 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1663 \\[org-remove-file]. You can also use customize to edit the list.
1665 If the value of the variable is not a list but a single file name, then
1666 the list of agenda files is actually stored and maintained in that file, one
1667 agenda file per line."
1668 :group 'org-agenda
1669 :type '(choice
1670 (repeat :tag "List of files" file)
1671 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1674 (defcustom org-agenda-confirm-kill 1
1675 "When set, remote killing from the agenda buffer needs confirmation.
1676 When t, a confirmation is always needed. When a number N, confirmation is
1677 only needed when the text to be killed contains more than N non-white lines."
1678 :group 'org-agenda
1679 :type '(choice
1680 (const :tag "Never" nil)
1681 (const :tag "Always" t)
1682 (number :tag "When more than N lines")))
1684 (defcustom org-calendar-to-agenda-key [?c]
1685 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1686 The command `org-calendar-goto-agenda' will be bound to this key. The
1687 default is the character `c' because then `c' can be used to switch back and
1688 forth between agenda and calendar."
1689 :group 'org-agenda
1690 :type 'sexp)
1692 (defgroup org-agenda-custom-commands nil
1693 "Options concerning agenda views in Org-mode."
1694 :tag "Org Agenda Custom Commands"
1695 :group 'org-agenda)
1697 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1698 "Custom commands for the agenda.
1699 These commands will be offered on the splash screen displayed by the
1700 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1702 (key type match options)
1704 key The key (a single char as a string) to be associated with the command.
1705 type The command type, any of the following symbols:
1706 todo Entries with a specific TODO keyword, in all agenda files.
1707 tags Tags match in all agenda files.
1708 tags-todo Tags match in all agenda files, TODO entries only.
1709 todo-tree Sparse tree of specific TODO keyword in *current* file.
1710 tags-tree Sparse tree with all tags matches in *current* file.
1711 occur-tree Occur sparse tree for *current* file.
1712 match What to search for:
1713 - a single keyword for TODO keyword searches
1714 - a tags match expression for tags searches
1715 - a regular expression for occur searches
1716 options A list of option setttings, similar to that in a let form, so like
1717 this: ((opt1 val1) (opt2 val2) ...)
1719 You can also define a set of commands, to create a composite agenda buffer.
1720 In this case, an entry looks like this:
1722 (key desc (cmd1 cmd2 ...) general-options)
1724 where
1726 desc A description string to be displayed in the dispatcher menu.
1727 cmd An agenda command, similar to the above. However, tree commands
1728 are no allowed, but instead you can get agenda and global todo list.
1729 So valid commands for a set are:
1730 (agenda)
1731 (alltodo)
1732 (stuck)
1733 (todo \"match\" options)
1734 (tags \"match\" options )
1735 (tags-todo \"match\" options)
1737 Each command can carry a list of options, and another set of options can be
1738 given for the whole set of commands. Individual command options take
1739 precedence over the general options."
1740 :group 'org-agenda-custom-commands
1741 :type '(repeat
1742 (choice
1743 (list :tag "Single command"
1744 (string :tag "Key")
1745 (choice
1746 (const :tag "Tags search (all agenda files)" tags)
1747 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1748 (const :tag "TODO keyword search (all agenda files)" todo)
1749 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1750 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1751 (const :tag "Occur tree (current buffer)" occur-tree)
1752 (symbol :tag "Other, user-defined function"))
1753 (string :tag "Match")
1754 (repeat :tag "Local options"
1755 (list (variable :tag "Option") (sexp :tag "Value"))))
1756 (list :tag "Command series, all agenda files"
1757 (string :tag "Key")
1758 (string :tag "Description")
1759 (repeat
1760 (choice
1761 (const :tag "Agenda" (agenda))
1762 (const :tag "TODO list" (alltodo))
1763 (const :tag "Stuck projects" (stuck))
1764 (list :tag "Tags search"
1765 (const :format "" tags)
1766 (string :tag "Match")
1767 (repeat :tag "Local options"
1768 (list (variable :tag "Option")
1769 (sexp :tag "Value"))))
1771 (list :tag "Tags search, TODO entries only"
1772 (const :format "" tags-todo)
1773 (string :tag "Match")
1774 (repeat :tag "Local options"
1775 (list (variable :tag "Option")
1776 (sexp :tag "Value"))))
1778 (list :tag "TODO keyword search"
1779 (const :format "" todo)
1780 (string :tag "Match")
1781 (repeat :tag "Local options"
1782 (list (variable :tag "Option")
1783 (sexp :tag "Value"))))
1785 (list :tag "Other, user-defined function"
1786 (symbol :tag "function")
1787 (string :tag "Match")
1788 (repeat :tag "Local options"
1789 (list (variable :tag "Option")
1790 (sexp :tag "Value"))))))
1792 (repeat :tag "General options"
1793 (list (variable :tag "Option")
1794 (sexp :tag "Value")))))))
1796 (defcustom org-stuck-projects
1797 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1798 "How to identify stuck projects.
1799 This is a list of three items:
1800 1. A tags/todo matcher string that is used to identify a project.
1801 The entire tree below a headline matched by this is considered a project.
1802 2. A list of TODO keywords itentifying non-stuck projects.
1803 If the project subtree contains any headline with one of these todo
1804 keywords, the project is consitered to be not stuck.
1805 3. A list of tags identifying non-stuck projects.
1806 If the project subtree contains any headline with one of these tags,
1807 the project is consitered to be not stuck.
1809 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1810 or `C-c a #' to produce the list."
1811 :group 'org-agenda-custom-commands
1812 :type '(list
1813 (string :tag "Tags/TODO match to identify a project")
1814 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1815 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1818 (defgroup org-agenda-skip nil
1819 "Options concerning skipping parts of agenda files."
1820 :tag "Org Agenda Skip"
1821 :group 'org-agenda)
1823 (defcustom org-agenda-todo-list-sublevels t
1824 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1825 When nil, the sublevels of a TODO entry are not checked, resulting in
1826 potentially much shorter TODO lists."
1827 :group 'org-agenda-skip
1828 :group 'org-todo
1829 :type 'boolean)
1831 (defcustom org-agenda-todo-ignore-scheduled nil
1832 "Non-nil means, don't show scheduled entries in the global todo list.
1833 The idea behind this is that by scheduling it, you have already taken care
1834 of this item."
1835 :group 'org-agenda-skip
1836 :group 'org-todo
1837 :type 'boolean)
1839 (defcustom org-agenda-todo-ignore-deadlines nil
1840 "Non-nil means, don't show near deadline entries in the global todo list.
1841 Near means closer than `org-deadline-warning-days' days.
1842 The idea behind this is that such items will appear in the agenda anyway."
1843 :group 'org-agenda-skip
1844 :group 'org-todo
1845 :type 'boolean)
1847 (defcustom org-agenda-skip-scheduled-if-done nil
1848 "Non-nil means don't show scheduled items in agenda when they are done.
1849 This is relevant for the daily/weekly agenda, not for the TODO list."
1850 :group 'org-agenda-skip
1851 :type 'boolean)
1853 (defcustom org-timeline-show-empty-dates 3
1854 "Non-nil means, `org-timeline' also shows dates without an entry.
1855 When nil, only the days which actually have entries are shown.
1856 When t, all days between the first and the last date are shown.
1857 When an integer, show also empty dates, but if there is a gap of more than
1858 N days, just insert a special line indicating the size of the gap."
1859 :group 'org-agenda-skip
1860 :type '(choice
1861 (const :tag "None" nil)
1862 (const :tag "All" t)
1863 (number :tag "at most")))
1866 (defgroup org-agenda-startup nil
1867 "Options concerning initial settings in the Agenda in Org Mode."
1868 :tag "Org Agenda Startup"
1869 :group 'org-agenda)
1871 (defcustom org-finalize-agenda-hook nil
1872 "Hook run just before displaying an agenda buffer."
1873 :group 'org-agenda-startup
1874 :type 'hook)
1876 (defcustom org-agenda-mouse-1-follows-link nil
1877 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1878 A longer mouse click will still set point. Does not wortk on XEmacs.
1879 Needs to be set before org.el is loaded."
1880 :group 'org-agenda-startup
1881 :type 'boolean)
1883 (defcustom org-agenda-start-with-follow-mode nil
1884 "The initial value of follwo-mode in a newly created agenda window."
1885 :group 'org-agenda-startup
1886 :type 'boolean)
1888 (defgroup org-agenda-windows nil
1889 "Options concerning the windows used by the Agenda in Org Mode."
1890 :tag "Org Agenda Windows"
1891 :group 'org-agenda)
1893 (defcustom org-agenda-window-setup 'reorganize-frame
1894 "How the agenda buffer should be displayed.
1895 Possible values for this option are:
1897 current-window Show agenda in the current window, keeping all other windows.
1898 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1899 other-window Use `switch-to-buffer-other-window' to display agenda.
1900 reorganize-frame Show only two windows on the current frame, the current
1901 window and the agenda.
1902 See also the variable `org-agenda-restore-windows-after-quit'."
1903 :group 'org-agenda-windows
1904 :type '(choice
1905 (const current-window)
1906 (const other-frame)
1907 (const other-window)
1908 (const reorganize-frame)))
1910 (defcustom org-agenda-restore-windows-after-quit nil
1911 "Non-nil means, restore window configuration open exiting agenda.
1912 Before the window configuration is changed for displaying the agenda,
1913 the current status is recorded. When the agenda is exited with
1914 `q' or `x' and this option is set, the old state is restored. If
1915 `org-agenda-window-setup' is `other-frame', the value of this
1916 option will be ignored.."
1917 :group 'org-agenda-windows
1918 :type 'boolean)
1920 (defcustom org-indirect-buffer-display 'other-window
1921 "How should indirect tree buffers be displayed?
1922 This applies to indirect buffers created with the commands
1923 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1924 Valid values are:
1925 current-window Display in the current window
1926 other-window Just display in another window.
1927 dedicated-frame Create one new frame, and re-use it each time.
1928 new-frame Make a new frame each time."
1929 :group 'org-structure
1930 :group 'org-agenda-windows
1931 :type '(choice
1932 (const :tag "In current window" current-window)
1933 (const :tag "In current frame, other window" other-window)
1934 (const :tag "Each time a new frame" new-frame)
1935 (const :tag "One dedicated frame" dedicated-frame)))
1937 (defgroup org-agenda-daily/weekly nil
1938 "Options concerning the daily/weekly agenda."
1939 :tag "Org Agenda Daily/Weekly"
1940 :group 'org-agenda)
1942 (defcustom org-agenda-ndays 7
1943 "Number of days to include in overview display.
1944 Should be 1 or 7."
1945 :group 'org-agenda-daily/weekly
1946 :type 'number)
1948 (defcustom org-agenda-start-on-weekday 1
1949 "Non-nil means, start the overview always on the specified weekday.
1950 0 denotes Sunday, 1 denotes Monday etc.
1951 When nil, always start on the current day."
1952 :group 'org-agenda-daily/weekly
1953 :type '(choice (const :tag "Today" nil)
1954 (number :tag "Weekday No.")))
1956 (defcustom org-agenda-show-all-dates t
1957 "Non-nil means, `org-agenda' shows every day in the selected range.
1958 When nil, only the days which actually have entries are shown."
1959 :group 'org-agenda-daily/weekly
1960 :type 'boolean)
1962 (defcustom org-agenda-date-format "%A %d %B %Y"
1963 "Format string for displaying dates in the agenda.
1964 Used by the daily/weekly agenda and by the timeline. This should be
1965 a format string understood by `format-time-string'.
1966 FIXME: Not used currently, because of timezone problem."
1967 :group 'org-agenda-daily/weekly
1968 :type 'string)
1970 (defcustom org-agenda-include-diary nil
1971 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1972 :group 'org-agenda-daily/weekly
1973 :type 'boolean)
1975 (defcustom org-agenda-include-all-todo nil
1976 "Set means weekly/daily agenda will always contain all TODO entries.
1977 The TODO entries will be listed at the top of the agenda, before
1978 the entries for specific days."
1979 :group 'org-agenda-daily/weekly
1980 :type 'boolean)
1982 (defgroup org-agenda-time-grid nil
1983 "Options concerning the time grid in the Org-mode Agenda."
1984 :tag "Org Agenda Time Grid"
1985 :group 'org-agenda)
1987 (defcustom org-agenda-use-time-grid t
1988 "Non-nil means, show a time grid in the agenda schedule.
1989 A time grid is a set of lines for specific times (like every two hours between
1990 8:00 and 20:00). The items scheduled for a day at specific times are
1991 sorted in between these lines.
1992 For details about when the grid will be shown, and what it will look like, see
1993 the variable `org-agenda-time-grid'."
1994 :group 'org-agenda-time-grid
1995 :type 'boolean)
1997 (defcustom org-agenda-time-grid
1998 '((daily today require-timed)
1999 "----------------"
2000 (800 1000 1200 1400 1600 1800 2000))
2002 "The settings for time grid for agenda display.
2003 This is a list of three items. The first item is again a list. It contains
2004 symbols specifying conditions when the grid should be displayed:
2006 daily if the agenda shows a single day
2007 weekly if the agenda shows an entire week
2008 today show grid on current date, independent of daily/weekly display
2009 require-timed show grid only if at least one item has a time specification
2011 The second item is a string which will be places behing the grid time.
2013 The third item is a list of integers, indicating the times that should have
2014 a grid line."
2015 :group 'org-agenda-time-grid
2016 :type
2017 '(list
2018 (set :greedy t :tag "Grid Display Options"
2019 (const :tag "Show grid in single day agenda display" daily)
2020 (const :tag "Show grid in weekly agenda display" weekly)
2021 (const :tag "Always show grid for today" today)
2022 (const :tag "Show grid only if any timed entries are present"
2023 require-timed)
2024 (const :tag "Skip grid times already present in an entry"
2025 remove-match))
2026 (string :tag "Grid String")
2027 (repeat :tag "Grid Times" (integer :tag "Time"))))
2029 (defgroup org-agenda-sorting nil
2030 "Options concerning sorting in the Org-mode Agenda."
2031 :tag "Org Agenda Sorting"
2032 :group 'org-agenda)
2034 (let ((sorting-choice
2035 '(choice
2036 (const time-up) (const time-down)
2037 (const category-keep) (const category-up) (const category-down)
2038 (const tag-down) (const tag-up)
2039 (const priority-up) (const priority-down))))
2041 (defcustom org-agenda-sorting-strategy
2042 '((agenda time-up category-keep priority-down)
2043 (todo category-keep priority-down)
2044 (tags category-keep priority-down))
2045 "Sorting structure for the agenda items of a single day.
2046 This is a list of symbols which will be used in sequence to determine
2047 if an entry should be listed before another entry. The following
2048 symbols are recognized:
2050 time-up Put entries with time-of-day indications first, early first
2051 time-down Put entries with time-of-day indications first, late first
2052 category-keep Keep the default order of categories, corresponding to the
2053 sequence in `org-agenda-files'.
2054 category-up Sort alphabetically by category, A-Z.
2055 category-down Sort alphabetically by category, Z-A.
2056 tag-up Sort alphabetically by last tag, A-Z.
2057 tag-down Sort alphabetically by last tag, Z-A.
2058 priority-up Sort numerically by priority, high priority last.
2059 priority-down Sort numerically by priority, high priority first.
2061 The different possibilities will be tried in sequence, and testing stops
2062 if one comparison returns a \"not-equal\". For example, the default
2063 '(time-up category-keep priority-down)
2064 means: Pull out all entries having a specified time of day and sort them,
2065 in order to make a time schedule for the current day the first thing in the
2066 agenda listing for the day. Of the entries without a time indication, keep
2067 the grouped in categories, don't sort the categories, but keep them in
2068 the sequence given in `org-agenda-files'. Within each category sort by
2069 priority.
2071 Leaving out `category-keep' would mean that items will be sorted across
2072 categories by priority."
2073 :group 'org-agenda-sorting
2074 :type `(choice
2075 (repeat :tag "General" ,sorting-choice)
2076 (list :tag "Individually"
2077 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2078 (repeat ,sorting-choice))
2079 (cons (const :tag "Strategy for TODO lists" todo)
2080 (repeat ,sorting-choice))
2081 (cons (const :tag "Strategy for Tags matches" tags)
2082 (repeat ,sorting-choice))))))
2084 (defcustom org-sort-agenda-notime-is-late t
2085 "Non-nil means, items without time are considered late.
2086 This is only relevant for sorting. When t, items which have no explicit
2087 time like 15:30 will be considered as 99:01, i.e. later than any items which
2088 do have a time. When nil, the default time is before 0:00. You can use this
2089 option to decide if the schedule for today should come before or after timeless
2090 agenda entries."
2091 :group 'org-agenda-sorting
2092 :type 'boolean)
2094 (defgroup org-agenda-prefix nil
2095 "Options concerning the entry prefix in the Org-mode agenda display."
2096 :tag "Org Agenda Prefix"
2097 :group 'org-agenda)
2099 (defcustom org-agenda-prefix-format
2100 '((agenda . " %-12:c%?-12t% s")
2101 (timeline . " % s")
2102 (todo . " %-12:c")
2103 (tags . " %-12:c"))
2104 "Format specifications for the prefix of items in the agenda views.
2105 An alist with four entries, for the different agenda types. The keys to the
2106 sublists are `agenda', `timeline', `todo', and `tags'. The values
2107 are format strings.
2108 This format works similar to a printf format, with the following meaning:
2110 %c the category of the item, \"Diary\" for entries from the diary, or
2111 as given by the CATEGORY keyword or derived from the file name.
2112 %T the *last* tag of the item. Last because inherited tags come
2113 first in the list.
2114 %t the time-of-day specification if one applies to the entry, in the
2115 format HH:MM
2116 %s Scheduling/Deadline information, a short string
2118 All specifiers work basically like the standard `%s' of printf, but may
2119 contain two additional characters: A question mark just after the `%' and
2120 a whitespace/punctuation character just before the final letter.
2122 If the first character after `%' is a question mark, the entire field
2123 will only be included if the corresponding value applies to the
2124 current entry. This is useful for fields which should have fixed
2125 width when present, but zero width when absent. For example,
2126 \"%?-12t\" will result in a 12 character time field if a time of the
2127 day is specified, but will completely disappear in entries which do
2128 not contain a time.
2130 If there is punctuation or whitespace character just before the final
2131 format letter, this character will be appended to the field value if
2132 the value is not empty. For example, the format \"%-12:c\" leads to
2133 \"Diary: \" if the category is \"Diary\". If the category were be
2134 empty, no additional colon would be interted.
2136 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2137 - Indent the line with two space characters
2138 - Give the category in a 12 chars wide field, padded with whitespace on
2139 the right (because of `-'). Append a colon if there is a category
2140 (because of `:').
2141 - If there is a time-of-day, put it into a 12 chars wide field. If no
2142 time, don't put in an empty field, just skip it (because of '?').
2143 - Finally, put the scheduling information and append a whitespace.
2145 As another example, if you don't want the time-of-day of entries in
2146 the prefix, you could use:
2148 (setq org-agenda-prefix-format \" %-11:c% s\")
2150 See also the variables `org-agenda-remove-times-when-in-prefix' and
2151 `org-agenda-remove-tags-when-in-prefix'."
2152 :type '(choice
2153 (string :tag "General format")
2154 (list :greedy t :tag "View dependent"
2155 (cons (const agenda) (string :tag "Format"))
2156 (cons (const timeline) (string :tag "Format"))
2157 (cons (const todo) (string :tag "Format"))
2158 (cons (const tags) (string :tag "Format"))))
2159 :group 'org-agenda-prefix)
2161 (defvar org-prefix-format-compiled nil
2162 "The compiled version of the most recently used prefix format.
2163 See the variable `org-agenda-prefix-format'.")
2165 (defcustom org-agenda-remove-times-when-in-prefix t
2166 "Non-nil means, remove duplicate time specifications in agenda items.
2167 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2168 time-of-day specification in a headline or diary entry is extracted and
2169 placed into the prefix. If this option is non-nil, the original specification
2170 \(a timestamp or -range, or just a plain time(range) specification like
2171 11:30-4pm) will be removed for agenda display. This makes the agenda less
2172 cluttered.
2173 The option can be t or nil. It may also be the symbol `beg', indicating
2174 that the time should only be removed what it is located at the beginning of
2175 the headline/diary entry."
2176 :group 'org-agenda-prefix
2177 :type '(choice
2178 (const :tag "Always" t)
2179 (const :tag "Never" nil)
2180 (const :tag "When at beginning of entry" beg)))
2182 (defcustom org-agenda-remove-tags-when-in-prefix nil
2183 "Non-nil means, remove the tags from the headline copy in the agenda.
2184 When this is the symbol `prefix', only remove tags when
2185 `org-agenda-prefix-format' contains a `%T' specifier."
2186 :group 'org-agenda-prefix
2187 :type '(choice
2188 (const :tag "Always" t)
2189 (const :tag "Never" nil)
2190 (const :tag "When prefix format contains %T" prefix)))
2192 (defcustom org-agenda-align-tags-to-column 65
2193 "Shift tags in agenda items to this column."
2194 :group 'org-agenda-prefix
2195 :type 'integer)
2197 (defgroup org-latex nil
2198 "Options for embedding LaTeX code into Org-mode"
2199 :tag "Org LaTeX"
2200 :group 'org)
2202 (defcustom org-format-latex-options
2203 '(:foreground "Black" :background "Transparent" :scale 1.0
2204 :matchers ("begin" "$" "$$" "\\(" "\\["))
2205 "Options for creating images from LaTeX fragments.
2206 This is a property list with the following properties:
2207 :foreground the foreground color, for example \"Black\".
2208 :background the background color, or \"Transparent\".
2209 :scale a scaling factor for the size of the images
2210 :matchers a list indicating which matchers should be used to
2211 find LaTeX fragments. Valid members of this list are:
2212 \"begin\" find environments
2213 \"$\" find math expressions surrounded by $...$
2214 \"$$\" find math expressions surrounded by $$....$$
2215 \"\\(\" find math expressions surrounded by \\(...\\)
2216 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2217 :group 'org-latex
2218 :type 'plist)
2220 (defgroup org-export nil
2221 "Options for exporting org-listings."
2222 :tag "Org Export"
2223 :group 'org)
2225 (defgroup org-export-general nil
2226 "General options for exporting Org-mode files."
2227 :tag "Org Export General"
2228 :group 'org-export)
2230 (defcustom org-export-publishing-directory "."
2231 "Path to the location where exported files should be located.
2232 This path may be relative to the directory where the Org-mode file lives.
2233 The default is to put them into the same directory as the Org-mode file.
2234 The variable may also be an alist with export types `:html', `:ascii',
2235 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2236 is relative, it is interpreted relative to the directory where the exported
2237 Org-mode files lives."
2238 :group 'org-export-general
2239 :type '(choice
2240 (directory)
2241 (repeat
2242 (cons
2243 (choice :tag "Type"
2244 (const :html) (const :ascii) (const :ical) (const :xoxo))
2245 (directory)))))
2247 (defcustom org-export-language-setup
2248 '(("en" "Author" "Date" "Table of Contents")
2249 ("cs" "Autor" "Datum" "Obsah")
2250 ("da" "Ophavsmand" "Dato" "Indhold")
2251 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2252 ("es" "Autor" "Fecha" "\xccndice")
2253 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2254 ("it" "Autore" "Data" "Indice")
2255 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2256 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2257 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2258 "Terms used in export text, translated to different languages.
2259 Use the variable `org-export-default-language' to set the language,
2260 or use the +OPTION lines for a per-file setting."
2261 :group 'org-export-general
2262 :type '(repeat
2263 (list
2264 (string :tag "HTML language tag")
2265 (string :tag "Author")
2266 (string :tag "Date")
2267 (string :tag "Table of Contents"))))
2269 (defcustom org-export-default-language "en"
2270 "The default language of HTML export, as a string.
2271 This should have an association in `org-export-language-setup'."
2272 :group 'org-export-general
2273 :type 'string)
2275 (defcustom org-export-skip-text-before-1st-heading t
2276 "Non-nil means, skip all text before the first headline when exporting.
2277 When nil, that text is exported as well."
2278 :group 'org-export-general
2279 :type 'boolean)
2281 (defcustom org-export-headline-levels 3
2282 "The last level which is still exported as a headline.
2283 Inferior levels will produce itemize lists when exported.
2284 Note that a numeric prefix argument to an exporter function overrides
2285 this setting.
2287 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2288 :group 'org-export-general
2289 :type 'number)
2291 (defcustom org-export-with-section-numbers t
2292 "Non-nil means, add section numbers to headlines when exporting.
2294 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2295 :group 'org-export-general
2296 :type 'boolean)
2298 (defcustom org-export-with-toc t
2299 "Non-nil means, create a table of contents in exported files.
2300 The TOC contains headlines with levels up to`org-export-headline-levels'.
2301 When an integer, include levels up to N in the toc, this may then be
2302 different from `org-export-headline-levels', but it will not be allowed
2303 to be larger than the number of headline levels.
2304 When nil, no table of contents is made.
2306 Headlines which contain any TODO items will be marked with \"(*)\" in
2307 ASCII export, and with red color in HTML output, if the option
2308 `org-export-mark-todo-in-toc' is set.
2310 In HTML output, the TOC will be clickable.
2312 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2313 or \"toc:3\"."
2314 :group 'org-export-general
2315 :type '(choice
2316 (const :tag "No Table of Contents" nil)
2317 (const :tag "Full Table of Contents" t)
2318 (integer :tag "TOC to level")))
2320 (defcustom org-export-mark-todo-in-toc nil
2321 "Non-nil means, mark TOC lines that contain any open TODO items."
2322 :group 'org-export-general
2323 :type 'boolean)
2325 (defcustom org-export-preserve-breaks nil
2326 "Non-nil means, preserve all line breaks when exporting.
2327 Normally, in HTML output paragraphs will be reformatted. In ASCII
2328 export, line breaks will always be preserved, regardless of this variable.
2330 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2331 :group 'org-export-general
2332 :type 'boolean)
2334 (defcustom org-export-with-archived-trees 'headline
2335 "Whether subtrees with the ARCHIVE tag should be exported.
2336 This can have three different values
2337 nil Do not export, pretend this tree is not present
2338 t Do export the entire tree
2339 headline Only export the headline, but skip the tree below it."
2340 :group 'org-export-general
2341 :group 'org-archive
2342 :type '(choice
2343 (const :tag "not at all" nil)
2344 (const :tag "headline only" 'headline)
2345 (const :tag "entirely" t)))
2347 (defcustom org-export-with-timestamps t
2348 "If nil, do not export time stamps and associated keywords."
2349 :group 'org-export-general
2350 :type 'boolean)
2352 (defcustom org-export-remove-timestamps-from-toc t
2353 "If nil, remove timestamps from the table of contents entries."
2354 :group 'org-export-general
2355 :type 'boolean)
2357 (defcustom org-export-with-tags 'not-in-toc
2358 "If nil, do not export tags, just remove them from headlines.
2359 If this is the symbol `not-in-toc', tags will be removed from table of
2360 contents entries, but still be shown in the headlines of the document."
2361 :group 'org-export-general
2362 :type '(choice
2363 (const :tag "Off" nil)
2364 (const :tag "Not in TOC" not-in-toc)
2365 (const :tag "On" t)))
2367 (defgroup org-export-translation nil
2368 "Options for translating special ascii sequences for the export backends."
2369 :tag "Org Export Translation"
2370 :group 'org-export)
2372 (defcustom org-export-with-emphasize t
2373 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2374 If the export target supports emphasizing text, the word will be
2375 typeset in bold, italic, or underlined, respectively. Works only for
2376 single words, but you can say: I *really* *mean* *this*.
2377 Not all export backends support this.
2379 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2380 :group 'org-export-translation
2381 :type 'boolean)
2383 (defcustom org-export-with-sub-superscripts t
2384 "Non-nil means, interpret \"_\" and \"^\" for export.
2385 When this option is turned on, you can use TeX-like syntax for sub- and
2386 superscripts. Several characters after \"_\" or \"^\" will be
2387 considered as a single item - so grouping with {} is normally not
2388 needed. For example, the following things will be parsed as single
2389 sub- or superscripts.
2391 10^24 or 10^tau several digits will be considered 1 item.
2392 10^-12 or 10^-tau a leading sign with digits or a word
2393 x^2-y^3 will be read as x^2 - y^3, because items are
2394 terminated by almost any nonword/nondigit char.
2395 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2397 Still, ambiguity is possible - so when in doubt use {} to enclose the
2398 sub/superscript. If you set this variable to the symbol `{}',
2399 the braces are *required* in order to trigger interpretations as
2400 sub/superscript. This can be helpful in documents that need \"_\"
2401 frequently in plain text.
2403 Not all export backends support this, but HTML does.
2405 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2406 :group 'org-export-translation
2407 :type '(choice
2408 (const :tag "Always interpret" t)
2409 (const :tag "Only with braces" {})
2410 (const :tag "Never interpret" nil)))
2412 (defcustom org-export-with-TeX-macros t
2413 "Non-nil means, interpret simple TeX-like macros when exporting.
2414 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2415 No only real TeX macros will work here, but the standard HTML entities
2416 for math can be used as macro names as well. For a list of supported
2417 names in HTML export, see the constant `org-html-entities'.
2418 Not all export backends support this.
2420 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2421 :group 'org-export-translation
2422 :group 'org-latex
2423 :type 'boolean)
2425 (defcustom org-export-with-LaTeX-fragments nil
2426 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2427 When set, the exporter will find LaTeX environments if the \\begin line is
2428 the first non-white thing on a line. It will also find the math delimiters
2429 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2430 display math.
2432 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2433 :group 'org-export-translation
2434 :group 'org-latex
2435 :type 'boolean)
2437 (defcustom org-export-with-fixed-width t
2438 "Non-nil means, lines starting with \":\" will be in fixed width font.
2439 This can be used to have pre-formatted text, fragments of code etc. For
2440 example:
2441 : ;; Some Lisp examples
2442 : (while (defc cnt)
2443 : (ding))
2444 will be looking just like this in also HTML. See also the QUOTE keyword.
2445 Not all export backends support this.
2447 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2448 :group 'org-export-translation
2449 :type 'boolean)
2451 (defcustom org-match-sexp-depth 3
2452 "Number of stacked braces for sub/superscript matching.
2453 This has to be set before loading org.el to be effective."
2454 :group 'org-export-translation
2455 :type 'integer)
2457 (defgroup org-export-tables nil
2458 "Options for exporting tables in Org-mode."
2459 :tag "Org Export Tables"
2460 :group 'org-export)
2462 (defcustom org-export-with-tables t
2463 "If non-nil, lines starting with \"|\" define a table.
2464 For example:
2466 | Name | Address | Birthday |
2467 |-------------+----------+-----------|
2468 | Arthur Dent | England | 29.2.2100 |
2470 Not all export backends support this.
2472 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2473 :group 'org-export-tables
2474 :type 'boolean)
2476 (defcustom org-export-highlight-first-table-line t
2477 "Non-nil means, highlight the first table line.
2478 In HTML export, this means use <th> instead of <td>.
2479 In tables created with table.el, this applies to the first table line.
2480 In Org-mode tables, all lines before the first horizontal separator
2481 line will be formatted with <th> tags."
2482 :group 'org-export-tables
2483 :type 'boolean)
2485 (defcustom org-export-table-remove-special-lines t
2486 "Remove special lines and marking characters in calculating tables.
2487 This removes the special marking character column from tables that are set
2488 up for spreadsheet calculations. It also removes the entire lines
2489 marked with `!', `_', or `^'. The lines with `$' are kept, because
2490 the values of constants may be useful to have."
2491 :group 'org-export-tables
2492 :type 'boolean)
2494 (defcustom org-export-prefer-native-exporter-for-tables nil
2495 "Non-nil means, always export tables created with table.el natively.
2496 Natively means, use the HTML code generator in table.el.
2497 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2498 the table does not use row- or column-spanning). This has the
2499 advantage, that the automatic HTML conversions for math symbols and
2500 sub/superscripts can be applied. Org-mode's HTML generator is also
2501 much faster."
2502 :group 'org-export-tables
2503 :type 'boolean)
2505 (defgroup org-export-ascii nil
2506 "Options specific for ASCII export of Org-mode files."
2507 :tag "Org Export ASCII"
2508 :group 'org-export)
2510 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2511 "Characters for underlining headings in ASCII export.
2512 In the given sequence, these characters will be used for level 1, 2, ..."
2513 :group 'org-export-ascii
2514 :type '(repeat character))
2516 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2517 "Bullet characters for headlines converted to lists in ASCII export.
2518 The first character is is used for the first lest level generated in this
2519 way, and so on. If there are more levels than characters given here,
2520 the list will be repeated.
2521 Note that plain lists will keep the same bullets as the have in the
2522 Org-mode file."
2523 :group 'org-export-ascii
2524 :type '(repeat character))
2526 (defgroup org-export-xml nil
2527 "Options specific for XML export of Org-mode files."
2528 :tag "Org Export XML"
2529 :group 'org-export)
2531 (defgroup org-export-html nil
2532 "Options specific for HTML export of Org-mode files."
2533 :tag "Org Export HTML"
2534 :group 'org-export)
2536 (defcustom org-export-html-style
2537 "<style type=\"text/css\">
2538 html {
2539 font-family: Times, serif;
2540 font-size: 12pt;
2542 .title { text-align: center; }
2543 .todo { color: red; }
2544 .done { color: green; }
2545 .timestamp { color: grey }
2546 .timestamp-kwd { color: CadetBlue }
2547 .tag { background-color:lightblue; font-weight:normal }
2548 .target { background-color: lavender; }
2549 pre {
2550 border: 1pt solid #AEBDCC;
2551 background-color: #F3F5F7;
2552 padding: 5pt;
2553 font-family: courier, monospace;
2555 table { border-collapse: collapse; }
2556 td, th {
2557 vertical-align: top;
2558 <!--border: 1pt solid #ADB9CC;-->
2560 </style>"
2561 "The default style specification for exported HTML files.
2562 Since there are different ways of setting style information, this variable
2563 needs to contain the full HTML structure to provide a style, including the
2564 surrounding HTML tags. The style specifications should include definitions
2565 for new classes todo, done, title, and deadline. For example, legal values
2566 would be:
2568 <style type=\"text/css\">
2569 p { font-weight: normal; color: gray; }
2570 h1 { color: black; }
2571 .title { text-align: center; }
2572 .todo, .deadline { color: red; }
2573 .done { color: green; }
2574 </style>
2576 or, if you want to keep the style in a file,
2578 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2580 As the value of this option simply gets inserted into the HTML <head> header,
2581 you can \"misuse\" it to add arbitrary text to the header."
2582 :group 'org-export-html
2583 :type 'string)
2585 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2586 "Format for typesetting the document title in HTML export."
2587 :group 'org-export-html
2588 :type 'string)
2590 (defcustom org-export-html-toplevel-hlevel 2
2591 "The <H> level for level 1 headings in HTML export."
2592 :group 'org-export-html
2593 :type 'string)
2595 (defcustom org-export-html-link-org-files-as-html t
2596 "Non-nil means, make file links to `file.org' point to `file.html'.
2597 When org-mode is exporting an org-mode file to HTML, links to
2598 non-html files are directly put into a href tag in HTML.
2599 However, links to other Org-mode files (recognized by the
2600 extension `.org.) should become links to the corresponding html
2601 file, assuming that the linked org-mode file will also be
2602 converted to HTML.
2603 When nil, the links still point to the plain `.org' file."
2604 :group 'org-export-html
2605 :type 'boolean)
2607 (defcustom org-export-html-inline-images 'maybe
2608 "Non-nil means, inline images into exported HTML pages.
2609 This is done using an <img> tag. When nil, an anchor with href is used to
2610 link to the image. If this option is `maybe', then images in links with
2611 an empty description will be inlined, while images with a description will
2612 be linked only."
2613 :group 'org-export-html
2614 :type '(choice (const :tag "Never" nil)
2615 (const :tag "Always" t)
2616 (const :tag "When there is no description" maybe)))
2618 ;; FIXME: rename
2619 (defcustom org-export-html-expand t
2620 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2621 When nil, these tags will be exported as plain text and therefore
2622 not be interpreted by a browser.
2624 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2625 :group 'org-export-html
2626 :type 'boolean)
2628 (defcustom org-export-html-table-tag
2629 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2630 "The HTML tag used to start a table.
2631 This must be a <table> tag, but you may change the options like
2632 borders and spacing."
2633 :group 'org-export-html
2634 :type 'string)
2636 (defcustom org-export-html-with-timestamp nil
2637 "If non-nil, write `org-export-html-html-helper-timestamp'
2638 into the exported HTML text. Otherwise, the buffer will just be saved
2639 to a file."
2640 :group 'org-export-html
2641 :type 'boolean)
2643 (defcustom org-export-html-html-helper-timestamp
2644 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2645 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2646 :group 'org-export-html
2647 :type 'string)
2649 (defgroup org-export-icalendar nil
2650 "Options specific for iCalendar export of Org-mode files."
2651 :tag "Org Export iCalendar"
2652 :group 'org-export)
2654 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2655 "The file name for the iCalendar file covering all agenda files.
2656 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2657 The file name should be absolute."
2658 :group 'org-export-icalendar
2659 :type 'file)
2661 (defcustom org-icalendar-include-todo nil
2662 "Non-nil means, export to iCalendar files should also cover TODO items."
2663 :group 'org-export-icalendar
2664 :type '(choice
2665 (const :tag "None" nil)
2666 (const :tag "Unfinished" t)
2667 (const :tag "All" all)))
2669 (defcustom org-icalendar-combined-name "OrgMode"
2670 "Calendar name for the combined iCalendar representing all agenda files."
2671 :group 'org-export-icalendar
2672 :type 'string)
2674 (defgroup org-font-lock nil
2675 "Font-lock settings for highlighting in Org-mode."
2676 :tag "Org Font Lock"
2677 :group 'org)
2679 (defcustom org-level-color-stars-only nil
2680 "Non-nil means fontify only the stars in each headline.
2681 When nil, the entire headline is fontified.
2682 Changing it requires restart of `font-lock-mode' to become effective
2683 also in regions already fontified."
2684 :group 'org-font-lock
2685 :type 'boolean)
2687 (defcustom org-hide-leading-stars nil
2688 "Non-nil means, hide the first N-1 stars in a headline.
2689 This works by using the face `org-hide' for these stars. This
2690 face is white for a light background, and black for a dark
2691 background. You may have to customize the face `org-hide' to
2692 make this work.
2693 Changing it requires restart of `font-lock-mode' to become effective
2694 also in regions already fontified.
2695 You may also set this on a per-file basis by adding one of the following
2696 lines to the buffer:
2698 #+STARTUP: hidestars
2699 #+STARTUP: showstars"
2700 :group 'org-font-lock
2701 :type 'boolean)
2703 (defcustom org-fontify-done-headline nil
2704 "Non-nil means, change the face of a headline if it is marked DONE.
2705 Normally, only the TODO/DONE keyword indicates the state of a headline.
2706 When this is non-nil, the headline after the keyword is set to the
2707 `org-headline-done' as an additional indication."
2708 :group 'org-font-lock
2709 :type 'boolean)
2711 (defcustom org-fontify-emphasized-text t
2712 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2713 Changing this variable requires a restart of Emacs to take effect."
2714 :group 'org-font-lock
2715 :type 'boolean)
2717 (defvar org-emph-re nil
2718 "Regular expression for matching emphasis.")
2719 (defvar org-emphasis-regexp-components) ; defined just below
2720 (defvar org-emphasis-alist) ; defined just below
2721 (defun org-set-emph-re (var val)
2722 "Set variable and compute the emphasis regular expression."
2723 (set var val)
2724 (when (and (boundp 'org-emphasis-alist)
2725 (boundp 'org-emphasis-regexp-components)
2726 org-emphasis-alist org-emphasis-regexp-components)
2727 (let* ((e org-emphasis-regexp-components)
2728 (pre (car e))
2729 (post (nth 1 e))
2730 (border (nth 2 e))
2731 (body (nth 3 e))
2732 (nl (nth 4 e))
2733 (stacked (nth 5 e))
2734 (body1 (concat body "*?"))
2735 (markers (mapconcat 'car org-emphasis-alist "")))
2736 ;; make sure special characters appear at the right position in the class
2737 (if (string-match "\\^" markers)
2738 (setq markers (concat (replace-match "" t t markers) "^")))
2739 (if (string-match "-" markers)
2740 (setq markers (concat (replace-match "" t t markers) "-")))
2741 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2742 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2743 (if (> nl 0)
2744 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2745 (int-to-string nl) "\\}")))
2746 ;; Make the regexp
2747 (setq org-emph-re
2748 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2749 "\\("
2750 "\\([" markers "]\\)"
2751 "\\("
2752 "[^" border markers "]"
2753 body1
2754 "[^" border markers "]"
2755 "\\)"
2756 "\\3\\)"
2757 "\\([" post (if stacked markers) "]\\|$\\)")))))
2759 (defcustom org-emphasis-regexp-components
2760 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2761 "Components used to build the reqular expression for emphasis.
2762 This is a list with 6 entries. Terminology: In an emphasis string
2763 like \" *strong word* \", we call the initial space PREMATCH, the final
2764 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2765 and \"trong wor\" is the body. The different components in this variable
2766 specify what is allowed/forbidden in each part:
2768 pre Chars allowed as prematch. Beginning of line will be allowed too.
2769 post Chars allowed as postmatch. End of line will be allowed too.
2770 border The chars *forbidden* as border characters. In addition to the
2771 characters given here, all marker characters are forbidden too.
2772 body-regexp A regexp like \".\" to match a body character. Don't use
2773 non-shy groups here, and don't allow newline here.
2774 newline The maximum number of newlines allowed in an emphasis exp.
2775 stacked Non-nil means, allow stacked styles. This works only in HTML
2776 export. When this is set, all marker characters (as given in
2777 `org-emphasis-alist') will be allowed as pre/post, aiding
2778 inside-out matching.
2779 Use customize to modify this, or restart Emacs after changing it."
2780 :group 'org-font-lock
2781 :set 'org-set-emph-re
2782 :type '(list
2783 (sexp :tag "Allowed chars in pre ")
2784 (sexp :tag "Allowed chars in post ")
2785 (sexp :tag "Forbidden chars in border ")
2786 (sexp :tag "Regexp for body ")
2787 (integer :tag "number of newlines allowed")
2788 (boolean :tag "Stacking allowed ")))
2790 (defcustom org-emphasis-alist
2791 '(("*" bold "<b>" "</b>")
2792 ("/" italic "<i>" "</i>")
2793 ("_" underline "<u>" "</u>")
2794 ("=" shadow "<code>" "</code>")
2795 ("+" (:strike-through t) "<del>" "</del>")
2797 "Special syntax for emphasized text.
2798 Text starting and ending with a special character will be emphasized, for
2799 example *bold*, _underlined_ and /italic/. This variable sets the marker
2800 characters, the face to bbe used by font-lock for highlighting in Org-mode
2801 Emacs buffers, and the HTML tags to be used for this.
2802 Use customize to modify this, or restart Emacs after changing it."
2803 :group 'org-font-lock
2804 :set 'org-set-emph-re
2805 :type '(repeat
2806 (list
2807 (string :tag "Marker character")
2808 (choice
2809 (face :tag "Font-lock-face")
2810 (plist :tag "Face property list"))
2811 (string :tag "HTML start tag")
2812 (string :tag "HTML end tag"))))
2814 ;;; The faces
2816 (defgroup org-faces nil
2817 "Faces in Org-mode."
2818 :tag "Org Faces"
2819 :group 'org-font-lock)
2821 (defun org-compatible-face (specs)
2822 "Make a compatible face specification.
2823 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2824 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2825 to the top of the list. The `min-colors' attribute will be removed from
2826 any other entries, and any resulting duplicates will be removed entirely."
2827 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2828 (let (r e a)
2829 (while (setq e (pop specs))
2830 (cond
2831 ((memq (car e) '(t default)) (push e r))
2832 ((setq a (member '(min-colors 8) (car e)))
2833 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2834 (cdr e)))))
2835 ((setq a (assq 'min-colors (car e)))
2836 (setq e (cons (delq a (car e)) (cdr e)))
2837 (or (assoc (car e) r) (push e r)))
2838 (t (or (assoc (car e) r) (push e r)))))
2839 (nreverse r))
2840 specs))
2842 (defface org-hide
2843 '((((background light)) (:foreground "white"))
2844 (((background dark)) (:foreground "black")))
2845 "Face used to hide leading stars in headlines.
2846 The forground color of this face should be equal to the background
2847 color of the frame."
2848 :group 'org-faces)
2850 (defface org-level-1 ;; font-lock-function-name-face
2851 (org-compatible-face
2852 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2853 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2854 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2855 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2856 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2857 (t (:bold t))))
2858 "Face used for level 1 headlines."
2859 :group 'org-faces)
2861 (defface org-level-2 ;; font-lock-variable-name-face
2862 (org-compatible-face
2863 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2864 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2865 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2866 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2867 (t (:bold t))))
2868 "Face used for level 2 headlines."
2869 :group 'org-faces)
2871 (defface org-level-3 ;; font-lock-keyword-face
2872 (org-compatible-face
2873 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2874 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2875 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2876 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2877 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2878 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2879 (t (:bold t))))
2880 "Face used for level 3 headlines."
2881 :group 'org-faces)
2883 (defface org-level-4 ;; font-lock-comment-face
2884 (org-compatible-face
2885 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2886 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2887 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2888 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2889 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2890 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2891 (t (:bold t))))
2892 "Face used for level 4 headlines."
2893 :group 'org-faces)
2895 (defface org-level-5 ;; font-lock-type-face
2896 (org-compatible-face
2897 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2898 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2899 (((class color) (min-colors 8)) (:foreground "green"))))
2900 "Face used for level 5 headlines."
2901 :group 'org-faces)
2903 (defface org-level-6 ;; font-lock-constant-face
2904 (org-compatible-face
2905 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2906 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2907 (((class color) (min-colors 8)) (:foreground "magenta"))))
2908 "Face used for level 6 headlines."
2909 :group 'org-faces)
2911 (defface org-level-7 ;; font-lock-builtin-face
2912 (org-compatible-face
2913 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2914 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2915 (((class color) (min-colors 8)) (:foreground "blue"))))
2916 "Face used for level 7 headlines."
2917 :group 'org-faces)
2919 (defface org-level-8 ;; font-lock-string-face
2920 (org-compatible-face
2921 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2922 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2923 (((class color) (min-colors 8)) (:foreground "green"))))
2924 "Face used for level 8 headlines."
2925 :group 'org-faces)
2927 (defface org-special-keyword ;; font-lock-string-face
2928 (org-compatible-face
2929 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2930 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2931 (t (:italic t))))
2932 "Face used for special keywords."
2933 :group 'org-faces)
2935 (defface org-warning ;; font-lock-warning-face
2936 (org-compatible-face
2937 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2938 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2939 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2940 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2941 (t (:bold t))))
2942 "Face for deadlines and TODO keywords."
2943 :group 'org-faces)
2945 (defface org-headline-done ;; font-lock-string-face
2946 (org-compatible-face
2947 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2948 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2949 (((class color) (min-colors 8) (background light)) (:bold nil))))
2950 "Face used to indicate that a headline is DONE.
2951 This face is only used if `org-fontify-done-headline' is set."
2952 :group 'org-faces)
2954 (defface org-archived ; similar to shadow
2955 (org-compatible-face
2956 '((((class color grayscale) (min-colors 88) (background light))
2957 (:foreground "grey50"))
2958 (((class color grayscale) (min-colors 88) (background dark))
2959 (:foreground "grey70"))
2960 (((class color) (min-colors 8) (background light))
2961 (:foreground "green"))
2962 (((class color) (min-colors 8) (background dark))
2963 (:foreground "yellow"))))
2964 "Face for headline with the ARCHIVE tag."
2965 :group 'org-faces)
2967 (defface org-link
2968 '((((class color) (background light)) (:foreground "Purple" :underline t))
2969 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2970 (t (:underline t)))
2971 "Face for links."
2972 :group 'org-faces)
2974 (defface org-date
2975 '((((class color) (background light)) (:foreground "Purple" :underline t))
2976 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2977 (t (:underline t)))
2978 "Face for links."
2979 :group 'org-faces)
2981 (defface org-tag
2982 '((t (:bold t)))
2983 "Face for tags."
2984 :group 'org-faces)
2986 (defface org-todo ;; font-lock-warning-face
2987 (org-compatible-face
2988 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2989 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2990 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2991 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2992 (t (:inverse-video t :bold t))))
2993 "Face for TODO keywords."
2994 :group 'org-faces)
2996 (defface org-done ;; font-lock-type-face
2997 (org-compatible-face
2998 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2999 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3000 (((class color) (min-colors 8)) (:foreground "green"))
3001 (t (:bold t))))
3002 "Face used for DONE."
3003 :group 'org-faces)
3005 (defface org-table ;; font-lock-function-name-face
3006 (org-compatible-face
3007 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3008 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3009 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3010 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3011 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3012 (((class color) (min-colors 8) (background dark)))))
3013 "Face used for tables."
3014 :group 'org-faces)
3016 (defface org-formula
3017 (org-compatible-face
3018 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3019 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3020 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3021 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3022 (t (:bold t :italic t))))
3023 "Face for formulas."
3024 :group 'org-faces)
3026 (defface org-scheduled-today
3027 (org-compatible-face
3028 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3029 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3030 (((class color) (min-colors 8)) (:foreground "green"))
3031 (t (:bold t :italic t))))
3032 "Face for items scheduled for a certain day."
3033 :group 'org-faces)
3035 (defface org-scheduled-previously
3036 (org-compatible-face
3037 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3038 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3039 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3040 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3041 (t (:bold t))))
3042 "Face for items scheduled previously, and not yet done."
3043 :group 'org-faces)
3045 (defface org-upcoming-deadline
3046 (org-compatible-face
3047 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3048 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3049 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3050 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3051 (t (:bold t))))
3052 "Face for items scheduled previously, and not yet done."
3053 :group 'org-faces)
3055 (defface org-time-grid ;; font-lock-variable-name-face
3056 (org-compatible-face
3057 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3058 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3059 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3060 "Face used for time grids."
3061 :group 'org-faces)
3063 (defconst org-level-faces
3064 '(org-level-1 org-level-2 org-level-3 org-level-4
3065 org-level-5 org-level-6 org-level-7 org-level-8
3067 (defconst org-n-levels (length org-level-faces))
3070 ;;; Variables for pre-computed regular expressions, all buffer local
3072 (defvar org-todo-regexp nil
3073 "Matches any of the TODO state keywords.")
3074 (make-variable-buffer-local 'org-todo-regexp)
3075 (defvar org-not-done-regexp nil
3076 "Matches any of the TODO state keywords except the last one.")
3077 (make-variable-buffer-local 'org-not-done-regexp)
3078 (defvar org-todo-line-regexp nil
3079 "Matches a headline and puts TODO state into group 2 if present.")
3080 (make-variable-buffer-local 'org-todo-line-regexp)
3081 (defvar org-todo-line-tags-regexp nil
3082 "Matches a headline and puts TODO state into group 2 if present.
3083 Also put tags into group 4 if tags are present.")
3084 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3085 (defvar org-nl-done-regexp nil
3086 "Matches newline followed by a headline with the DONE keyword.")
3087 (make-variable-buffer-local 'org-nl-done-regexp)
3088 (defvar org-looking-at-done-regexp nil
3089 "Matches the DONE keyword a point.")
3090 (make-variable-buffer-local 'org-looking-at-done-regexp)
3091 (defvar org-ds-keyword-length 12
3092 "Maximum length of the Deadline and SCHEDULED keywords.")
3093 (make-variable-buffer-local 'org-ds-keyword-length)
3094 (defvar org-deadline-regexp nil
3095 "Matches the DEADLINE keyword.")
3096 (make-variable-buffer-local 'org-deadline-regexp)
3097 (defvar org-deadline-time-regexp nil
3098 "Matches the DEADLINE keyword together with a time stamp.")
3099 (make-variable-buffer-local 'org-deadline-time-regexp)
3100 (defvar org-deadline-line-regexp nil
3101 "Matches the DEADLINE keyword and the rest of the line.")
3102 (make-variable-buffer-local 'org-deadline-line-regexp)
3103 (defvar org-scheduled-regexp nil
3104 "Matches the SCHEDULED keyword.")
3105 (make-variable-buffer-local 'org-scheduled-regexp)
3106 (defvar org-scheduled-time-regexp nil
3107 "Matches the SCHEDULED keyword together with a time stamp.")
3108 (make-variable-buffer-local 'org-scheduled-time-regexp)
3109 (defvar org-closed-time-regexp nil
3110 "Matches the CLOSED keyword together with a time stamp.")
3111 (make-variable-buffer-local 'org-closed-time-regexp)
3113 (defvar org-keyword-time-regexp nil
3114 "Matches any of the 4 keywords, together with the time stamp.")
3115 (make-variable-buffer-local 'org-keyword-time-regexp)
3116 (defvar org-keyword-time-not-clock-regexp nil
3117 "Matches any of the 3 keywords, together with the time stamp.")
3118 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3119 (defvar org-maybe-keyword-time-regexp nil
3120 "Matches a timestamp, possibly preceeded by a keyword.")
3121 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3123 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3124 rear-nonsticky t mouse-map t fontified t)
3125 "Properties to remove when a string without properties is wanted.")
3127 (defsubst org-match-string-no-properties (num &optional string)
3128 (if (featurep 'xemacs)
3129 (let ((s (match-string num string)))
3130 (remove-text-properties 0 (length s) org-rm-props s)
3132 (match-string-no-properties num string)))
3134 (defsubst org-no-properties (s)
3135 (remove-text-properties 0 (length s) org-rm-props s)
3138 (defsubst org-get-alist-option (option key)
3139 (cond ((eq key t) t)
3140 ((eq option t) t)
3141 ((assoc key option) (cdr (assoc key option)))
3142 (t (cdr (assq 'default option)))))
3144 (defsubst org-inhibit-invisibility ()
3145 "Modified `buffer-invisibility-spec' for Emacs 21.
3146 Some ops with invisible text do not work correctly on Emacs 21. For these
3147 we turn off invisibility temporarily. Use this in a `let' form."
3148 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3150 (defsubst org-set-local (var value)
3151 "Make VAR local in current buffer and set it to VALUE."
3152 (set (make-variable-buffer-local var) value))
3154 (defsubst org-mode-p ()
3155 "Check if the current buffer is in Org-mode."
3156 (eq major-mode 'org-mode))
3158 (defsubst org-last (list)
3159 "Return the last element of LIST."
3160 (car (last list)))
3162 (defun org-let (list &rest body)
3163 (eval (cons 'let (cons list body))))
3164 (put 'org-let 'lisp-indent-function 1)
3166 (defun org-let2 (list1 list2 &rest body)
3167 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3168 (put 'org-let2 'lisp-indent-function 2)
3169 (defconst org-startup-options
3170 '(("fold" org-startup-folded t)
3171 ("overview" org-startup-folded t)
3172 ("nofold" org-startup-folded nil)
3173 ("showall" org-startup-folded nil)
3174 ("content" org-startup-folded content)
3175 ("hidestars" org-hide-leading-stars t)
3176 ("showstars" org-hide-leading-stars nil)
3177 ("odd" org-odd-levels-only t)
3178 ("oddeven" org-odd-levels-only nil)
3179 ("align" org-startup-align-all-tables t)
3180 ("noalign" org-startup-align-all-tables nil)
3181 ("customtime" org-display-custom-times t)
3182 ("logging" org-log-done t)
3183 ("logdone" org-log-done t)
3184 ("nologging" org-log-done nil)
3185 ("lognotedone" org-log-done done push)
3186 ("lognotestate" org-log-done state push)
3187 ("lognoteclock-out" org-log-done clock-out push)
3188 ("constcgs" constants-unit-system cgs)
3189 ("constSI" constants-unit-system SI))
3190 "Variable associated with STARTUP options for org-mode.
3191 Each element is a list of three items: The startup options as written
3192 in the #+STARTUP line, the corresponding variable, and the value to
3193 set this variable to if the option is found. An optional forth element PUSH
3194 means to push this value onto the list in the variable.")
3196 (defun org-set-regexps-and-options ()
3197 "Precompute regular expressions for current buffer."
3198 (when (org-mode-p)
3199 (org-set-local 'org-todo-kwd-alist nil)
3200 (org-set-local 'org-todo-keywords nil)
3201 (org-set-local 'org-done-keywords nil)
3202 (org-set-local 'org-todo-heads nil)
3203 (org-set-local 'org-todo-sets nil)
3204 (let ((re (org-make-options-regexp
3205 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3206 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3207 (splitre "[ \t]+")
3208 kwds int key value cat arch tags links hw dw)
3209 (save-excursion
3210 (save-restriction
3211 (widen)
3212 (goto-char (point-min))
3213 (while (re-search-forward re nil t)
3214 (setq key (match-string 1) value (org-match-string-no-properties 2))
3215 (cond
3216 ((equal key "CATEGORY")
3217 (if (string-match "[ \t]+$" value)
3218 (setq value (replace-match "" t t value)))
3219 (setq cat (intern value)))
3220 ((equal key "SEQ_TODO")
3221 (push 'sequence int)
3222 (push (org-split-string value splitre) kwds))
3223 ((equal key "TYP_TODO")
3224 (push 'type int)
3225 (push (org-split-string value splitre) kwds))
3226 ((equal key "TAGS")
3227 (setq tags (append tags (org-split-string value splitre))))
3228 ((equal key "LINK")
3229 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3230 (push (cons (match-string 1 value)
3231 (org-trim (match-string 2 value)))
3232 links)))
3233 ((equal key "STARTUP")
3234 (let ((opts (org-split-string value splitre))
3235 l var val)
3236 (while (setq l (pop opts))
3237 (when (setq l (assoc l org-startup-options))
3238 (setq var (nth 1 l) val (nth 2 l))
3239 (if (not (nth 3 l))
3240 (set (make-local-variable var) val)
3241 (if (not (listp (symbol-value var)))
3242 (set (make-local-variable var) nil))
3243 (set (make-local-variable var) (symbol-value var))
3244 (add-to-list var val))))))
3245 ((equal key "ARCHIVE")
3246 (string-match " *$" value)
3247 (setq arch (replace-match "" t t value))
3248 (remove-text-properties 0 (length arch)
3249 '(face t fontified t) arch)))
3251 (and cat (org-set-local 'org-category cat))
3252 (and arch (org-set-local 'org-archive-location arch))
3253 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3254 ;; Process the TODO keywords
3255 (unless (and int kwds)
3256 ;; Use the global values as if they had been given locally.
3257 (setq kwds (list (default-value 'org-todo-keywords))
3258 int (list org-todo-interpretation)))
3259 (setq int (nreverse int) kwds (nreverse kwds))
3260 (let (i k)
3261 (while (setq i (pop int))
3262 (setq k (pop kwds) hw (car k) dw (org-last k))
3263 (add-to-list 'org-todo-heads hw 'append)
3264 (push k org-todo-sets)
3265 (push dw org-done-keywords)
3266 (mapc (lambda (x) (push (list x i hw dw) org-todo-kwd-alist)) k)
3267 (setq org-todo-keywords (append org-todo-keywords k)))
3268 (setq org-done-keywords (nreverse org-done-keywords)
3269 org-todo-sets (nreverse org-todo-sets)
3270 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3271 ;; Process the tags.
3272 (when tags
3273 (let (e tgs)
3274 (while (setq e (pop tags))
3275 (cond
3276 ((equal e "{") (push '(:startgroup) tgs))
3277 ((equal e "}") (push '(:endgroup) tgs))
3278 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3279 (push (cons (match-string 1 e)
3280 (string-to-char (match-string 2 e)))
3281 tgs))
3282 (t (push (list e) tgs))))
3283 (org-set-local 'org-tag-alist nil)
3284 (while (setq e (pop tgs))
3285 (or (and (stringp (car e))
3286 (assoc (car e) org-tag-alist))
3287 (push e org-tag-alist))))))
3289 ;; Compute the regular expressions and other local variables
3290 (if (not org-done-keywords)
3291 (setq org-done-keywords (list (org-last org-todo-keywords))))
3292 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3293 (length org-scheduled-string)))
3294 org-not-done-keywords
3295 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords))
3296 org-todo-regexp
3297 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3298 "\\|") "\\)\\>")
3299 org-not-done-regexp
3300 (concat "\\<\\("
3301 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3302 "\\)\\>")
3303 org-todo-line-regexp
3304 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3305 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3306 "\\)\\>\\)? *\\(.*\\)")
3307 org-nl-done-regexp
3308 (concat "[\r\n]\\*+[ \t]+"
3309 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3310 "\\)" "\\>")
3311 org-todo-line-tags-regexp
3312 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3313 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3314 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3315 org-looking-at-done-regexp
3316 (concat "^" "\\(?:"
3317 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3318 "\\>")
3319 org-deadline-regexp (concat "\\<" org-deadline-string)
3320 org-deadline-time-regexp
3321 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3322 org-deadline-line-regexp
3323 (concat "\\<\\(" org-deadline-string "\\).*")
3324 org-scheduled-regexp
3325 (concat "\\<" org-scheduled-string)
3326 org-scheduled-time-regexp
3327 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3328 org-closed-time-regexp
3329 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3330 org-keyword-time-regexp
3331 (concat "\\<\\(" org-scheduled-string
3332 "\\|" org-deadline-string
3333 "\\|" org-closed-string
3334 "\\|" org-clock-string "\\)"
3335 " *[[<]\\([^]>]+\\)[]>]")
3336 org-keyword-time-not-clock-regexp
3337 (concat "\\<\\(" org-scheduled-string
3338 "\\|" org-deadline-string
3339 "\\|" org-closed-string "\\)"
3340 " *[[<]\\([^]>]+\\)[]>]")
3341 org-maybe-keyword-time-regexp
3342 (concat "\\(\\<\\(" org-scheduled-string
3343 "\\|" org-deadline-string
3344 "\\|" org-closed-string
3345 "\\|" org-clock-string "\\)\\)?"
3346 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3348 (org-set-font-lock-defaults)))
3351 ;;; Some variables ujsed in various places
3353 (defvar org-window-configuration nil
3354 "Used in various places to store a window configuration.")
3355 (defvar org-finish-function nil
3356 "Function to be called when `C-c C-c' is used.
3357 This is for getting out of special buffers like remember.")
3359 ;;; Foreign variables, to inform the compiler
3361 ;; XEmacs only
3362 (defvar outline-mode-menu-heading)
3363 (defvar outline-mode-menu-show)
3364 (defvar outline-mode-menu-hide)
3365 (defvar zmacs-regions) ; XEmacs regions
3366 ;; Emacs only
3367 (defvar mark-active)
3369 ;; Packages that org-mode interacts with
3370 (defvar calc-embedded-close-formula)
3371 (defvar calc-embedded-open-formula)
3372 (defvar font-lock-unfontify-region-function)
3373 (defvar org-goto-start-pos)
3374 (defvar vm-message-pointer)
3375 (defvar vm-folder-directory)
3376 (defvar wl-summary-buffer-elmo-folder)
3377 (defvar wl-summary-buffer-folder-name)
3378 (defvar gnus-other-frame-object)
3379 (defvar gnus-group-name)
3380 (defvar gnus-article-current)
3381 (defvar w3m-current-url)
3382 (defvar w3m-current-title)
3383 (defvar mh-progs)
3384 (defvar mh-current-folder)
3385 (defvar mh-show-folder-buffer)
3386 (defvar mh-index-folder)
3387 (defvar mh-searcher)
3388 (defvar calendar-mode-map)
3389 (defvar Info-current-file)
3390 (defvar Info-current-node)
3391 (defvar texmathp-why)
3392 (defvar remember-save-after-remembering)
3393 (defvar remember-data-file)
3394 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3395 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3396 (defvar org-latex-regexps)
3397 (defvar constants-unit-system)
3399 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3401 ;; FIXME: Occasionally check by commenting these, to make sure
3402 ;; no other functions uses these, forgetting to let-bind them.
3403 (defvar entry)
3404 (defvar state)
3405 (defvar last-state)
3406 (defvar date)
3407 (defvar description)
3410 ;; Defined somewhere in this file, but used before definition.
3411 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3412 (defvar org-agenda-undo-list)
3413 (defvar org-agenda-pending-undo-list)
3414 (defvar org-agenda-overriding-header)
3415 (defvar orgtbl-mode)
3416 (defvar org-html-entities)
3417 (defvar org-struct-menu)
3418 (defvar org-org-menu)
3419 (defvar org-tbl-menu)
3420 (defvar org-agenda-keymap)
3421 (defvar org-category-table)
3423 ;;;; Emacs/XEmacs compatibility
3425 ;; Overlay compatibility functions
3426 (defun org-make-overlay (beg end &optional buffer)
3427 (if (featurep 'xemacs)
3428 (make-extent beg end buffer)
3429 (make-overlay beg end buffer)))
3430 (defun org-delete-overlay (ovl)
3431 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3432 (defun org-detach-overlay (ovl)
3433 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3434 (defun org-move-overlay (ovl beg end &optional buffer)
3435 (if (featurep 'xemacs)
3436 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3437 (move-overlay ovl beg end buffer)))
3438 (defun org-overlay-put (ovl prop value)
3439 (if (featurep 'xemacs)
3440 (set-extent-property ovl prop value)
3441 (overlay-put ovl prop value)))
3442 (defun org-overlay-display (ovl text &optional face evap)
3443 "Make overlay OVL display TEXT with face FACE."
3444 (if (featurep 'xemacs)
3445 (let ((gl (make-glyph text)))
3446 (and face (set-glyph-face gl face))
3447 (set-extent-property ovl 'invisible t)
3448 (set-extent-property ovl 'end-glyph gl))
3449 (overlay-put ovl 'display text)
3450 (if face (overlay-put ovl 'face face))
3451 (if evap (overlay-put ovl 'evaporate t))))
3452 (defun org-overlay-before-string (ovl text &optional face evap)
3453 "Make overlay OVL display TEXT with face FACE."
3454 (if (featurep 'xemacs)
3455 (let ((gl (make-glyph text)))
3456 (and face (set-glyph-face gl face))
3457 (set-extent-property ovl 'begin-glyph gl))
3458 (if face (org-add-props text nil 'face face))
3459 (overlay-put ovl 'before-string text)
3460 (if evap (overlay-put ovl 'evaporate t))))
3461 (defun org-overlay-get (ovl prop)
3462 (if (featurep 'xemacs)
3463 (extent-property ovl prop)
3464 (overlay-get ovl prop)))
3465 (defun org-overlays-at (pos)
3466 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3467 ;; FIXME: this is currently not used
3468 (defun org-overlays-in (&optional start end)
3469 (if (featurep 'xemacs)
3470 (extent-list nil start end)
3471 (overlays-in start end)))
3472 (defun org-overlay-start (o)
3473 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3474 (defun org-overlay-end (o)
3475 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3476 ;; FIXME: this is currently not used
3477 (defun org-find-overlays (prop &optional pos delete)
3478 "Find all overlays specifying PROP at POS or point.
3479 If DELETE is non-nil, delete all those overlays."
3480 (let ((overlays (org-overlays-at (or pos (point))))
3481 ov found)
3482 (while (setq ov (pop overlays))
3483 (if (org-overlay-get ov prop)
3484 (if delete (org-delete-overlay ov) (push ov found))))
3485 found))
3487 ;; Region compatibility
3489 (defun org-add-hook (hook function &optional append local)
3490 "Add-hook, compatible with both Emacsen."
3491 (if (and local (featurep 'xemacs))
3492 (add-local-hook hook function append)
3493 (add-hook hook function append local)))
3495 (defvar org-ignore-region nil
3496 "To temporarily disable the active region.")
3498 (defun org-region-active-p ()
3499 "Is `transient-mark-mode' on and the region active?
3500 Works on both Emacs and XEmacs."
3501 (if org-ignore-region
3503 (if (featurep 'xemacs)
3504 (and zmacs-regions (region-active-p))
3505 (and transient-mark-mode mark-active))))
3507 ;; Invisibility compatibility
3509 (defun org-add-to-invisibility-spec (arg)
3510 "Add elements to `buffer-invisibility-spec'.
3511 See documentation for `buffer-invisibility-spec' for the kind of elements
3512 that can be added."
3513 (cond
3514 ((fboundp 'add-to-invisibility-spec)
3515 (add-to-invisibility-spec arg))
3516 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3517 (setq buffer-invisibility-spec (list arg)))
3519 (setq buffer-invisibility-spec
3520 (cons arg buffer-invisibility-spec)))))
3522 (defun org-remove-from-invisibility-spec (arg)
3523 "Remove elements from `buffer-invisibility-spec'."
3524 (if (fboundp 'remove-from-invisibility-spec)
3525 (remove-from-invisibility-spec arg)
3526 (if (consp buffer-invisibility-spec)
3527 (setq buffer-invisibility-spec
3528 (delete arg buffer-invisibility-spec)))))
3530 ;; FIXME: this is currently not used
3531 (defun org-in-invisibility-spec-p (arg)
3532 "Is ARG a member of `buffer-invisibility-spec'?"
3533 (if (consp buffer-invisibility-spec)
3534 (member arg buffer-invisibility-spec)
3535 nil))
3537 ;;;; Define the Org-mode
3539 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3540 (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."))
3543 ;; We use a before-change function to check if a table might need
3544 ;; an update.
3545 (defvar org-table-may-need-update t
3546 "Indicates that a table might need an update.
3547 This variable is set by `org-before-change-function'.
3548 `org-table-align' sets it back to nil.")
3549 (defvar org-mode-map)
3550 (defvar org-mode-hook nil)
3551 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3552 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3555 ;;;###autoload
3556 (define-derived-mode org-mode outline-mode "Org"
3557 "Outline-based notes management and organizer, alias
3558 \"Carsten's outline-mode for keeping track of everything.\"
3560 Org-mode develops organizational tasks around a NOTES file which
3561 contains information about projects as plain text. Org-mode is
3562 implemented on top of outline-mode, which is ideal to keep the content
3563 of large files well structured. It supports ToDo items, deadlines and
3564 time stamps, which magically appear in the diary listing of the Emacs
3565 calendar. Tables are easily created with a built-in table editor.
3566 Plain text URL-like links connect to websites, emails (VM), Usenet
3567 messages (Gnus), BBDB entries, and any files related to the project.
3568 For printing and sharing of notes, an Org-mode file (or a part of it)
3569 can be exported as a structured ASCII or HTML file.
3571 The following commands are available:
3573 \\{org-mode-map}"
3575 ;; Get rid of Outline menus, they are not needed
3576 ;; Need to do this here because define-derived-mode sets up
3577 ;; the keymap so late. Still, it is a waste to call this each time
3578 ;; we switch another buffer into org-mode.
3579 (if (featurep 'xemacs)
3580 (when (boundp 'outline-mode-menu-heading)
3581 ;; Assume this is Greg's port, it used easymenu
3582 (easy-menu-remove outline-mode-menu-heading)
3583 (easy-menu-remove outline-mode-menu-show)
3584 (easy-menu-remove outline-mode-menu-hide))
3585 (define-key org-mode-map [menu-bar headings] 'undefined)
3586 (define-key org-mode-map [menu-bar hide] 'undefined)
3587 (define-key org-mode-map [menu-bar show] 'undefined))
3589 (easy-menu-add org-org-menu)
3590 (easy-menu-add org-tbl-menu)
3591 (org-install-agenda-files-menu)
3592 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3593 (org-add-to-invisibility-spec '(org-cwidth))
3594 (when (featurep 'xemacs)
3595 (org-set-local 'line-move-ignore-invisible t))
3596 (setq outline-regexp "\\*+")
3597 (setq outline-level 'org-outline-level)
3598 (when (and org-ellipsis (stringp org-ellipsis)
3599 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3600 (unless org-display-table
3601 (setq org-display-table (make-display-table)))
3602 (set-display-table-slot org-display-table
3603 4 (string-to-vector org-ellipsis))
3604 (setq buffer-display-table org-display-table))
3605 (org-set-regexps-and-options)
3606 ;; Calc embedded
3607 (org-set-local 'calc-embedded-open-mode "# ")
3608 (modify-syntax-entry ?# "<")
3609 (modify-syntax-entry ?@ "w")
3610 (if org-startup-truncated (setq truncate-lines t))
3611 (org-set-local 'font-lock-unfontify-region-function
3612 'org-unfontify-region)
3613 ;; Activate before-change-function
3614 (org-set-local 'org-table-may-need-update t)
3615 (org-add-hook 'before-change-functions 'org-before-change-function nil
3616 'local)
3617 ;; Check for running clock before killing a buffer
3618 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3619 ;; Paragraphs and auto-filling
3620 (org-set-autofill-regexps)
3621 (setq indent-line-function 'org-indent-line-function)
3622 (org-update-radio-target-regexp)
3624 ;; Comment characters
3625 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3626 (org-set-local 'comment-padding " ")
3628 ;; Make isearch reveal context
3629 (if (or (featurep 'xemacs)
3630 (not (boundp 'outline-isearch-open-invisible-function)))
3631 ;; Emacs 21 and XEmacs make use of the hook
3632 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3633 ;; Emacs 22 deals with this through a special variable
3634 (org-set-local 'outline-isearch-open-invisible-function
3635 (lambda (&rest ignore) (org-show-context 'isearch))))
3637 ;; If empty file that did not turn on org-mode automatically, make it to.
3638 (if (and org-insert-mode-line-in-empty-file
3639 (interactive-p)
3640 (= (point-min) (point-max)))
3641 (insert "# -*- mode: org -*-\n\n"))
3643 (unless org-inhibit-startup
3644 (when org-startup-align-all-tables
3645 (let ((bmp (buffer-modified-p)))
3646 (org-table-map-tables 'org-table-align)
3647 (set-buffer-modified-p bmp)))
3648 (cond
3649 ((eq org-startup-folded t)
3650 (org-cycle '(4)))
3651 ((eq org-startup-folded 'content)
3652 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3653 (org-cycle '(4)) (org-cycle '(4)))))))
3655 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3657 (defsubst org-call-with-arg (command arg)
3658 "Call COMMAND interactively, but pretend prefix are was ARG."
3659 (let ((current-prefix-arg arg)) (call-interactively command)))
3661 (defsubst org-current-line (&optional pos)
3662 (save-excursion
3663 (and pos (goto-char pos))
3664 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3666 (defun org-current-time ()
3667 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3668 (if (> org-time-stamp-rounding-minutes 0)
3669 (let ((r org-time-stamp-rounding-minutes)
3670 (time (decode-time)))
3671 (apply 'encode-time
3672 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3673 (nthcdr 2 time))))
3674 (current-time)))
3676 (defun org-add-props (string plist &rest props)
3677 "Add text properties to entire string, from beginning to end.
3678 PLIST may be a list of properties, PROPS are individual properties and values
3679 that will be added to PLIST. Returns the string that was modified."
3680 (add-text-properties
3681 0 (length string) (if props (append plist props) plist) string)
3682 string)
3683 (put 'org-add-props 'lisp-indent-function 2)
3686 ;;;; Font-Lock stuff, including the activators
3688 (defvar org-mouse-map (make-sparse-keymap))
3689 (define-key org-mouse-map
3690 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3691 (define-key org-mouse-map
3692 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3693 (when org-mouse-1-follows-link
3694 (define-key org-mouse-map [follow-link] 'mouse-face))
3695 (when org-tab-follows-link
3696 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3697 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3698 (when org-return-follows-link
3699 (define-key org-mouse-map [(return)] 'org-open-at-point)
3700 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3702 (require 'font-lock)
3704 (defconst org-non-link-chars "]\t\n\r<>")
3705 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3706 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3707 (defconst org-link-re-with-space
3708 (concat
3709 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3710 "\\([^" org-non-link-chars " ]"
3711 "[^" org-non-link-chars "]*"
3712 "[^" org-non-link-chars " ]\\)>?")
3713 "Matches a link with spaces, optional angular brackets around it.")
3715 (defconst org-link-re-with-space2
3716 (concat
3717 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3718 "\\([^" org-non-link-chars " ]"
3719 "[^]\t\n\r]*"
3720 "[^" org-non-link-chars " ]\\)>?")
3721 "Matches a link with spaces, optional angular brackets around it.")
3723 (defconst org-angle-link-re
3724 (concat
3725 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3726 "\\([^" org-non-link-chars " ]"
3727 "[^" org-non-link-chars "]*"
3728 "\\)>")
3729 "Matches link with angular brackets, spaces are allowed.")
3730 (defconst org-plain-link-re
3731 (concat
3732 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3733 "\\([^]\t\n\r<>,;() ]+\\)")
3734 "Matches plain link, without spaces.")
3736 (defconst org-bracket-link-regexp
3737 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3738 "Matches a link in double brackets.")
3740 (defconst org-bracket-link-analytic-regexp
3741 (concat
3742 "\\[\\["
3743 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3744 "\\([^]]+\\)"
3745 "\\]"
3746 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3747 "\\]"))
3748 ; 1: http:
3749 ; 2: http
3750 ; 3: path
3751 ; 4: [desc]
3752 ; 5: desc
3754 (defconst org-any-link-re
3755 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3756 org-angle-link-re "\\)\\|\\("
3757 org-plain-link-re "\\)")
3758 "Regular expression matching any link.")
3760 (defconst org-ts-lengths
3761 (cons (length (format-time-string (car org-time-stamp-formats)))
3762 (length (format-time-string (cdr org-time-stamp-formats))))
3763 "This holds the lengths of the two different time formats.")
3764 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3765 "Regular expression for fast time stamp matching.")
3766 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3767 "Regular expression for fast time stamp matching.")
3768 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3769 "Regular expression matching time strings for analysis.")
3770 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3771 "Regular expression matching time stamps, with groups.")
3772 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3773 "Regular expression matching time stamps (also [..]), with groups.")
3774 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3775 "Regular expression matching a time stamp range.")
3776 (defconst org-tr-regexp-both
3777 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3778 "Regular expression matching a time stamp range.")
3779 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3780 org-ts-regexp "\\)?")
3781 "Regular expression matching a time stamp or time stamp range.")
3782 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3783 org-ts-regexp-both "\\)?")
3784 "Regular expression matching a time stamp or time stamp range.
3785 The time stamps may be either active or inactive.")
3787 (defvar org-emph-face nil)
3789 (defun org-do-emphasis-faces (limit)
3790 "Run through the buffer and add overlays to links."
3791 (if (re-search-forward org-emph-re limit t)
3792 (progn
3793 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3794 'face
3795 (nth 1 (assoc (match-string 3)
3796 org-emphasis-alist)))
3797 (add-text-properties (match-beginning 2) (match-end 2)
3798 '(font-lock-multiline t))
3799 (backward-char 1)
3800 t)))
3802 (defun org-activate-plain-links (limit)
3803 "Run through the buffer and add overlays to links."
3804 (if (re-search-forward org-plain-link-re limit t)
3805 (progn
3806 (add-text-properties (match-beginning 0) (match-end 0)
3807 (list 'mouse-face 'highlight
3808 'rear-nonsticky t
3809 'keymap org-mouse-map
3811 t)))
3813 (defun org-activate-angle-links (limit)
3814 "Run through the buffer and add overlays to links."
3815 (if (re-search-forward org-angle-link-re limit t)
3816 (progn
3817 (add-text-properties (match-beginning 0) (match-end 0)
3818 (list 'mouse-face 'highlight
3819 'rear-nonsticky t
3820 'keymap org-mouse-map
3822 t)))
3824 (defmacro org-maybe-intangible (props)
3825 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3826 In emacs 21, invisible text is not avoided by the command loop, so the
3827 intangible property is needed to make sure point skips this text.
3828 In Emacs 22, this is not necessary. The intangible text property has
3829 led to problems with flyspell. These problems are fixed in flyspell.el,
3830 but we still avoid setting the property in Emacs 22 and later.
3831 We use a macro so that the test can happen at compilation time."
3832 (if (< emacs-major-version 22)
3833 `(append '(intangible t) ,props)
3834 props))
3836 (defun org-activate-bracket-links (limit)
3837 "Run through the buffer and add overlays to bracketed links."
3838 (if (re-search-forward org-bracket-link-regexp limit t)
3839 (let* ((help (concat "LINK: "
3840 (org-match-string-no-properties 1)))
3841 ;; FIXME: above we should remove the escapes.
3842 ;; but that requires another match, protecting match data,
3843 ;; a lot of overhead for font-lock.
3844 (ip (org-maybe-intangible
3845 (list 'invisible 'org-link 'rear-nonsticky t
3846 'keymap org-mouse-map 'mouse-face 'highlight
3847 'help-echo help)))
3848 (vp (list 'rear-nonsticky t
3849 'keymap org-mouse-map 'mouse-face 'highlight
3850 'help-echo help)))
3851 ;; We need to remove the invisible property here. Table narrowing
3852 ;; may have made some of this invisible.
3853 (remove-text-properties (match-beginning 0) (match-end 0)
3854 '(invisible nil))
3855 (if (match-end 3)
3856 (progn
3857 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3858 (add-text-properties (match-beginning 3) (match-end 3) vp)
3859 (add-text-properties (match-end 3) (match-end 0) ip))
3860 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3861 (add-text-properties (match-beginning 1) (match-end 1) vp)
3862 (add-text-properties (match-end 1) (match-end 0) ip))
3863 t)))
3865 (defun org-activate-dates (limit)
3866 "Run through the buffer and add overlays to dates."
3867 (if (re-search-forward org-tsr-regexp-both limit t)
3868 (progn
3869 (add-text-properties (match-beginning 0) (match-end 0)
3870 (list 'mouse-face 'highlight
3871 'rear-nonsticky t
3872 'keymap org-mouse-map))
3873 (when org-display-custom-times
3874 (if (match-end 3)
3875 (org-display-custom-time (match-beginning 3) (match-end 3)))
3876 (org-display-custom-time (match-beginning 1) (match-end 1)))
3877 t)))
3879 (defvar org-target-link-regexp nil
3880 "Regular expression matching radio targets in plain text.")
3881 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3882 "Regular expression matching a link target.")
3883 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3884 "Regular expression matching a link target.")
3886 (defun org-activate-target-links (limit)
3887 "Run through the buffer and add overlays to target matches."
3888 (when org-target-link-regexp
3889 (let ((case-fold-search t))
3890 (if (re-search-forward org-target-link-regexp limit t)
3891 (progn
3892 (add-text-properties (match-beginning 0) (match-end 0)
3893 (list 'mouse-face 'highlight
3894 'rear-nonsticky t
3895 'keymap org-mouse-map
3896 'help-echo "Radio target link"
3897 'org-linked-text t))
3898 t)))))
3900 (defun org-update-radio-target-regexp ()
3901 "Find all radio targets in this file and update the regular expression."
3902 (interactive)
3903 (when (memq 'radio org-activate-links)
3904 (setq org-target-link-regexp
3905 (org-make-target-link-regexp (org-all-targets 'radio)))
3906 (org-restart-font-lock)))
3908 (defun org-hide-wide-columns (limit)
3909 (let (s e)
3910 (setq s (text-property-any (point) (or limit (point-max))
3911 'org-cwidth t))
3912 (when s
3913 (setq e (next-single-property-change s 'org-cwidth))
3914 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3915 (goto-char e)
3916 t)))
3918 (defun org-restart-font-lock ()
3919 "Restart font-lock-mode, to force refontification."
3920 (when (and (boundp 'font-lock-mode) font-lock-mode)
3921 (font-lock-mode -1)
3922 (font-lock-mode 1)))
3924 (defun org-all-targets (&optional radio)
3925 "Return a list of all targets in this file.
3926 With optional argument RADIO, only find radio targets."
3927 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3928 rtn)
3929 (save-excursion
3930 (goto-char (point-min))
3931 (while (re-search-forward re nil t)
3932 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3933 rtn)))
3935 (defun org-make-target-link-regexp (targets)
3936 "Make regular expression matching all strings in TARGETS.
3937 The regular expression finds the targets also if there is a line break
3938 between words."
3939 (and targets
3940 (concat
3941 "\\<\\("
3942 (mapconcat
3943 (lambda (x)
3944 (while (string-match " +" x)
3945 (setq x (replace-match "\\s-+" t t x)))
3947 targets
3948 "\\|")
3949 "\\)\\>")))
3951 (defun org-activate-tags (limit)
3952 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3953 (progn
3954 (add-text-properties (match-beginning 1) (match-end 1)
3955 (list 'mouse-face 'highlight
3956 'rear-nonsticky t
3957 'keymap org-mouse-map))
3958 t)))
3960 (defun org-outline-level ()
3961 (save-excursion
3962 (looking-at outline-regexp)
3963 (if (match-beginning 1)
3964 (+ (org-get-string-indentation (match-string 1)) 1000)
3965 (- (match-end 0) (match-beginning 0)))))
3967 (defvar org-font-lock-keywords nil)
3969 (defun org-set-font-lock-defaults ()
3970 (let* ((em org-fontify-emphasized-text)
3971 (lk org-activate-links)
3972 (org-font-lock-extra-keywords
3973 ;; Headlines
3974 (list
3975 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3976 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3977 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3978 (1 'org-table))
3979 ;; Links
3980 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3981 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3982 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3983 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3984 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3985 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3986 '(org-hide-wide-columns (0 nil append))
3987 ;; TODO lines
3988 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3989 '(1 'org-todo t))
3990 ;; Priorities
3991 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3992 ;; Special keywords
3993 (list org-repeat-re '(0 'org-special-keyword t))
3994 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3995 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3996 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3997 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3998 ;; Emphasis
3999 (if em
4000 (if (featurep 'xemacs)
4001 '(org-do-emphasis-faces (0 nil append))
4002 '(org-do-emphasis-faces)))
4003 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4004 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
4005 2 'bold prepend)
4006 (if org-provide-checkbox-statistics
4007 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4008 (0 (org-get-checkbox-statistics-face) t)))
4009 ;; COMMENT
4010 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
4011 "\\|" org-quote-string "\\)\\>")
4012 '(1 'org-special-keyword t))
4013 '("^#.*" (0 'font-lock-comment-face t))
4014 ;; DONE
4015 (if org-fontify-done-headline
4016 (list (concat "^[*]+ +\\<\\("
4017 (mapconcat 'regexp-quote org-done-keywords "\\|")
4018 "\\)\\(.*\\)\\>")
4019 '(1 'org-done t) '(2 'org-headline-done t))
4020 (list (concat "^[*]+ +\\<\\("
4021 (mapconcat 'regexp-quote org-done-keywords "\\|")
4022 "\\)\\>")
4023 '(1 'org-done t)))
4024 ;; Table stuff
4025 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4026 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4027 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
4028 (if org-format-transports-properties-p
4029 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4030 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4032 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4033 ;; Now set the full font-lock-keywords
4034 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4035 (org-set-local 'font-lock-defaults
4036 '(org-font-lock-keywords t nil nil backward-paragraph))
4037 (kill-local-variable 'font-lock-keywords) nil))
4039 (defvar org-m nil)
4040 (defvar org-l nil)
4041 (defvar org-f nil)
4042 (defun org-get-level-face (n)
4043 "Get the right face for match N in font-lock matching of healdines."
4044 (setq org-l (- (match-end 2) (match-beginning 1)))
4045 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4046 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
4047 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
4048 (cond
4049 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4050 ((eq n 2) org-f)
4051 (t (if org-level-color-stars-only nil org-f))))
4053 (defun org-unfontify-region (beg end &optional maybe_loudly)
4054 "Remove fontification and activation overlays from links."
4055 (font-lock-default-unfontify-region beg end)
4056 (let* ((buffer-undo-list t)
4057 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4058 (inhibit-modification-hooks t)
4059 deactivate-mark buffer-file-name buffer-file-truename)
4060 (remove-text-properties beg end
4061 '(mouse-face t keymap t org-linked-text t
4062 rear-nonsticky t
4063 invisible t intangible t))))
4065 ;;;; Visibility cycling, including org-goto and indirect buffer
4067 ;;; Cycling
4069 (defvar org-cycle-global-status nil)
4070 (make-variable-buffer-local 'org-cycle-global-status)
4071 (defvar org-cycle-subtree-status nil)
4072 (make-variable-buffer-local 'org-cycle-subtree-status)
4074 ;;;###autoload
4075 (defun org-cycle (&optional arg)
4076 "Visibility cycling for Org-mode.
4078 - When this function is called with a prefix argument, rotate the entire
4079 buffer through 3 states (global cycling)
4080 1. OVERVIEW: Show only top-level headlines.
4081 2. CONTENTS: Show all headlines of all levels, but no body text.
4082 3. SHOW ALL: Show everything.
4084 - When point is at the beginning of a headline, rotate the subtree started
4085 by this line through 3 different states (local cycling)
4086 1. FOLDED: Only the main headline is shown.
4087 2. CHILDREN: The main headline and the direct children are shown.
4088 From this state, you can move to one of the children
4089 and zoom in further.
4090 3. SUBTREE: Show the entire subtree, including body text.
4092 - When there is a numeric prefix, go up to a heading with level ARG, do
4093 a `show-subtree' and return to the previous cursor position. If ARG
4094 is negative, go up that many levels.
4096 - When point is not at the beginning of a headline, execute
4097 `indent-relative', like TAB normally does. See the option
4098 `org-cycle-emulate-tab' for details.
4100 - Special case: if point is the the beginning of the buffer and there is
4101 no headline in line 1, this function will act as if called with prefix arg."
4102 (interactive "P")
4103 (let* ((outline-regexp
4104 (if (and (org-mode-p) org-cycle-include-plain-lists)
4105 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4106 outline-regexp))
4107 (bob-special (and org-cycle-global-at-bob (bobp)
4108 (not (looking-at outline-regexp))))
4109 (org-cycle-hook
4110 (if bob-special
4111 (delq 'org-optimize-window-after-visibility-change
4112 (copy-sequence org-cycle-hook))
4113 org-cycle-hook))
4114 (pos (point)))
4116 (if (or bob-special (equal arg '(4)))
4117 ;; special case: use global cycling
4118 (setq arg t))
4120 (cond
4122 ((org-at-table-p 'any)
4123 ;; Enter the table or move to the next field in the table
4124 (or (org-table-recognize-table.el)
4125 (progn
4126 (if arg (org-table-edit-field t)
4127 (org-table-justify-field-maybe)
4128 (call-interactively 'org-table-next-field)))))
4130 ((eq arg t) ;; Global cycling
4132 (cond
4133 ((and (eq last-command this-command)
4134 (eq org-cycle-global-status 'overview))
4135 ;; We just created the overview - now do table of contents
4136 ;; This can be slow in very large buffers, so indicate action
4137 (message "CONTENTS...")
4138 (org-content)
4139 (message "CONTENTS...done")
4140 (setq org-cycle-global-status 'contents)
4141 (run-hook-with-args 'org-cycle-hook 'contents))
4143 ((and (eq last-command this-command)
4144 (eq org-cycle-global-status 'contents))
4145 ;; We just showed the table of contents - now show everything
4146 (show-all)
4147 (message "SHOW ALL")
4148 (setq org-cycle-global-status 'all)
4149 (run-hook-with-args 'org-cycle-hook 'all))
4152 ;; Default action: go to overview
4153 (org-overview)
4154 (message "OVERVIEW")
4155 (setq org-cycle-global-status 'overview)
4156 (run-hook-with-args 'org-cycle-hook 'overview))))
4158 ((integerp arg)
4159 ;; Show-subtree, ARG levels up from here.
4160 (save-excursion
4161 (org-back-to-heading)
4162 (outline-up-heading (if (< arg 0) (- arg)
4163 (- (funcall outline-level) arg)))
4164 (org-show-subtree)))
4166 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4167 ;; At a heading: rotate between three different views
4168 (org-back-to-heading)
4169 (let ((goal-column 0) eoh eol eos)
4170 ;; First, some boundaries
4171 (save-excursion
4172 (org-back-to-heading)
4173 (save-excursion
4174 (beginning-of-line 2)
4175 (while (and (not (eobp)) ;; this is like `next-line'
4176 (get-char-property (1- (point)) 'invisible))
4177 (beginning-of-line 2)) (setq eol (point)))
4178 (outline-end-of-heading) (setq eoh (point))
4179 (org-end-of-subtree t)
4180 (skip-chars-forward " \t\n")
4181 (beginning-of-line 1) ; in case this is an item
4182 (setq eos (1- (point))))
4183 ;; Find out what to do next and set `this-command'
4184 (cond
4185 ((= eos eoh)
4186 ;; Nothing is hidden behind this heading
4187 (message "EMPTY ENTRY")
4188 (setq org-cycle-subtree-status nil))
4189 ((>= eol eos)
4190 ;; Entire subtree is hidden in one line: open it
4191 (org-show-entry)
4192 (show-children)
4193 (message "CHILDREN")
4194 (setq org-cycle-subtree-status 'children)
4195 (run-hook-with-args 'org-cycle-hook 'children))
4196 ((and (eq last-command this-command)
4197 (eq org-cycle-subtree-status 'children))
4198 ;; We just showed the children, now show everything.
4199 (org-show-subtree)
4200 (message "SUBTREE")
4201 (setq org-cycle-subtree-status 'subtree)
4202 (run-hook-with-args 'org-cycle-hook 'subtree))
4204 ;; Default action: hide the subtree.
4205 (hide-subtree)
4206 (message "FOLDED")
4207 (setq org-cycle-subtree-status 'folded)
4208 (run-hook-with-args 'org-cycle-hook 'folded)))))
4210 ;; TAB emulation
4211 (buffer-read-only (org-back-to-heading))
4213 ((org-try-cdlatex-tab))
4215 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4216 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4217 (or (and (eq org-cycle-emulate-tab 'white)
4218 (= (match-end 0) (point-at-eol)))
4219 (and (eq org-cycle-emulate-tab 'whitestart)
4220 (>= (match-end 0) pos))))
4222 (eq org-cycle-emulate-tab t))
4223 (if (and (looking-at "[ \n\r\t]")
4224 (string-match "^[ \t]*$" (buffer-substring
4225 (point-at-bol) (point))))
4226 (progn
4227 (beginning-of-line 1)
4228 (and (looking-at "[ \t]+") (replace-match ""))))
4229 (indent-relative))
4231 (t (save-excursion
4232 (org-back-to-heading)
4233 (org-cycle))))))
4235 ;;;###autoload
4236 (defun org-global-cycle (&optional arg)
4237 "Cycle the global visibility. For details see `org-cycle'."
4238 (interactive "P")
4239 (let ((org-cycle-include-plain-lists
4240 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4241 (if (integerp arg)
4242 (progn
4243 (show-all)
4244 (hide-sublevels arg)
4245 (setq org-cycle-global-status 'contents))
4246 (org-cycle '(4)))))
4248 (defun org-overview ()
4249 "Switch to overview mode, shoing only top-level headlines.
4250 Really, this shows all headlines with level equal or greater than the level
4251 of the first headline in the buffer. This is important, because if the
4252 first headline is not level one, then (hide-sublevels 1) gives confusing
4253 results."
4254 (interactive)
4255 (hide-sublevels (save-excursion
4256 (goto-char (point-min))
4257 (if (re-search-forward (concat "^" outline-regexp) nil t)
4258 (progn
4259 (goto-char (match-beginning 0))
4260 (funcall outline-level))
4261 1))))
4263 (defun org-content (&optional arg)
4264 "Show all headlines in the buffer, like a table of contents.
4265 With numerical argument N, show content up to level N."
4266 (interactive "P")
4267 (save-excursion
4268 ;; Visit all headings and show their offspring
4269 (and (integerp arg) (org-overview))
4270 (goto-char (point-max))
4271 (catch 'exit
4272 (while (and (progn (condition-case nil
4273 (outline-previous-visible-heading 1)
4274 (error (goto-char (point-min))))
4276 (looking-at outline-regexp))
4277 (if (integerp arg)
4278 (show-children (1- arg))
4279 (show-branches))
4280 (if (bobp) (throw 'exit nil))))))
4283 (defun org-optimize-window-after-visibility-change (state)
4284 "Adjust the window after a change in outline visibility.
4285 This function is the default value of the hook `org-cycle-hook'."
4286 (when (get-buffer-window (current-buffer))
4287 (cond
4288 ((eq state 'overview) (org-first-headline-recenter 1))
4289 ((eq state 'content) nil)
4290 ((eq state 'all) nil)
4291 ((eq state 'folded) nil)
4292 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4293 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4295 (defun org-subtree-end-visible-p ()
4296 "Is the end of the current subtree visible?"
4297 (pos-visible-in-window-p
4298 (save-excursion (org-end-of-subtree t) (point))))
4300 (defun org-first-headline-recenter (&optional N)
4301 "Move cursor to the first headline and recenter the headline.
4302 Optional argument N means, put the headline into the Nth line of the window."
4303 (goto-char (point-min))
4304 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4305 (beginning-of-line)
4306 (recenter (prefix-numeric-value N))))
4308 ;;; Org-goto
4310 (defvar org-goto-window-configuration nil)
4311 (defvar org-goto-marker nil)
4312 (defvar org-goto-map (make-sparse-keymap))
4313 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4314 (while (setq cmd (pop cmds))
4315 (substitute-key-definition cmd cmd org-goto-map global-map)))
4316 (define-key org-goto-map "\C-m" 'org-goto-ret)
4317 (define-key org-goto-map [(left)] 'org-goto-left)
4318 (define-key org-goto-map [(right)] 'org-goto-right)
4319 (define-key org-goto-map [(?q)] 'org-goto-quit)
4320 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4321 (define-key org-goto-map "\C-i" 'org-cycle)
4322 (define-key org-goto-map [(tab)] 'org-cycle)
4323 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4324 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4325 (define-key org-goto-map "n" 'outline-next-visible-heading)
4326 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4327 (define-key org-goto-map "f" 'outline-forward-same-level)
4328 (define-key org-goto-map "b" 'outline-backward-same-level)
4329 (define-key org-goto-map "u" 'outline-up-heading)
4330 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4331 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4332 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4333 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4334 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4335 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4336 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4338 (defconst org-goto-help
4339 "Select a location to jump to, press RET
4340 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4342 (defun org-goto ()
4343 "Go to a different location of the document, keeping current visibility.
4345 When you want to go to a different location in a document, the fastest way
4346 is often to fold the entire buffer and then dive into the tree. This
4347 method has the disadvantage, that the previous location will be folded,
4348 which may not be what you want.
4350 This command works around this by showing a copy of the current buffer in
4351 overview mode. You can dive into the tree in that copy, to find the
4352 location you want to reach. When pressing RET, the command returns to the
4353 original buffer in which the visibility is still unchanged. It then jumps
4354 to the new location, making it and the headline hierarchy above it visible."
4355 (interactive)
4356 (let* ((org-goto-start-pos (point))
4357 (selected-point
4358 (org-get-location (current-buffer) org-goto-help)))
4359 (if selected-point
4360 (progn
4361 (org-mark-ring-push org-goto-start-pos)
4362 (goto-char selected-point)
4363 (if (or (org-invisible-p) (org-invisible-p2))
4364 (org-show-context 'org-goto)))
4365 (error "Quit"))))
4367 (defvar org-selected-point nil) ; dynamically scoped parameter
4369 (defun org-get-location (buf help)
4370 "Let the user select a location in the Org-mode buffer BUF.
4371 This function uses a recursive edit. It returns the selected position
4372 or nil."
4373 (let (org-selected-point)
4374 (save-excursion
4375 (save-window-excursion
4376 (delete-other-windows)
4377 (switch-to-buffer (get-buffer-create "*org-goto*"))
4378 (with-output-to-temp-buffer "*Help*"
4379 (princ help))
4380 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4381 (setq buffer-read-only nil)
4382 (erase-buffer)
4383 (insert-buffer-substring buf)
4384 (let ((org-startup-truncated t)
4385 (org-startup-folded t)
4386 (org-startup-align-all-tables nil))
4387 (org-mode))
4388 (setq buffer-read-only t)
4389 (if (and (boundp 'org-goto-start-pos)
4390 (integer-or-marker-p org-goto-start-pos))
4391 (let ((org-show-hierarchy-above t)
4392 (org-show-siblings t)
4393 (org-show-following-heading t))
4394 (goto-char org-goto-start-pos)
4395 (and (org-invisible-p) (org-show-context)))
4396 (goto-char (point-min)))
4397 (org-beginning-of-line)
4398 (message "Select location and press RET")
4399 ;; now we make sure that during selection, ony very few keys work
4400 ;; and that it is impossible to switch to another window.
4401 (let ((gm (current-global-map))
4402 (overriding-local-map org-goto-map))
4403 (unwind-protect
4404 (progn
4405 (use-global-map org-goto-map)
4406 (recursive-edit))
4407 (use-global-map gm)))))
4408 (kill-buffer "*org-goto*")
4409 org-selected-point))
4411 (defun org-goto-ret (&optional arg)
4412 "Finish `org-goto' by going to the new location."
4413 (interactive "P")
4414 (setq org-selected-point (point)
4415 current-prefix-arg arg)
4416 (throw 'exit nil))
4418 (defun org-goto-left ()
4419 "Finish `org-goto' by going to the new location."
4420 (interactive)
4421 (if (org-on-heading-p)
4422 (progn
4423 (beginning-of-line 1)
4424 (setq org-selected-point (point)
4425 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4426 (throw 'exit nil))
4427 (error "Not on a heading")))
4429 (defun org-goto-right ()
4430 "Finish `org-goto' by going to the new location."
4431 (interactive)
4432 (if (org-on-heading-p)
4433 (progn
4434 (outline-end-of-subtree)
4435 (or (eobp) (forward-char 1))
4436 (setq org-selected-point (point)
4437 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4438 (throw 'exit nil))
4439 (error "Not on a heading")))
4441 (defun org-goto-quit ()
4442 "Finish `org-goto' without cursor motion."
4443 (interactive)
4444 (setq org-selected-point nil)
4445 (throw 'exit nil))
4447 ;;; Indirect buffer display of subtrees
4449 (defvar org-indirect-dedicated-frame nil
4450 "This is the frame being used for indirect tree display.")
4451 (defvar org-last-indirect-buffer nil)
4453 (defun org-tree-to-indirect-buffer (&optional arg)
4454 "Create indirect buffer and narrow it to current subtree.
4455 With numerical prefix ARG, go up to this level and then take that tree.
4456 If ARG is negative, go up that many levels.
4457 Normally this command removes the indirect buffer previously made
4458 with this command. However, when called with a C-u prefix, the last buffer
4459 is kept so that you can work with several indirect buffers at the same time.
4460 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4461 requests that a new frame be made for the new buffer, so that the dedicated
4462 frame is not changed."
4463 (interactive "P")
4464 (let ((cbuf (current-buffer))
4465 (cwin (selected-window))
4466 (pos (point))
4467 beg end level heading ibuf)
4468 (save-excursion
4469 (org-back-to-heading t)
4470 (when (numberp arg)
4471 (setq level (org-outline-level))
4472 (if (< arg 0) (setq arg (+ level arg)))
4473 (while (> (setq level (org-outline-level)) arg)
4474 (outline-up-heading 1 t)))
4475 (setq beg (point)
4476 heading (org-get-heading))
4477 (org-end-of-subtree t) (setq end (point)))
4478 (if (and (not arg)
4479 (buffer-live-p org-last-indirect-buffer))
4480 (kill-buffer org-last-indirect-buffer))
4481 (setq ibuf (org-get-indirect-buffer cbuf)
4482 org-last-indirect-buffer ibuf)
4483 (cond
4484 ((or (eq org-indirect-buffer-display 'new-frame)
4485 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4486 (select-frame (make-frame))
4487 (delete-other-windows)
4488 (switch-to-buffer ibuf)
4489 (org-set-frame-title heading))
4490 ((eq org-indirect-buffer-display 'dedicated-frame)
4491 (raise-frame
4492 (select-frame (or (and org-indirect-dedicated-frame
4493 (frame-live-p org-indirect-dedicated-frame)
4494 org-indirect-dedicated-frame)
4495 (setq org-indirect-dedicated-frame (make-frame)))))
4496 (delete-other-windows)
4497 (switch-to-buffer ibuf)
4498 (org-set-frame-title (concat "Indirect: " heading)))
4499 ((eq org-indirect-buffer-display 'current-window)
4500 (switch-to-buffer ibuf))
4501 ((eq org-indirect-buffer-display 'other-window)
4502 (pop-to-buffer ibuf))
4503 (t (error "Invalid value.")))
4504 (if (featurep 'xemacs)
4505 (save-excursion (org-mode) (turn-on-font-lock)))
4506 (narrow-to-region beg end)
4507 (show-all)
4508 (goto-char pos)
4509 (and (window-live-p cwin) (select-window cwin))))
4511 (defun org-get-indirect-buffer (&optional buffer)
4512 (setq buffer (or buffer (current-buffer)))
4513 (let ((n 1) (base (buffer-name buffer)) bname)
4514 (while (buffer-live-p
4515 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4516 (setq n (1+ n)))
4517 (condition-case nil
4518 (make-indirect-buffer buffer bname 'clone)
4519 (error (make-indirect-buffer buffer bname)))))
4521 (defun org-set-frame-title (title)
4522 "Set the title of the current frame to the string TITLE."
4523 ;; FIXME: how to name a single frame in XEmacs???
4524 (unless (featurep 'xemacs)
4525 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4527 ;;;; Structure editing
4529 ;;; Inserting headlines
4531 (defun org-insert-heading (&optional force-heading)
4532 "Insert a new heading or item with same depth at point.
4533 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4534 If point is at the beginning of a headline, insert a sibling before the
4535 current headline. If point is in the middle of a headline, split the headline
4536 at that position and make the rest of the headline part of the sibling below
4537 the current headline."
4538 (interactive "P")
4539 (if (= (buffer-size) 0)
4540 (insert "\n* ")
4541 (when (or force-heading (not (org-insert-item)))
4542 (let* ((head (save-excursion
4543 (condition-case nil
4544 (progn
4545 (org-back-to-heading)
4546 (match-string 0))
4547 (error "*"))))
4548 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4549 pos)
4550 (cond
4551 ((and (org-on-heading-p) (bolp)
4552 (or (bobp)
4553 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4554 (open-line (if blank 2 1)))
4555 ((and (bolp)
4556 (or (bobp)
4557 (save-excursion
4558 (backward-char 1) (not (org-invisible-p)))))
4559 nil)
4560 (t (newline (if blank 2 1))))
4561 (insert head) (just-one-space)
4562 (setq pos (point))
4563 (end-of-line 1)
4564 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4565 (run-hooks 'org-insert-heading-hook)))))
4568 (defun org-insert-todo-heading (arg)
4569 "Insert a new heading with the same level and TODO state as current heading.
4570 If the heading has no TODO state, or if the state is DONE, use the first
4571 state (TODO by default). Also with prefix arg, force first state."
4572 (interactive "P")
4573 (when (not (org-insert-item 'checkbox))
4574 (org-insert-heading)
4575 (save-excursion
4576 (org-back-to-heading)
4577 (outline-previous-heading)
4578 (looking-at org-todo-line-regexp))
4579 (if (or arg
4580 (not (match-beginning 2))
4581 (member (match-string 2) org-done-keywords))
4582 (insert (car org-todo-keywords) " ")
4583 (insert (match-string 2) " "))))
4585 ;;; Promotion and Demotion
4587 (defun org-promote-subtree ()
4588 "Promote the entire subtree.
4589 See also `org-promote'."
4590 (interactive)
4591 (save-excursion
4592 (org-map-tree 'org-promote))
4593 (org-fix-position-after-promote))
4595 (defun org-demote-subtree ()
4596 "Demote the entire subtree. See `org-demote'.
4597 See also `org-promote'."
4598 (interactive)
4599 (save-excursion
4600 (org-map-tree 'org-demote))
4601 (org-fix-position-after-promote))
4604 (defun org-do-promote ()
4605 "Promote the current heading higher up the tree.
4606 If the region is active in `transient-mark-mode', promote all headings
4607 in the region."
4608 (interactive)
4609 (save-excursion
4610 (if (org-region-active-p)
4611 (org-map-region 'org-promote (region-beginning) (region-end))
4612 (org-promote)))
4613 (org-fix-position-after-promote))
4615 (defun org-do-demote ()
4616 "Demote the current heading lower down the tree.
4617 If the region is active in `transient-mark-mode', demote all headings
4618 in the region."
4619 (interactive)
4620 (save-excursion
4621 (if (org-region-active-p)
4622 (org-map-region 'org-demote (region-beginning) (region-end))
4623 (org-demote)))
4624 (org-fix-position-after-promote))
4626 (defun org-fix-position-after-promote ()
4627 "Make sure that after pro/demotion cursor position is right."
4628 (let ((pos (point)))
4629 (when (save-excursion
4630 (beginning-of-line 1)
4631 (looking-at org-todo-line-regexp)
4632 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4633 (cond ((eobp) (insert " "))
4634 ((eolp) (insert " "))
4635 ((equal (char-after) ?\ ) (forward-char 1))))))
4637 (defun org-get-legal-level (level &optional change)
4638 "Rectify a level change under the influence of `org-odd-levels-only'
4639 LEVEL is a current level, CHANGE is by how much the level should be
4640 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4641 even level numbers will become the next higher odd number."
4642 (if org-odd-levels-only
4643 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4644 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4645 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4646 (max 1 (+ level change))))
4648 (defun org-promote ()
4649 "Promote the current heading higher up the tree.
4650 If the region is active in `transient-mark-mode', promote all headings
4651 in the region."
4652 (org-back-to-heading t)
4653 (let* ((level (save-match-data (funcall outline-level)))
4654 (up-head (make-string (org-get-legal-level level -1) ?*))
4655 (diff (abs (- level (length up-head)))))
4656 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4657 (replace-match up-head nil t)
4658 ;; Fixup tag positioning
4659 (and org-auto-align-tags (org-set-tags nil t))
4660 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4662 (defun org-demote ()
4663 "Demote the current heading lower down the tree.
4664 If the region is active in `transient-mark-mode', demote all headings
4665 in the region."
4666 (org-back-to-heading t)
4667 (let* ((level (save-match-data (funcall outline-level)))
4668 (down-head (make-string (org-get-legal-level level 1) ?*))
4669 (diff (abs (- level (length down-head)))))
4670 (replace-match down-head nil t)
4671 ;; Fixup tag positioning
4672 (and org-auto-align-tags (org-set-tags nil t))
4673 (if org-adapt-indentation (org-fixup-indentation diff))))
4675 (defun org-map-tree (fun)
4676 "Call FUN for every heading underneath the current one."
4677 (org-back-to-heading)
4678 (let ((level (funcall outline-level)))
4679 (save-excursion
4680 (funcall fun)
4681 (while (and (progn
4682 (outline-next-heading)
4683 (> (funcall outline-level) level))
4684 (not (eobp)))
4685 (funcall fun)))))
4687 (defun org-map-region (fun beg end)
4688 "Call FUN for every heading between BEG and END."
4689 (let ((org-ignore-region t))
4690 (save-excursion
4691 (setq end (copy-marker end))
4692 (goto-char beg)
4693 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4694 (< (point) end))
4695 (funcall fun))
4696 (while (and (progn
4697 (outline-next-heading)
4698 (< (point) end))
4699 (not (eobp)))
4700 (funcall fun)))))
4702 (defun org-fixup-indentation (diff)
4703 "Change the indentation in the current entry by DIFF
4704 However, if any line in the current entry has no indentation, or if it
4705 would end up with no indentation after the change, nothing at all is done."
4706 (save-excursion
4707 (let ((end (save-excursion (outline-next-heading)
4708 (point-marker)))
4709 (prohibit (if (> diff 0)
4710 "^\\S-"
4711 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4712 col)
4713 (unless (save-excursion (re-search-forward prohibit end t))
4714 (while (re-search-forward "^[ \t]+" end t)
4715 (goto-char (match-end 0))
4716 (setq col (current-column))
4717 (if (< diff 0) (replace-match ""))
4718 (indent-to (+ diff col))))
4719 (move-marker end nil))))
4721 (defun org-convert-to-odd-levels ()
4722 "Convert an org-mode file with all levels allowed to one with odd levels.
4723 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4724 level 5 etc."
4725 (interactive)
4726 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4727 (let ((org-odd-levels-only nil) n)
4728 (save-excursion
4729 (goto-char (point-min))
4730 (while (re-search-forward "^\\*\\*+" nil t)
4731 (setq n (1- (length (match-string 0))))
4732 (while (>= (setq n (1- n)) 0)
4733 (org-demote))
4734 (end-of-line 1))))))
4737 (defun org-convert-to-oddeven-levels ()
4738 "Convert an org-mode file with only odd levels to one with odd and even levels.
4739 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4740 section with an even level, conversion would destroy the structure of the file. An error
4741 is signaled in this case."
4742 (interactive)
4743 (goto-char (point-min))
4744 ;; First check if there are no even levels
4745 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4746 (org-show-context t)
4747 (error "Not all levels are odd in this file. Conversion not possible."))
4748 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4749 (let ((org-odd-levels-only nil) n)
4750 (save-excursion
4751 (goto-char (point-min))
4752 (while (re-search-forward "^\\*\\*+" nil t)
4753 (setq n (/ (length (match-string 0)) 2))
4754 (while (>= (setq n (1- n)) 0)
4755 (org-promote))
4756 (end-of-line 1))))))
4758 (defun org-tr-level (n)
4759 "Make N odd if required."
4760 (if org-odd-levels-only (1+ (/ n 2)) n))
4762 ;;; Vertical tree motion, cutting and pasting of subtrees
4764 (defun org-move-subtree-up (&optional arg)
4765 "Move the current subtree up past ARG headlines of the same level."
4766 (interactive "p")
4767 (org-move-subtree-down (- (prefix-numeric-value arg))))
4769 (defun org-move-subtree-down (&optional arg)
4770 "Move the current subtree down past ARG headlines of the same level."
4771 (interactive "p")
4772 (setq arg (prefix-numeric-value arg))
4773 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4774 'outline-get-last-sibling))
4775 (ins-point (make-marker))
4776 (cnt (abs arg))
4777 beg end txt folded)
4778 ;; Select the tree
4779 (org-back-to-heading)
4780 (setq beg (point))
4781 (save-match-data
4782 (save-excursion (outline-end-of-heading)
4783 (setq folded (org-invisible-p)))
4784 (outline-end-of-subtree))
4785 (outline-next-heading)
4786 (setq end (point))
4787 ;; Find insertion point, with error handling
4788 (goto-char beg)
4789 (while (> cnt 0)
4790 (or (and (funcall movfunc) (looking-at outline-regexp))
4791 (progn (goto-char beg)
4792 (error "Cannot move past superior level or buffer limit")))
4793 (setq cnt (1- cnt)))
4794 (if (> arg 0)
4795 ;; Moving forward - still need to move over subtree
4796 (progn (outline-end-of-subtree)
4797 (outline-next-heading)
4798 (if (not (or (looking-at (concat "^" outline-regexp))
4799 (bolp)))
4800 (newline))))
4801 (move-marker ins-point (point))
4802 (setq txt (buffer-substring beg end))
4803 (delete-region beg end)
4804 (insert txt)
4805 (goto-char ins-point)
4806 (if folded (hide-subtree))
4807 (move-marker ins-point nil)))
4809 (defvar org-subtree-clip ""
4810 "Clipboard for cut and paste of subtrees.
4811 This is actually only a copy of the kill, because we use the normal kill
4812 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4814 (defvar org-subtree-clip-folded nil
4815 "Was the last copied subtree folded?
4816 This is used to fold the tree back after pasting.")
4818 (defun org-cut-subtree ()
4819 "Cut the current subtree into the clipboard.
4820 This is a short-hand for marking the subtree and then cutting it."
4821 (interactive)
4822 (org-copy-subtree 'cut))
4824 (defun org-copy-subtree (&optional cut)
4825 "Cut the current subtree into the clipboard.
4826 This is a short-hand for marking the subtree and then copying it.
4827 If CUT is non-nil, actually cut the subtree."
4828 (interactive)
4829 (let (beg end folded)
4830 (org-back-to-heading)
4831 (setq beg (point))
4832 (save-match-data
4833 (save-excursion (outline-end-of-heading)
4834 (setq folded (org-invisible-p)))
4835 (outline-end-of-subtree))
4836 (if (equal (char-after) ?\n) (forward-char 1))
4837 (setq end (point))
4838 (goto-char beg)
4839 (when (> end beg)
4840 (setq org-subtree-clip-folded folded)
4841 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4842 (setq org-subtree-clip (current-kill 0))
4843 (message "%s: Subtree with %d characters"
4844 (if cut "Cut" "Copied")
4845 (length org-subtree-clip)))))
4847 (defun org-paste-subtree (&optional level tree)
4848 "Paste the clipboard as a subtree, with modification of headline level.
4849 The entire subtree is promoted or demoted in order to match a new headline
4850 level. By default, the new level is derived from the visible headings
4851 before and after the insertion point, and taken to be the inferior headline
4852 level of the two. So if the previous visible heading is level 3 and the
4853 next is level 4 (or vice versa), level 4 will be used for insertion.
4854 This makes sure that the subtree remains an independent subtree and does
4855 not swallow low level entries.
4857 You can also force a different level, either by using a numeric prefix
4858 argument, or by inserting the heading marker by hand. For example, if the
4859 cursor is after \"*****\", then the tree will be shifted to level 5.
4861 If you want to insert the tree as is, just use \\[yank].
4863 If optional TREE is given, use this text instead of the kill ring."
4864 (interactive "P")
4865 (unless (org-kill-is-subtree-p tree)
4866 (error
4867 (substitute-command-keys
4868 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4869 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4870 (^re (concat "^\\(" outline-regexp "\\)"))
4871 (re (concat "\\(" outline-regexp "\\)"))
4872 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4874 (old-level (if (string-match ^re txt)
4875 (- (match-end 0) (match-beginning 0))
4876 -1))
4877 (force-level (cond (level (prefix-numeric-value level))
4878 ((string-match
4879 ^re_ (buffer-substring (point-at-bol) (point)))
4880 (- (match-end 0) (match-beginning 0)))
4881 (t nil)))
4882 (previous-level (save-excursion
4883 (condition-case nil
4884 (progn
4885 (outline-previous-visible-heading 1)
4886 (if (looking-at re)
4887 (- (match-end 0) (match-beginning 0))
4889 (error 1))))
4890 (next-level (save-excursion
4891 (condition-case nil
4892 (progn
4893 (outline-next-visible-heading 1)
4894 (if (looking-at re)
4895 (- (match-end 0) (match-beginning 0))
4897 (error 1))))
4898 (new-level (or force-level (max previous-level next-level)))
4899 (shift (if (or (= old-level -1)
4900 (= new-level -1)
4901 (= old-level new-level))
4903 (- new-level old-level)))
4904 (shift1 shift)
4905 (delta (if (> shift 0) -1 1))
4906 (func (if (> shift 0) 'org-demote 'org-promote))
4907 (org-odd-levels-only nil)
4908 beg end)
4909 ;; Remove the forces level indicator
4910 (if force-level
4911 (delete-region (point-at-bol) (point)))
4912 ;; Make sure we start at the beginning of an empty line
4913 (if (not (bolp)) (insert "\n"))
4914 (if (not (looking-at "[ \t]*$"))
4915 (progn (insert "\n") (backward-char 1)))
4916 ;; Paste
4917 (setq beg (point))
4918 (if (string-match "[ \t\r\n]+\\'" txt)
4919 (setq txt (replace-match "\n" t t txt)))
4920 (insert txt)
4921 (setq end (point))
4922 (if (looking-at "[ \t\r\n]+")
4923 (replace-match "\n"))
4924 (goto-char beg)
4925 ;; Shift if necessary
4926 (if (= shift 0)
4927 (message "Pasted at level %d, without shift" new-level)
4928 (save-restriction
4929 (narrow-to-region beg end)
4930 (while (not (= shift 0))
4931 (org-map-region func (point-min) (point-max))
4932 (setq shift (+ delta shift)))
4933 (goto-char (point-min))
4934 (message "Pasted at level %d, with shift by %d levels"
4935 new-level shift1)))
4936 (if (and kill-ring
4937 (eq org-subtree-clip (current-kill 0))
4938 org-subtree-clip-folded)
4939 ;; The tree was folded before it was killed/copied
4940 (hide-subtree))))
4942 (defun org-kill-is-subtree-p (&optional txt)
4943 "Check if the current kill is an outline subtree, or a set of trees.
4944 Returns nil if kill does not start with a headline, or if the first
4945 headline level is not the largest headline level in the tree.
4946 So this will actually accept several entries of equal levels as well,
4947 which is OK for `org-paste-subtree'.
4948 If optional TXT is given, check this string instead of the current kill."
4949 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4950 (start-level (and kill
4951 (string-match (concat "\\`" outline-regexp) kill)
4952 (- (match-end 0) (match-beginning 0))))
4953 (re (concat "^" outline-regexp))
4954 (start 1))
4955 (if (not start-level)
4956 nil ;; does not even start with a heading
4957 (catch 'exit
4958 (while (setq start (string-match re kill (1+ start)))
4959 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4960 (throw 'exit nil)))
4961 t))))
4963 (defun org-narrow-to-subtree ()
4964 "Narrow buffer to the current subtree."
4965 (interactive)
4966 (save-excursion
4967 (narrow-to-region
4968 (progn (org-back-to-heading) (point))
4969 (progn (org-end-of-subtree t) (point)))))
4972 ;;; Outline Sorting
4974 (defun org-sort (with-case)
4975 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4976 (interactive "P")
4977 (if (org-at-table-p)
4978 (org-call-with-arg 'org-table-sort-lines with-case)
4979 (org-call-with-arg 'org-sort-entries with-case)))
4981 (defun org-sort-entries (&optional with-case sorting-type)
4982 "Sort entries on a certain level of an outline tree.
4983 If there is an active region, the entries in the region are sorted.
4984 Else, if the cursor is before the first entry, sort the top-level items.
4985 Else, the children of the entry at point are sorted.
4987 Sorting can be alphabetically, numerically, and by date/time as given by
4988 the first time stamp in the entry. The command prompts for the sorting
4989 type unless it has been given to the function through the SORTING-TYPE
4990 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4992 Comparing entries ignores case by default. However, with an optional argument
4993 WITH-CASE, the sorting considers case as well. With two prefix arguments
4994 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4995 (interactive "P")
4996 (let ((unique (equal with-case '(16)))
4997 start beg end entries stars re re2 p nentries (nremoved 0)
4998 last txt what)
4999 ;; Find beginning and end of region to sort
5000 (cond
5001 ((org-region-active-p)
5002 ;; we will sort the region
5003 (setq end (region-end)
5004 what "region")
5005 (goto-char (region-beginning))
5006 (if (not (org-on-heading-p)) (outline-next-heading))
5007 (setq start (point)))
5008 ((or (org-on-heading-p)
5009 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5010 ;; we will sort the children of the current headline
5011 (org-back-to-heading)
5012 (setq start (point) end (org-end-of-subtree) what "children")
5013 (goto-char start)
5014 (show-subtree)
5015 (outline-next-heading))
5017 ;; we will sort the top-level entries in this file
5018 (goto-char (point-min))
5019 (or (org-on-heading-p) (outline-next-heading))
5020 (setq start (point) end (point-max) what "top-level")
5021 (goto-char start)
5022 (show-all)))
5023 (setq beg (point))
5024 (if (>= (point) end) (error "Nothing to sort"))
5025 (looking-at "\\(\\*+\\)")
5026 (setq stars (match-string 1)
5027 re (concat "^" (regexp-quote stars) " +")
5028 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5029 txt (buffer-substring beg end))
5030 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5031 (if (and (not (equal stars "*")) (string-match re2 txt))
5032 (error "Region to sort contains a level above the first entry"))
5033 ;; Make a list that can be sorted.
5034 ;; The car is the string for comparison, the cdr is the subtree
5035 (message "Sorting entries...")
5036 (setq entries
5037 (mapcar
5038 (lambda (x)
5039 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5040 (cons (match-string 0 x) x))
5041 (org-split-string txt re)))
5043 ;; Sort the list
5044 (save-excursion
5045 (goto-char start)
5046 (setq entries (org-do-sort entries what with-case sorting-type)))
5048 ;; Delete the old stuff
5049 (goto-char beg)
5050 (kill-region beg end)
5051 (setq nentries (length entries))
5052 ;; Insert the sorted entries, and remove duplicates if this is required
5053 (while (setq p (pop entries))
5054 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5055 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5056 (insert stars " " (cdr p))))
5057 (goto-char start)
5058 (message "Sorting entries...done (%d entries%s)"
5059 nentries
5060 (if unique (format ", %d duplicates removed" nremoved) ""))))
5062 (defun org-do-sort (table what &optional with-case sorting-type)
5063 "Sort TABLE of WHAT according to SORTING-TYPE.
5064 The user will be prompted for the SORTING-TYPE if the call to this
5065 function does not specify it. WHAT is only for the prompt, to indicate
5066 what is being sorted. The sorting key will be extracted from
5067 the car of the elements of the table.
5068 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5069 (unless sorting-type
5070 (message
5071 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5072 what)
5073 (setq sorting-type (read-char-exclusive)))
5074 (let ((dcst (downcase sorting-type))
5075 extractfun comparefun)
5076 ;; Define the appropriate functions
5077 (cond
5078 ((= dcst ?n)
5079 (setq extractfun 'string-to-number
5080 comparefun (if (= dcst sorting-type) '< '>)))
5081 ((= dcst ?a)
5082 (setq extractfun (if with-case 'identity 'downcase)
5083 comparefun (if (= dcst sorting-type)
5084 'string<
5085 (lambda (a b) (and (not (string< a b))
5086 (not (string= a b)))))))
5087 ((= dcst ?t)
5088 (setq extractfun
5089 (lambda (x)
5090 (if (string-match org-ts-regexp x)
5091 (time-to-seconds
5092 (org-time-string-to-time (match-string 0 x)))
5094 comparefun (if (= dcst sorting-type) '< '>)))
5095 (t (error "Invalid sorting type `%c'" sorting-type)))
5097 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5098 table)
5099 (lambda (a b) (funcall comparefun (car a) (car b))))))
5101 ;;;; Plain list items, including checkboxes
5103 ;;; Plain list items
5105 (defun org-at-item-p ()
5106 "Is point in a line starting a hand-formatted item?"
5107 (let ((llt org-plain-list-ordered-item-terminator))
5108 (save-excursion
5109 (goto-char (point-at-bol))
5110 (looking-at
5111 (cond
5112 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5113 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5114 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5115 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5118 (defun org-in-item-p ()
5119 "It the cursor inside a plain list item.
5120 Does not have to be the first line."
5121 (save-excursion
5122 (condition-case nil
5123 (progn
5124 (org-beginning-of-item)
5125 (org-at-item-p)
5127 (error nil))))
5129 (defun org-insert-item (&optional checkbox)
5130 "Insert a new item at the current level.
5131 Return t when things worked, nil when we are not in an item."
5132 (when (save-excursion
5133 (condition-case nil
5134 (progn
5135 (org-beginning-of-item)
5136 (org-at-item-p)
5137 (if (org-invisible-p) (error "Invisible item"))
5139 (error nil)))
5140 (let* ((bul (match-string 0))
5141 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5142 (match-end 0)))
5143 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5144 pos)
5145 (cond
5146 ((and (org-at-item-p) (<= (point) eow))
5147 ;; before the bullet
5148 (beginning-of-line 1)
5149 (open-line (if blank 2 1)))
5150 ((<= (point) eow)
5151 (beginning-of-line 1))
5152 (t (newline (if blank 2 1))))
5153 (insert bul (if checkbox "[ ]" ""))
5154 (just-one-space)
5155 (setq pos (point))
5156 (end-of-line 1)
5157 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5158 (org-maybe-renumber-ordered-list)
5159 (and checkbox (org-update-checkbox-count-maybe))
5162 ;;; Checkboxes
5164 (defun org-at-item-checkbox-p ()
5165 "Is point at a line starting a plain-list item with a checklet?"
5166 (and (org-at-item-p)
5167 (save-excursion
5168 (goto-char (match-end 0))
5169 (skip-chars-forward " \t")
5170 (looking-at "\\[[ X]\\]"))))
5172 (defun org-toggle-checkbox (&optional arg)
5173 "Toggle the checkbox in the current line."
5174 (interactive "P")
5175 (catch 'exit
5176 (let (beg end status (firstnew 'unknown))
5177 (cond
5178 ((org-region-active-p)
5179 (setq beg (region-beginning) end (region-end)))
5180 ((org-on-heading-p)
5181 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5182 ((org-at-item-checkbox-p)
5183 (save-excursion
5184 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5185 (throw 'exit t))
5186 (t (error "Not at a checkbox or heading, and no active region")))
5187 (save-excursion
5188 (goto-char beg)
5189 (while (< (point) end)
5190 (when (org-at-item-checkbox-p)
5191 (setq status (equal (match-string 0) "[X]"))
5192 (when (eq firstnew 'unknown)
5193 (setq firstnew (not status)))
5194 (replace-match
5195 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5196 (beginning-of-line 2)))))
5197 (org-update-checkbox-count-maybe))
5199 (defun org-update-checkbox-count-maybe ()
5200 "Update checkbox statistics unless turned off by user."
5201 (when org-provide-checkbox-statistics
5202 (org-update-checkbox-count)))
5204 (defun org-update-checkbox-count (&optional all)
5205 "Update the checkbox statistics in the current section.
5206 This will find all statistic cookies like [57%] and [6/12] and update them
5207 with the current numbers. With optional prefix argument ALL, do this for
5208 the whole buffer."
5209 (interactive "P")
5210 (save-excursion
5211 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5212 (beg (progn (outline-back-to-heading) (point)))
5213 (end (move-marker (make-marker)
5214 (progn (outline-next-heading) (point))))
5215 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5216 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5217 b1 e1 f1 c-on c-off lim (cstat 0))
5218 (when all
5219 (goto-char (point-min))
5220 (outline-next-heading)
5221 (setq beg (point) end (point-max)))
5222 (goto-char beg)
5223 (while (re-search-forward re end t)
5224 (setq cstat (1+ cstat)
5225 b1 (match-beginning 0)
5226 e1 (match-end 0)
5227 f1 (match-beginning 1)
5228 lim (cond
5229 ((org-on-heading-p) (outline-next-heading) (point))
5230 ((org-at-item-p) (org-end-of-item) (point))
5231 (t nil))
5232 c-on 0 c-off 0)
5233 (goto-char e1)
5234 (when lim
5235 (while (re-search-forward re-box lim t)
5236 (if (equal (match-string 2) "[ ]")
5237 (setq c-off (1+ c-off))
5238 (setq c-on (1+ c-on))))
5239 (delete-region b1 e1)
5240 (goto-char b1)
5241 (insert (if f1
5242 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5243 (format "[%d/%d]" c-on (+ c-on c-off))))))
5244 (when (interactive-p)
5245 (message "Checkbox satistics updated %s (%d places)"
5246 (if all "in entire file" "in current outline entry") cstat)))))
5248 (defun org-get-checkbox-statistics-face ()
5249 "Select the face for checkbox statistics.
5250 The face will be `org-done' when all relevant boxes are checked. Otherwise
5251 it will be `org-todo'."
5252 (if (match-end 1)
5253 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5254 (if (and (> (match-end 2) (match-beginning 2))
5255 (equal (match-string 2) (match-string 3)))
5256 'org-done
5257 'org-todo)))
5259 (defun org-get-indentation (&optional line)
5260 "Get the indentation of the current line, interpreting tabs.
5261 When LINE is given, assume it represents a line and compute its indentation."
5262 (if line
5263 (if (string-match "^ *" (org-remove-tabs line))
5264 (match-end 0))
5265 (save-excursion
5266 (beginning-of-line 1)
5267 (skip-chars-forward " \t")
5268 (current-column))))
5270 (defun org-remove-tabs (s &optional width)
5271 "Replace tabulators in S with spaces.
5272 Assumes that s is a single line, starting in column 0."
5273 (setq width (or width tab-width))
5274 (while (string-match "\t" s)
5275 (setq s (replace-match
5276 (make-string
5277 (- (* width (/ (+ (match-beginning 0) width) width))
5278 (match-beginning 0)) ?\ )
5279 t t s)))
5282 (defun org-fix-indentation (line ind)
5283 "Fix indentation in LINE.
5284 IND is a cons cell with target and minimum indentation.
5285 If the current indenation in LINE is smaller than the minimum,
5286 leave it alone. If it is larger than ind, set it to the target."
5287 (let* ((l (org-remove-tabs line))
5288 (i (org-get-indentation l))
5289 (i1 (car ind)) (i2 (cdr ind)))
5290 (if (>= i i2) (setq l (substring line i2)))
5291 (if (> i1 0)
5292 (concat (make-string i1 ?\ ) l)
5293 l)))
5295 (defcustom org-empty-line-terminates-plain-lists nil
5296 "Non-nil means, an empty line ends all plain list levels.
5297 When nil, empty lines are part of the preceeding item."
5298 :group 'org-plain-lists
5299 :type 'boolean)
5301 (defun org-beginning-of-item ()
5302 "Go to the beginning of the current hand-formatted item.
5303 If the cursor is not in an item, throw an error."
5304 (interactive)
5305 (let ((pos (point))
5306 (limit (save-excursion (org-back-to-heading)
5307 (beginning-of-line 2) (point)))
5308 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5309 ind ind1)
5310 (if (org-at-item-p)
5311 (beginning-of-line 1)
5312 (beginning-of-line 1)
5313 (skip-chars-forward " \t")
5314 (setq ind (current-column))
5315 (if (catch 'exit
5316 (while t
5317 (beginning-of-line 0)
5318 (if (< (point) limit) (throw 'exit nil))
5320 (if (looking-at "[ \t]*$")
5321 (setq ind1 ind-empty)
5322 (skip-chars-forward " \t")
5323 (setq ind1 (current-column)))
5324 (if (< ind1 ind)
5325 (throw 'exit (org-at-item-p)))))
5327 (goto-char pos)
5328 (error "Not in an item")))))
5330 (defun org-end-of-item ()
5331 "Go to the end of the current hand-formatted item.
5332 If the cursor is not in an item, throw an error."
5333 (interactive)
5334 (let* ((pos (point))
5335 ind1
5336 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5337 (limit (save-excursion (outline-next-heading) (point)))
5338 (ind (save-excursion
5339 (org-beginning-of-item)
5340 (skip-chars-forward " \t")
5341 (current-column)))
5342 (end (catch 'exit
5343 (while t
5344 (beginning-of-line 2)
5345 (if (eobp) (throw 'exit (point)))
5346 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5347 (if (looking-at "[ \t]*$")
5348 (setq ind1 ind-empty)
5349 (skip-chars-forward " \t")
5350 (setq ind1 (current-column)))
5351 (if (<= ind1 ind)
5352 (throw 'exit (point-at-bol)))))))
5353 (if end
5354 (goto-char end)
5355 (goto-char pos)
5356 (error "Not in an item"))))
5358 (defun org-next-item ()
5359 "Move to the beginning of the next item in the current plain list.
5360 Error if not at a plain list, or if this is the last item in the list."
5361 (interactive)
5362 (let (ind ind1 (pos (point)))
5363 (org-beginning-of-item)
5364 (setq ind (org-get-indentation))
5365 (org-end-of-item)
5366 (setq ind1 (org-get-indentation))
5367 (unless (and (org-at-item-p) (= ind ind1))
5368 (goto-char pos)
5369 (error "On last item"))))
5371 (defun org-previous-item ()
5372 "Move to the beginning of the previous item in the current plain list.
5373 Error if not at a plain list, or if this is the last item in the list."
5374 (interactive)
5375 (let (beg ind (pos (point)))
5376 (org-beginning-of-item)
5377 (setq beg (point))
5378 (setq ind (org-get-indentation))
5379 (goto-char beg)
5380 (catch 'exit
5381 (while t
5382 (beginning-of-line 0)
5383 (if (looking-at "[ \t]*$")
5385 (if (<= (org-get-indentation) ind)
5386 (throw 'exit t)))))
5387 (condition-case nil
5388 (org-beginning-of-item)
5389 (error (goto-char pos)
5390 (error "On first item")))))
5392 (defun org-move-item-down ()
5393 "Move the plain list item at point down, i.e. swap with following item.
5394 Subitems (items with larger indentation) are considered part of the item,
5395 so this really moves item trees."
5396 (interactive)
5397 (let (beg end ind ind1 (pos (point)) txt)
5398 (org-beginning-of-item)
5399 (setq beg (point))
5400 (setq ind (org-get-indentation))
5401 (org-end-of-item)
5402 (setq end (point))
5403 (setq ind1 (org-get-indentation))
5404 (if (and (org-at-item-p) (= ind ind1))
5405 (progn
5406 (org-end-of-item)
5407 (setq txt (buffer-substring beg end))
5408 (save-excursion
5409 (delete-region beg end))
5410 (setq pos (point))
5411 (insert txt)
5412 (goto-char pos)
5413 (org-maybe-renumber-ordered-list))
5414 (goto-char pos)
5415 (error "Cannot move this item further down"))))
5417 (defun org-move-item-up (arg)
5418 "Move the plain list item at point up, i.e. swap with previous item.
5419 Subitems (items with larger indentation) are considered part of the item,
5420 so this really moves item trees."
5421 (interactive "p")
5422 (let (beg end ind ind1 (pos (point)) txt)
5423 (org-beginning-of-item)
5424 (setq beg (point))
5425 (setq ind (org-get-indentation))
5426 (org-end-of-item)
5427 (setq end (point))
5428 (goto-char beg)
5429 (catch 'exit
5430 (while t
5431 (beginning-of-line 0)
5432 (if (looking-at "[ \t]*$")
5433 (if org-empty-line-terminates-plain-lists
5434 (progn
5435 (goto-char pos)
5436 (error "Cannot move this item further up"))
5437 nil)
5438 (if (<= (setq ind1 (org-get-indentation)) ind)
5439 (throw 'exit t)))))
5440 (condition-case nil
5441 (org-beginning-of-item)
5442 (error (goto-char beg)
5443 (error "Cannot move this item further up")))
5444 (setq ind1 (org-get-indentation))
5445 (if (and (org-at-item-p) (= ind ind1))
5446 (progn
5447 (setq txt (buffer-substring beg end))
5448 (save-excursion
5449 (delete-region beg end))
5450 (setq pos (point))
5451 (insert txt)
5452 (goto-char pos)
5453 (org-maybe-renumber-ordered-list))
5454 (goto-char pos)
5455 (error "Cannot move this item further up"))))
5457 (defun org-maybe-renumber-ordered-list ()
5458 "Renumber the ordered list at point if setup allows it.
5459 This tests the user option `org-auto-renumber-ordered-lists' before
5460 doing the renumbering."
5461 (and org-auto-renumber-ordered-lists
5462 (org-at-item-p)
5463 (match-beginning 3)
5464 (org-renumber-ordered-list 1)))
5466 (defun org-get-string-indentation (s)
5467 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5468 (let ((n -1) (i 0) (w tab-width) c)
5469 (catch 'exit
5470 (while (< (setq n (1+ n)) (length s))
5471 (setq c (aref s n))
5472 (cond ((= c ?\ ) (setq i (1+ i)))
5473 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5474 (t (throw 'exit t)))))
5477 (defun org-renumber-ordered-list (arg)
5478 "Renumber an ordered plain list.
5479 Cursor needs to be in the first line of an item, the line that starts
5480 with something like \"1.\" or \"2)\"."
5481 (interactive "p")
5482 (unless (and (org-at-item-p)
5483 (match-beginning 3))
5484 (error "This is not an ordered list"))
5485 (let ((line (org-current-line))
5486 (col (current-column))
5487 (ind (org-get-string-indentation
5488 (buffer-substring (point-at-bol) (match-beginning 3))))
5489 ;; (term (substring (match-string 3) -1))
5490 ind1 (n (1- arg)))
5491 ;; find where this list begins
5492 (catch 'exit
5493 (while t
5494 (catch 'next
5495 (beginning-of-line 0)
5496 (if (looking-at "[ \t]*$") (throw 'next t))
5497 (skip-chars-forward " \t") (setq ind1 (current-column))
5498 (if (or (< ind1 ind)
5499 (and (= ind1 ind)
5500 (not (org-at-item-p))))
5501 (throw 'exit t)))))
5502 ;; Walk forward and replace these numbers
5503 (catch 'exit
5504 (while t
5505 (catch 'next
5506 (beginning-of-line 2)
5507 (if (eobp) (throw 'exit nil))
5508 (if (looking-at "[ \t]*$") (throw 'next nil))
5509 (skip-chars-forward " \t") (setq ind1 (current-column))
5510 (if (> ind1 ind) (throw 'next t))
5511 (if (< ind1 ind) (throw 'exit t))
5512 (if (not (org-at-item-p)) (throw 'exit nil))
5513 (if (not (match-beginning 3))
5514 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5515 (delete-region (match-beginning 3) (1- (match-end 3)))
5516 (goto-char (match-beginning 3))
5517 (insert (format "%d" (setq n (1+ n)))))))
5518 (goto-line line)
5519 (move-to-column col)))
5521 (defvar org-last-indent-begin-marker (make-marker))
5522 (defvar org-last-indent-end-marker (make-marker))
5524 (defun org-outdent-item (arg)
5525 "Outdent a local list item."
5526 (interactive "p")
5527 (org-indent-item (- arg)))
5529 (defun org-indent-item (arg)
5530 "Indent a local list item."
5531 (interactive "p")
5532 (unless (org-at-item-p)
5533 (error "Not on an item"))
5534 (save-excursion
5535 (let (beg end ind ind1)
5536 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5537 (setq beg org-last-indent-begin-marker
5538 end org-last-indent-end-marker)
5539 (org-beginning-of-item)
5540 (setq beg (move-marker org-last-indent-begin-marker (point)))
5541 (org-end-of-item)
5542 (setq end (move-marker org-last-indent-end-marker (point))))
5543 (goto-char beg)
5544 (skip-chars-forward " \t") (setq ind (current-column))
5545 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5546 (while (< (point) end)
5547 (beginning-of-line 1)
5548 (skip-chars-forward " \t") (setq ind1 (current-column))
5549 (delete-region (point-at-bol) (point))
5550 (indent-to-column (+ ind1 arg))
5551 (beginning-of-line 2)))))
5553 ;;;; Archiving
5555 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5557 (defun org-archive-subtree (&optional find-done)
5558 "Move the current subtree to the archive.
5559 The archive can be a certain top-level heading in the current file, or in
5560 a different file. The tree will be moved to that location, the subtree
5561 heading be marked DONE, and the current time will be added.
5563 When called with prefix argument FIND-DONE, find whole trees without any
5564 open TODO items and archive them (after getting confirmation from the user).
5565 If the cursor is not at a headline when this comand is called, try all level
5566 1 trees. If the cursor is on a headline, only try the direct children of
5567 this heading. "
5568 (interactive "P")
5569 (if find-done
5570 (org-archive-all-done)
5571 ;; Save all relevant TODO keyword-relatex variables
5573 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5574 (tr-org-todo-keywords org-todo-keywords)
5575 (tr-org-todo-kwd-alist org-todo-kwd-alist)
5576 (tr-org-done-keywords org-done-keywords)
5577 (tr-org-todo-regexp org-todo-regexp)
5578 (tr-org-todo-line-regexp org-todo-line-regexp)
5579 (tr-org-odd-levels-only org-odd-levels-only)
5580 (this-buffer (current-buffer))
5581 (org-archive-location org-archive-location)
5582 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5583 file heading buffer level newfile-p)
5585 ;; Try to find a local archive location
5586 (save-excursion
5587 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5588 (setq org-archive-location (match-string 1))))
5590 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5591 (progn
5592 (setq file (format (match-string 1 org-archive-location)
5593 (file-name-nondirectory buffer-file-name))
5594 heading (match-string 2 org-archive-location)))
5595 (error "Invalid `org-archive-location'"))
5596 (if (> (length file) 0)
5597 (setq newfile-p (not (file-exists-p file))
5598 buffer (find-file-noselect file))
5599 (setq buffer (current-buffer)))
5600 (unless buffer
5601 (error "Cannot access file \"%s\"" file))
5602 (if (and (> (length heading) 0)
5603 (string-match "^\\*+" heading))
5604 (setq level (match-end 0))
5605 (setq heading nil level 0))
5606 (save-excursion
5607 ;; We first only copy, in case something goes wrong
5608 ;; we need to protect this-command, to avoid kill-region sets it,
5609 ;; which would lead to duplication of subtrees
5610 (let (this-command) (org-copy-subtree))
5611 (set-buffer buffer)
5612 ;; Enforce org-mode for the archive buffer
5613 (if (not (org-mode-p))
5614 ;; Force the mode for future visits.
5615 (let ((org-insert-mode-line-in-empty-file t))
5616 (call-interactively 'org-mode)))
5617 (when newfile-p
5618 (goto-char (point-max))
5619 (insert (format "\nArchived entries from file %s\n\n"
5620 (buffer-file-name this-buffer))))
5621 ;; Force the TODO keywords of the original buffer
5622 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5623 (org-todo-keywords tr-org-todo-keywords)
5624 (org-todo-kwd-alist tr-org-todo-kwd-alist)
5625 (org-done-keywords tr-org-done-keywords)
5626 (org-todo-regexp tr-org-todo-regexp)
5627 (org-todo-line-regexp tr-org-todo-line-regexp)
5628 (org-odd-levels-only
5629 (if (local-variable-p 'org-odd-levels-only (current-buffer))
5630 org-odd-levels-only
5631 tr-org-odd-levels-only)))
5632 (goto-char (point-min))
5633 (if heading
5634 (progn
5635 (if (re-search-forward
5636 (concat "\\(^\\|\r\\)"
5637 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5638 nil t)
5639 (goto-char (match-end 0))
5640 ;; Heading not found, just insert it at the end
5641 (goto-char (point-max))
5642 (or (bolp) (insert "\n"))
5643 (insert "\n" heading "\n")
5644 (end-of-line 0))
5645 ;; Make the subtree visible
5646 (show-subtree)
5647 (org-end-of-subtree t)
5648 (skip-chars-backward " \t\r\n")
5649 (and (looking-at "[ \t\r\n]*")
5650 (replace-match "\n\n")))
5651 ;; No specific heading, just go to end of file.
5652 (goto-char (point-max)) (insert "\n"))
5653 ;; Paste
5654 (org-paste-subtree (org-get-legal-level level 1))
5655 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5656 (if org-archive-mark-done
5657 (let (org-log-done)
5658 (org-todo (length org-todo-keywords))))
5659 ;; Move cursor to right after the TODO keyword
5660 (when org-archive-stamp-time
5661 (beginning-of-line 1)
5662 (looking-at org-todo-line-regexp)
5663 (goto-char (or (match-end 2) (match-beginning 3)))
5664 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5665 ;; Save the buffer, if it is not the same buffer.
5666 (if (not (eq this-buffer buffer)) (save-buffer))))
5667 ;; Here we are back in the original buffer. Everything seems to have
5668 ;; worked. So now cut the tree and finish up.
5669 (let (this-command) (org-cut-subtree))
5670 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5671 (message "Subtree archived %s"
5672 (if (eq this-buffer buffer)
5673 (concat "under heading: " heading)
5674 (concat "in file: " (abbreviate-file-name file)))))))
5676 (defun org-archive-all-done (&optional tag)
5677 "Archive sublevels of the current tree without open TODO items.
5678 If the cursor is not on a headline, try all level 1 trees. If
5679 it is on a headline, try all direct children.
5680 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5681 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5682 (rea (concat ".*:" org-archive-tag ":"))
5683 (begm (make-marker))
5684 (endm (make-marker))
5685 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5686 "Move subtree to archive (no open TODO items)? "))
5687 beg end (cntarch 0))
5688 (if (org-on-heading-p)
5689 (progn
5690 (setq re1 (concat "^" (regexp-quote
5691 (make-string
5692 (1+ (- (match-end 0) (match-beginning 0)))
5693 ?*))
5694 " "))
5695 (move-marker begm (point))
5696 (move-marker endm (org-end-of-subtree t)))
5697 (setq re1 "^* ")
5698 (move-marker begm (point-min))
5699 (move-marker endm (point-max)))
5700 (save-excursion
5701 (goto-char begm)
5702 (while (re-search-forward re1 endm t)
5703 (setq beg (match-beginning 0)
5704 end (save-excursion (org-end-of-subtree t) (point)))
5705 (goto-char beg)
5706 (if (re-search-forward re end t)
5707 (goto-char end)
5708 (goto-char beg)
5709 (if (and (or (not tag) (not (looking-at rea)))
5710 (y-or-n-p question))
5711 (progn
5712 (if tag
5713 (org-toggle-tag org-archive-tag 'on)
5714 (org-archive-subtree))
5715 (setq cntarch (1+ cntarch)))
5716 (goto-char end)))))
5717 (message "%d trees archived" cntarch)))
5719 (defun org-cycle-hide-archived-subtrees (state)
5720 "Re-hide all archived subtrees after a visibility state change."
5721 (when (and (not org-cycle-open-archived-trees)
5722 (not (memq state '(overview folded))))
5723 (save-excursion
5724 (let* ((globalp (memq state '(contents all)))
5725 (beg (if globalp (point-min) (point)))
5726 (end (if globalp (point-max) (org-end-of-subtree t))))
5727 (org-hide-archived-subtrees beg end)
5728 (goto-char beg)
5729 (if (looking-at (concat ".*:" org-archive-tag ":"))
5730 (message (substitute-command-keys
5731 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5733 (defun org-force-cycle-archived ()
5734 "Cycle subtree even if it is archived."
5735 (interactive)
5736 (setq this-command 'org-cycle)
5737 (let ((org-cycle-open-archived-trees t))
5738 (call-interactively 'org-cycle)))
5740 (defun org-hide-archived-subtrees (beg end)
5741 "Re-hide all archived subtrees after a visibility state change."
5742 (save-excursion
5743 (let* ((re (concat ":" org-archive-tag ":")))
5744 (goto-char beg)
5745 (while (re-search-forward re end t)
5746 (and (org-on-heading-p) (hide-subtree))
5747 (org-end-of-subtree t)))))
5749 (defun org-toggle-tag (tag &optional onoff)
5750 "Toggle the tag TAG for the current line.
5751 If ONOFF is `on' or `off', don't toggle but set to this state."
5752 (unless (org-on-heading-p t) (error "Not on headling"))
5753 (let (res current)
5754 (save-excursion
5755 (beginning-of-line)
5756 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5757 (point-at-eol) t)
5758 (progn
5759 (setq current (match-string 1))
5760 (replace-match ""))
5761 (setq current ""))
5762 (setq current (nreverse (org-split-string current ":")))
5763 (cond
5764 ((eq onoff 'on)
5765 (setq res t)
5766 (or (member tag current) (push tag current)))
5767 ((eq onoff 'off)
5768 (or (not (member tag current)) (setq current (delete tag current))))
5769 (t (if (member tag current)
5770 (setq current (delete tag current))
5771 (setq res t)
5772 (push tag current))))
5773 (end-of-line 1)
5774 (when current
5775 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5776 (org-set-tags nil t))
5777 res))
5779 (defun org-toggle-archive-tag (&optional arg)
5780 "Toggle the archive tag for the current headline.
5781 With prefix ARG, check all children of current headline and offer tagging
5782 the children that do not contain any open TODO items."
5783 (interactive "P")
5784 (if arg
5785 (org-archive-all-done 'tag)
5786 (let (set)
5787 (save-excursion
5788 (org-back-to-heading t)
5789 (setq set (org-toggle-tag org-archive-tag))
5790 (when set (hide-subtree)))
5791 (and set (beginning-of-line 1))
5792 (message "Subtree %s" (if set "archived" "unarchived")))))
5795 ;;;; Tables
5797 ;;; The table editor
5799 ;; Watch out: Here we are talking about two different kind of tables.
5800 ;; Most of the code is for the tables created with the Org-mode table editor.
5801 ;; Sometimes, we talk about tables created and edited with the table.el
5802 ;; Emacs package. We call the former org-type tables, and the latter
5803 ;; table.el-type tables.
5805 (defun org-before-change-function (beg end)
5806 "Every change indicates that a table might need an update."
5807 (setq org-table-may-need-update t))
5809 (defconst org-table-line-regexp "^[ \t]*|"
5810 "Detects an org-type table line.")
5811 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5812 "Detects an org-type table line.")
5813 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5814 "Detects a table line marked for automatic recalculation.")
5815 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5816 "Detects a table line marked for automatic recalculation.")
5817 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5818 "Detects a table line marked for automatic recalculation.")
5819 (defconst org-table-hline-regexp "^[ \t]*|-"
5820 "Detects an org-type table hline.")
5821 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5822 "Detects a table-type table hline.")
5823 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5824 "Detects an org-type or table-type table.")
5825 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5826 "Searching from within a table (any type) this finds the first line
5827 outside the table.")
5828 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5829 "Searching from within a table (any type) this finds the first line
5830 outside the table.")
5832 (defvar org-table-last-highlighted-reference nil)
5833 (defvar org-table-formula-history nil)
5835 (defvar org-table-column-names nil
5836 "Alist with column names, derived from the `!' line.")
5837 (defvar org-table-column-name-regexp nil
5838 "Regular expression matching the current column names.")
5839 (defvar org-table-local-parameters nil
5840 "Alist with parameter names, derived from the `$' line.")
5841 (defvar org-table-named-field-locations nil
5842 "Alist with locations of named fields.")
5844 (defvar org-table-current-line-types nil
5845 "Table row types, non-nil only for the duration of a comand.")
5846 (defvar org-table-current-begin-line nil
5847 "Table begin line, non-nil only for the duration of a comand.")
5848 (defvar org-table-current-begin-pos nil
5849 "Table begin position, non-nil only for the duration of a comand.")
5850 (defvar org-table-dlines nil
5851 "Vector of data line line numbers in the current table.")
5852 (defvar org-table-hlines nil
5853 "Vector of hline line numbers in the current table.")
5855 (defconst org-table-range-regexp
5856 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5857 ;; 1 2 3 4 5
5858 "Regular expression for matching ranges in formulas.")
5860 (defconst org-table-range-regexp2
5861 (concat
5862 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
5863 "\\.\\."
5864 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
5865 "Match a range for reference display.")
5867 (defconst org-table-translate-regexp
5868 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
5869 "Match a reference that needs translation, for reference display.")
5871 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
5873 (defun org-table-create-with-table.el ()
5874 "Use the table.el package to insert a new table.
5875 If there is already a table at point, convert between Org-mode tables
5876 and table.el tables."
5877 (interactive)
5878 (require 'table)
5879 (cond
5880 ((org-at-table.el-p)
5881 (if (y-or-n-p "Convert table to Org-mode table? ")
5882 (org-table-convert)))
5883 ((org-at-table-p)
5884 (if (y-or-n-p "Convert table to table.el table? ")
5885 (org-table-convert)))
5886 (t (call-interactively 'table-insert))))
5888 (defun org-table-create-or-convert-from-region (arg)
5889 "Convert region to table, or create an empty table.
5890 If there is an active region, convert it to a table. If there is no such
5891 region, create an empty table."
5892 (interactive "P")
5893 (if (org-region-active-p)
5894 (org-table-convert-region (region-beginning) (region-end) arg)
5895 (org-table-create arg)))
5897 (defun org-table-create (&optional size)
5898 "Query for a size and insert a table skeleton.
5899 SIZE is a string Columns x Rows like for example \"3x2\"."
5900 (interactive "P")
5901 (unless size
5902 (setq size (read-string
5903 (concat "Table size Columns x Rows [e.g. "
5904 org-table-default-size "]: ")
5905 "" nil org-table-default-size)))
5907 (let* ((pos (point))
5908 (indent (make-string (current-column) ?\ ))
5909 (split (org-split-string size " *x *"))
5910 (rows (string-to-number (nth 1 split)))
5911 (columns (string-to-number (car split)))
5912 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5913 "\n")))
5914 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5915 (point-at-bol) (point)))
5916 (beginning-of-line 1)
5917 (newline))
5918 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5919 (dotimes (i rows) (insert line))
5920 (goto-char pos)
5921 (if (> rows 1)
5922 ;; Insert a hline after the first row.
5923 (progn
5924 (end-of-line 1)
5925 (insert "\n|-")
5926 (goto-char pos)))
5927 (org-table-align)))
5929 (defun org-table-convert-region (beg0 end0 &optional nspace)
5930 "Convert region to a table.
5931 The region goes from BEG0 to END0, but these borders will be moved
5932 slightly, to make sure a beginning of line in the first line is included.
5933 When NSPACE is non-nil, it indicates the minimum number of spaces that
5934 separate columns (default: just one space)."
5935 (interactive "rP")
5936 (let* ((beg (min beg0 end0))
5937 (end (max beg0 end0))
5938 (tabsep t)
5940 (goto-char beg)
5941 (beginning-of-line 1)
5942 (setq beg (move-marker (make-marker) (point)))
5943 (goto-char end)
5944 (if (bolp) (backward-char 1) (end-of-line 1))
5945 (setq end (move-marker (make-marker) (point)))
5946 ;; Lets see if this is tab-separated material. If every nonempty line
5947 ;; contains a tab, we will assume that it is tab-separated material
5948 (if nspace
5949 (setq tabsep nil)
5950 (goto-char beg)
5951 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5952 (if nspace (setq tabsep nil))
5953 (if tabsep
5954 (setq re "^\\|\t")
5955 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5956 (max 1 (prefix-numeric-value nspace)))))
5957 (goto-char beg)
5958 (while (re-search-forward re end t)
5959 (replace-match "| " t t))
5960 (goto-char beg)
5961 (insert " ")
5962 (org-table-align)))
5964 (defun org-table-import (file arg)
5965 "Import FILE as a table.
5966 The file is assumed to be tab-separated. Such files can be produced by most
5967 spreadsheet and database applications. If no tabs (at least one per line)
5968 are found, lines will be split on whitespace into fields."
5969 (interactive "f\nP")
5970 (or (bolp) (newline))
5971 (let ((beg (point))
5972 (pm (point-max)))
5973 (insert-file-contents file)
5974 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5976 (defun org-table-export ()
5977 "Export table as a tab-separated file.
5978 Such a file can be imported into a spreadsheet program like Excel."
5979 (interactive)
5980 (let* ((beg (org-table-begin))
5981 (end (org-table-end))
5982 (table (buffer-substring beg end))
5983 (file (read-file-name "Export table to: "))
5984 buf)
5985 (unless (or (not (file-exists-p file))
5986 (y-or-n-p (format "Overwrite file %s? " file)))
5987 (error "Abort"))
5988 (with-current-buffer (find-file-noselect file)
5989 (setq buf (current-buffer))
5990 (erase-buffer)
5991 (fundamental-mode)
5992 (insert table)
5993 (goto-char (point-min))
5994 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5995 (replace-match "" t t)
5996 (end-of-line 1))
5997 (goto-char (point-min))
5998 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5999 (replace-match "" t t)
6000 (goto-char (min (1+ (point)) (point-max))))
6001 (goto-char (point-min))
6002 (while (re-search-forward "^-[-+]*$" nil t)
6003 (replace-match "")
6004 (if (looking-at "\n")
6005 (delete-char 1)))
6006 (goto-char (point-min))
6007 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6008 (replace-match "\t" t t))
6009 (save-buffer))
6010 (kill-buffer buf)))
6012 (defvar org-table-aligned-begin-marker (make-marker)
6013 "Marker at the beginning of the table last aligned.
6014 Used to check if cursor still is in that table, to minimize realignment.")
6015 (defvar org-table-aligned-end-marker (make-marker)
6016 "Marker at the end of the table last aligned.
6017 Used to check if cursor still is in that table, to minimize realignment.")
6018 (defvar org-table-last-alignment nil
6019 "List of flags for flushright alignment, from the last re-alignment.
6020 This is being used to correctly align a single field after TAB or RET.")
6021 (defvar org-table-last-column-widths nil
6022 "List of max width of fields in each column.
6023 This is being used to correctly align a single field after TAB or RET.")
6024 (defvar org-table-overlay-coordinates nil
6025 "Overlay coordinates after each align of a table.")
6026 (make-variable-buffer-local 'org-table-overlay-coordinates)
6028 (defvar org-last-recalc-line nil)
6029 (defconst org-narrow-column-arrow "=>"
6030 "Used as display property in narrowed table columns.")
6032 (defun org-table-align ()
6033 "Align the table at point by aligning all vertical bars."
6034 (interactive)
6035 (let* (
6036 ;; Limits of table
6037 (beg (org-table-begin))
6038 (end (org-table-end))
6039 ;; Current cursor position
6040 (linepos (org-current-line))
6041 (colpos (org-table-current-column))
6042 (winstart (window-start))
6043 (winstartline (org-current-line (min winstart (1- (point-max)))))
6044 lines (new "") lengths l typenums ty fields maxfields i
6045 column
6046 (indent "") cnt frac
6047 rfmt hfmt
6048 (spaces '(1 . 1))
6049 (sp1 (car spaces))
6050 (sp2 (cdr spaces))
6051 (rfmt1 (concat
6052 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6053 (hfmt1 (concat
6054 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6055 emptystrings links dates narrow fmax f1 len c e)
6056 (untabify beg end)
6057 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
6058 ;; Check if we have links or dates
6059 (goto-char beg)
6060 (setq links (re-search-forward org-bracket-link-regexp end t))
6061 (goto-char beg)
6062 (setq dates (and org-display-custom-times
6063 (re-search-forward org-ts-regexp-both end t)))
6064 ;; Make sure the link properties are right
6065 (when links (goto-char beg) (while (org-activate-bracket-links end)))
6066 ;; Make sure the date properties are right
6067 (when dates (goto-char beg) (while (org-activate-dates end)))
6069 ;; Check if we are narrowing any columns
6070 (goto-char beg)
6071 (setq narrow (and org-format-transports-properties-p
6072 (re-search-forward "<[0-9]+>" end t)))
6073 ;; Get the rows
6074 (setq lines (org-split-string
6075 (buffer-substring beg end) "\n"))
6076 ;; Store the indentation of the first line
6077 (if (string-match "^ *" (car lines))
6078 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6079 ;; Mark the hlines by setting the corresponding element to nil
6080 ;; At the same time, we remove trailing space.
6081 (setq lines (mapcar (lambda (l)
6082 (if (string-match "^ *|-" l)
6084 (if (string-match "[ \t]+$" l)
6085 (substring l 0 (match-beginning 0))
6086 l)))
6087 lines))
6088 ;; Get the data fields by splitting the lines.
6089 (setq fields (mapcar
6090 (lambda (l)
6091 (org-split-string l " *| *"))
6092 (delq nil (copy-sequence lines))))
6093 ;; How many fields in the longest line?
6094 (condition-case nil
6095 (setq maxfields (apply 'max (mapcar 'length fields)))
6096 (error
6097 (kill-region beg end)
6098 (org-table-create org-table-default-size)
6099 (error "Empty table - created default table")))
6100 ;; A list of empty strings to fill any short rows on output
6101 (setq emptystrings (make-list maxfields ""))
6102 ;; Check for special formatting.
6103 (setq i -1)
6104 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6105 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6106 ;; Check if there is an explicit width specified
6107 (when narrow
6108 (setq c column fmax nil)
6109 (while c
6110 (setq e (pop c))
6111 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6112 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6113 ;; Find fields that are wider than fmax, and shorten them
6114 (when fmax
6115 (loop for xx in column do
6116 (when (and (stringp xx)
6117 (> (org-string-width xx) fmax))
6118 (org-add-props xx nil
6119 'help-echo
6120 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6121 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6122 (unless (> f1 1)
6123 (error "Cannot narrow field starting with wide link \"%s\""
6124 (match-string 0 xx)))
6125 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6126 (add-text-properties (- f1 2) f1
6127 (list 'display org-narrow-column-arrow)
6128 xx)))))
6129 ;; Get the maximum width for each column
6130 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6131 ;; Get the fraction of numbers, to decide about alignment of the column
6132 (setq cnt 0 frac 0.0)
6133 (loop for x in column do
6134 (if (equal x "")
6136 (setq frac ( / (+ (* frac cnt)
6137 (if (string-match org-table-number-regexp x) 1 0))
6138 (setq cnt (1+ cnt))))))
6139 (push (>= frac org-table-number-fraction) typenums))
6140 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6142 ;; Store the alignment of this table, for later editing of single fields
6143 (setq org-table-last-alignment typenums
6144 org-table-last-column-widths lengths)
6146 ;; With invisible characters, `format' does not get the field width right
6147 ;; So we need to make these fields wide by hand.
6148 (when links
6149 (loop for i from 0 upto (1- maxfields) do
6150 (setq len (nth i lengths))
6151 (loop for j from 0 upto (1- (length fields)) do
6152 (setq c (nthcdr i (car (nthcdr j fields))))
6153 (if (and (stringp (car c))
6154 (string-match org-bracket-link-regexp (car c))
6155 (< (org-string-width (car c)) len))
6156 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6158 ;; Compute the formats needed for output of the table
6159 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6160 (while (setq l (pop lengths))
6161 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6162 (setq rfmt (concat rfmt (format rfmt1 ty l))
6163 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6164 (setq rfmt (concat rfmt "\n")
6165 hfmt (concat (substring hfmt 0 -1) "|\n"))
6167 (setq new (mapconcat
6168 (lambda (l)
6169 (if l (apply 'format rfmt
6170 (append (pop fields) emptystrings))
6171 hfmt))
6172 lines ""))
6173 ;; Replace the old one
6174 (delete-region beg end)
6175 (move-marker end nil)
6176 (move-marker org-table-aligned-begin-marker (point))
6177 (insert new)
6178 (move-marker org-table-aligned-end-marker (point))
6179 (when (and orgtbl-mode (not (org-mode-p)))
6180 (goto-char org-table-aligned-begin-marker)
6181 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6182 ;; Try to move to the old location
6183 (goto-line winstartline)
6184 (setq winstart (point-at-bol))
6185 (goto-line linepos)
6186 (set-window-start (selected-window) winstart 'noforce)
6187 (org-table-goto-column colpos)
6188 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6189 (setq org-table-may-need-update nil)
6192 (defun org-string-width (s)
6193 "Compute width of string, ignoring invisible characters.
6194 This ignores character with invisibility property `org-link', and also
6195 characters with property `org-cwidth', because these will become invisible
6196 upon the next fontification round."
6197 (let (b l)
6198 (when (or (eq t buffer-invisibility-spec)
6199 (assq 'org-link buffer-invisibility-spec))
6200 (while (setq b (text-property-any 0 (length s)
6201 'invisible 'org-link s))
6202 (setq s (concat (substring s 0 b)
6203 (substring s (or (next-single-property-change
6204 b 'invisible s) (length s)))))))
6205 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6206 (setq s (concat (substring s 0 b)
6207 (substring s (or (next-single-property-change
6208 b 'org-cwidth s) (length s))))))
6209 (setq l (string-width s) b -1)
6210 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6211 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6214 (defun org-table-begin (&optional table-type)
6215 "Find the beginning of the table and return its position.
6216 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6217 (save-excursion
6218 (if (not (re-search-backward
6219 (if table-type org-table-any-border-regexp
6220 org-table-border-regexp)
6221 nil t))
6222 (progn (goto-char (point-min)) (point))
6223 (goto-char (match-beginning 0))
6224 (beginning-of-line 2)
6225 (point))))
6227 (defun org-table-end (&optional table-type)
6228 "Find the end of the table and return its position.
6229 With argument TABLE-TYPE, go to the end of a table.el-type table."
6230 (save-excursion
6231 (if (not (re-search-forward
6232 (if table-type org-table-any-border-regexp
6233 org-table-border-regexp)
6234 nil t))
6235 (goto-char (point-max))
6236 (goto-char (match-beginning 0)))
6237 (point-marker)))
6239 (defun org-table-justify-field-maybe (&optional new)
6240 "Justify the current field, text to left, number to right.
6241 Optional argument NEW may specify text to replace the current field content."
6242 (cond
6243 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6244 ((org-at-table-hline-p))
6245 ((and (not new)
6246 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6247 (current-buffer)))
6248 (< (point) org-table-aligned-begin-marker)
6249 (>= (point) org-table-aligned-end-marker)))
6250 ;; This is not the same table, force a full re-align
6251 (setq org-table-may-need-update t))
6252 (t ;; realign the current field, based on previous full realign
6253 (let* ((pos (point)) s
6254 (col (org-table-current-column))
6255 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6256 l f n o e)
6257 (when (> col 0)
6258 (skip-chars-backward "^|\n")
6259 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6260 (progn
6261 (setq s (match-string 1)
6262 o (match-string 0)
6263 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6264 e (not (= (match-beginning 2) (match-end 2))))
6265 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6266 l (if e "|" (setq org-table-may-need-update t) ""))
6267 n (format f s))
6268 (if new
6269 (if (<= (length new) l) ;; FIXME: length -> str-width?
6270 (setq n (format f new))
6271 (setq n (concat new "|") org-table-may-need-update t)))
6272 (or (equal n o)
6273 (let (org-table-may-need-update)
6274 (replace-match n))))
6275 (setq org-table-may-need-update t))
6276 (goto-char pos))))))
6278 (defun org-table-next-field ()
6279 "Go to the next field in the current table, creating new lines as needed.
6280 Before doing so, re-align the table if necessary."
6281 (interactive)
6282 (org-table-maybe-eval-formula)
6283 (org-table-maybe-recalculate-line)
6284 (if (and org-table-automatic-realign
6285 org-table-may-need-update)
6286 (org-table-align))
6287 (let ((end (org-table-end)))
6288 (if (org-at-table-hline-p)
6289 (end-of-line 1))
6290 (condition-case nil
6291 (progn
6292 (re-search-forward "|" end)
6293 (if (looking-at "[ \t]*$")
6294 (re-search-forward "|" end))
6295 (if (and (looking-at "-")
6296 org-table-tab-jumps-over-hlines
6297 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6298 (goto-char (match-beginning 1)))
6299 (if (looking-at "-")
6300 (progn
6301 (beginning-of-line 0)
6302 (org-table-insert-row 'below))
6303 (if (looking-at " ") (forward-char 1))))
6304 (error
6305 (org-table-insert-row 'below)))))
6307 (defun org-table-previous-field ()
6308 "Go to the previous field in the table.
6309 Before doing so, re-align the table if necessary."
6310 (interactive)
6311 (org-table-justify-field-maybe)
6312 (org-table-maybe-recalculate-line)
6313 (if (and org-table-automatic-realign
6314 org-table-may-need-update)
6315 (org-table-align))
6316 (if (org-at-table-hline-p)
6317 (end-of-line 1))
6318 (re-search-backward "|" (org-table-begin))
6319 (re-search-backward "|" (org-table-begin))
6320 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6321 (re-search-backward "|" (org-table-begin)))
6322 (if (looking-at "| ?")
6323 (goto-char (match-end 0))))
6325 (defun org-table-next-row ()
6326 "Go to the next row (same column) in the current table.
6327 Before doing so, re-align the table if necessary."
6328 (interactive)
6329 (org-table-maybe-eval-formula)
6330 (org-table-maybe-recalculate-line)
6331 (if (or (looking-at "[ \t]*$")
6332 (save-excursion (skip-chars-backward " \t") (bolp)))
6333 (newline)
6334 (if (and org-table-automatic-realign
6335 org-table-may-need-update)
6336 (org-table-align))
6337 (let ((col (org-table-current-column)))
6338 (beginning-of-line 2)
6339 (if (or (not (org-at-table-p))
6340 (org-at-table-hline-p))
6341 (progn
6342 (beginning-of-line 0)
6343 (org-table-insert-row 'below)))
6344 (org-table-goto-column col)
6345 (skip-chars-backward "^|\n\r")
6346 (if (looking-at " ") (forward-char 1)))))
6348 (defun org-table-copy-down (n)
6349 "Copy a field down in the current column.
6350 If the field at the cursor is empty, copy into it the content of the nearest
6351 non-empty field above. With argument N, use the Nth non-empty field.
6352 If the current field is not empty, it is copied down to the next row, and
6353 the cursor is moved with it. Therefore, repeating this command causes the
6354 column to be filled row-by-row.
6355 If the variable `org-table-copy-increment' is non-nil and the field is an
6356 integer, it will be incremented while copying."
6357 (interactive "p")
6358 (let* ((colpos (org-table-current-column))
6359 (field (org-table-get-field))
6360 (non-empty (string-match "[^ \t]" field))
6361 (beg (org-table-begin))
6362 txt)
6363 (org-table-check-inside-data-field)
6364 (if non-empty
6365 (progn
6366 (setq txt (org-trim field))
6367 (org-table-next-row)
6368 (org-table-blank-field))
6369 (save-excursion
6370 (setq txt
6371 (catch 'exit
6372 (while (progn (beginning-of-line 1)
6373 (re-search-backward org-table-dataline-regexp
6374 beg t))
6375 (org-table-goto-column colpos t)
6376 (if (and (looking-at
6377 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6378 (= (setq n (1- n)) 0))
6379 (throw 'exit (match-string 1))))))))
6380 (if txt
6381 (progn
6382 (if (and org-table-copy-increment
6383 (string-match "^[0-9]+$" txt))
6384 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6385 (insert txt)
6386 (org-table-maybe-recalculate-line)
6387 (org-table-align))
6388 (error "No non-empty field found"))))
6390 (defun org-table-check-inside-data-field ()
6391 "Is point inside a table data field?
6392 I.e. not on a hline or before the first or after the last column?
6393 This actually throws an error, so it aborts the current command."
6394 (if (or (not (org-at-table-p))
6395 (= (org-table-current-column) 0)
6396 (org-at-table-hline-p)
6397 (looking-at "[ \t]*$"))
6398 (error "Not in table data field")))
6400 (defvar org-table-clip nil
6401 "Clipboard for table regions.")
6403 (defun org-table-blank-field ()
6404 "Blank the current table field or active region."
6405 (interactive)
6406 (org-table-check-inside-data-field)
6407 (if (and (interactive-p) (org-region-active-p))
6408 (let (org-table-clip)
6409 (org-table-cut-region (region-beginning) (region-end)))
6410 (skip-chars-backward "^|")
6411 (backward-char 1)
6412 (if (looking-at "|[^|\n]+")
6413 (let* ((pos (match-beginning 0))
6414 (match (match-string 0))
6415 (len (org-string-width match)))
6416 (replace-match (concat "|" (make-string (1- len) ?\ )))
6417 (goto-char (+ 2 pos))
6418 (substring match 1)))))
6420 (defun org-table-get-field (&optional n replace)
6421 "Return the value of the field in column N of current row.
6422 N defaults to current field.
6423 If REPLACE is a string, replace field with this value. The return value
6424 is always the old value."
6425 (and n (org-table-goto-column n))
6426 (skip-chars-backward "^|\n")
6427 (backward-char 1)
6428 (if (looking-at "|[^|\r\n]*")
6429 (let* ((pos (match-beginning 0))
6430 (val (buffer-substring (1+ pos) (match-end 0))))
6431 (if replace
6432 (replace-match (concat "|" replace) t t))
6433 (goto-char (min (point-at-eol) (+ 2 pos)))
6434 val)
6435 (forward-char 1) ""))
6438 (defun org-table-field-info (arg)
6439 "Show info about the current field, and highlight any reference at point."
6440 (interactive "P")
6441 (org-table-get-specials)
6442 (save-excursion
6443 (let* ((pos (point))
6444 (col (org-table-current-column))
6445 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6446 (name (car (rassoc (list (org-current-line) col)
6447 org-table-named-field-locations)))
6448 (eql (org-table-get-stored-formulas))
6449 (dline (org-table-current-dline))
6450 (ref (format "@%d$%d" dline col))
6451 (ref1 (org-table-convert-refs-to-an ref))
6452 (fequation (or (assoc name eql) (assoc ref eql)))
6453 (cequation (assoc (int-to-string col) eql))
6454 (eqn (or fequation cequation)))
6455 (goto-char pos)
6456 (condition-case nil
6457 (org-table-show-reference 'local)
6458 (error nil))
6459 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
6460 dline col
6461 (if cname (concat " or $" cname) "")
6462 dline col ref1
6463 (if name (concat " or $" name) "")
6464 ;; FIXME: formula info not correct if special table line
6465 (if eqn
6466 (concat ", formula: "
6467 (org-table-formula-to-user
6468 (concat
6469 (if (string-match "^[$@]"(car eqn)) "" "$")
6470 (car eqn) "=" (cdr eqn))))
6471 "")))))
6473 (defun org-table-current-column ()
6474 "Find out which column we are in.
6475 When called interactively, column is also displayed in echo area."
6476 (interactive)
6477 (if (interactive-p) (org-table-check-inside-data-field))
6478 (save-excursion
6479 (let ((cnt 0) (pos (point)))
6480 (beginning-of-line 1)
6481 (while (search-forward "|" pos t)
6482 (setq cnt (1+ cnt)))
6483 (if (interactive-p) (message "This is table column %d" cnt))
6484 cnt)))
6486 (defun org-table-current-dline ()
6487 "Find out what table data line we are in.
6488 Only datalins count for this."
6489 (interactive)
6490 (if (interactive-p) (org-table-check-inside-data-field))
6491 (save-excursion
6492 (let ((cnt 0) (pos (point)))
6493 (goto-char (org-table-begin))
6494 (while (<= (point) pos)
6495 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6496 (beginning-of-line 2))
6497 (if (interactive-p) (message "This is table line %d" cnt))
6498 cnt)))
6500 (defun org-table-goto-column (n &optional on-delim force)
6501 "Move the cursor to the Nth column in the current table line.
6502 With optional argument ON-DELIM, stop with point before the left delimiter
6503 of the field.
6504 If there are less than N fields, just go to after the last delimiter.
6505 However, when FORCE is non-nil, create new columns if necessary."
6506 (interactive "p")
6507 (let ((pos (point-at-eol)))
6508 (beginning-of-line 1)
6509 (when (> n 0)
6510 (while (and (> (setq n (1- n)) -1)
6511 (or (search-forward "|" pos t)
6512 (and force
6513 (progn (end-of-line 1)
6514 (skip-chars-backward "^|")
6515 (insert " | "))))))
6516 ; (backward-char 2) t)))))
6517 (when (and force (not (looking-at ".*|")))
6518 (save-excursion (end-of-line 1) (insert " | ")))
6519 (if on-delim
6520 (backward-char 1)
6521 (if (looking-at " ") (forward-char 1))))))
6523 (defun org-at-table-p (&optional table-type)
6524 "Return t if the cursor is inside an org-type table.
6525 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6526 (if org-enable-table-editor
6527 (save-excursion
6528 (beginning-of-line 1)
6529 (looking-at (if table-type org-table-any-line-regexp
6530 org-table-line-regexp)))
6531 nil))
6533 (defun org-at-table.el-p ()
6534 "Return t if and only if we are at a table.el table."
6535 (and (org-at-table-p 'any)
6536 (save-excursion
6537 (goto-char (org-table-begin 'any))
6538 (looking-at org-table1-hline-regexp))))
6540 (defun org-table-recognize-table.el ()
6541 "If there is a table.el table nearby, recognize it and move into it."
6542 (if org-table-tab-recognizes-table.el
6543 (if (org-at-table.el-p)
6544 (progn
6545 (beginning-of-line 1)
6546 (if (looking-at org-table-dataline-regexp)
6548 (if (looking-at org-table1-hline-regexp)
6549 (progn
6550 (beginning-of-line 2)
6551 (if (looking-at org-table-any-border-regexp)
6552 (beginning-of-line -1)))))
6553 (if (re-search-forward "|" (org-table-end t) t)
6554 (progn
6555 (require 'table)
6556 (if (table--at-cell-p (point))
6558 (message "recognizing table.el table...")
6559 (table-recognize-table)
6560 (message "recognizing table.el table...done")))
6561 (error "This should not happen..."))
6563 nil)
6564 nil))
6566 (defun org-at-table-hline-p ()
6567 "Return t if the cursor is inside a hline in a table."
6568 (if org-enable-table-editor
6569 (save-excursion
6570 (beginning-of-line 1)
6571 (looking-at org-table-hline-regexp))
6572 nil))
6574 (defun org-table-insert-column ()
6575 "Insert a new column into the table."
6576 (interactive)
6577 (if (not (org-at-table-p))
6578 (error "Not at a table"))
6579 (org-table-find-dataline)
6580 (let* ((col (max 1 (org-table-current-column)))
6581 (beg (org-table-begin))
6582 (end (org-table-end))
6583 ;; Current cursor position
6584 (linepos (org-current-line))
6585 (colpos col))
6586 (goto-char beg)
6587 (while (< (point) end)
6588 (if (org-at-table-hline-p)
6590 (org-table-goto-column col t)
6591 (insert "| "))
6592 (beginning-of-line 2))
6593 (move-marker end nil)
6594 (goto-line linepos)
6595 (org-table-goto-column colpos)
6596 (org-table-align)
6597 (org-table-fix-formulas "$" nil (1- col) 1)))
6599 (defun org-table-find-dataline ()
6600 "Find a dataline in the current table, which is needed for column commands."
6601 (if (and (org-at-table-p)
6602 (not (org-at-table-hline-p)))
6604 (let ((col (current-column))
6605 (end (org-table-end)))
6606 (move-to-column col)
6607 (while (and (< (point) end)
6608 (or (not (= (current-column) col))
6609 (org-at-table-hline-p)))
6610 (beginning-of-line 2)
6611 (move-to-column col))
6612 (if (and (org-at-table-p)
6613 (not (org-at-table-hline-p)))
6615 (error
6616 "Please position cursor in a data line for column operations")))))
6618 (defun org-table-delete-column ()
6619 "Delete a column from the table."
6620 (interactive)
6621 (if (not (org-at-table-p))
6622 (error "Not at a table"))
6623 (org-table-find-dataline)
6624 (org-table-check-inside-data-field)
6625 (let* ((col (org-table-current-column))
6626 (beg (org-table-begin))
6627 (end (org-table-end))
6628 ;; Current cursor position
6629 (linepos (org-current-line))
6630 (colpos col))
6631 (goto-char beg)
6632 (while (< (point) end)
6633 (if (org-at-table-hline-p)
6635 (org-table-goto-column col t)
6636 (and (looking-at "|[^|\n]+|")
6637 (replace-match "|")))
6638 (beginning-of-line 2))
6639 (move-marker end nil)
6640 (goto-line linepos)
6641 (org-table-goto-column colpos)
6642 (org-table-align)
6643 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6644 col -1 col)))
6646 (defun org-table-move-column-right ()
6647 "Move column to the right."
6648 (interactive)
6649 (org-table-move-column nil))
6650 (defun org-table-move-column-left ()
6651 "Move column to the left."
6652 (interactive)
6653 (org-table-move-column 'left))
6655 (defun org-table-move-column (&optional left)
6656 "Move the current column to the right. With arg LEFT, move to the left."
6657 (interactive "P")
6658 (if (not (org-at-table-p))
6659 (error "Not at a table"))
6660 (org-table-find-dataline)
6661 (org-table-check-inside-data-field)
6662 (let* ((col (org-table-current-column))
6663 (col1 (if left (1- col) col))
6664 (beg (org-table-begin))
6665 (end (org-table-end))
6666 ;; Current cursor position
6667 (linepos (org-current-line))
6668 (colpos (if left (1- col) (1+ col))))
6669 (if (and left (= col 1))
6670 (error "Cannot move column further left"))
6671 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6672 (error "Cannot move column further right"))
6673 (goto-char beg)
6674 (while (< (point) end)
6675 (if (org-at-table-hline-p)
6677 (org-table-goto-column col1 t)
6678 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6679 (replace-match "|\\2|\\1|")))
6680 (beginning-of-line 2))
6681 (move-marker end nil)
6682 (goto-line linepos)
6683 (org-table-goto-column colpos)
6684 (org-table-align)
6685 (org-table-fix-formulas
6686 "$" (list (cons (number-to-string col) (number-to-string colpos))
6687 (cons (number-to-string colpos) (number-to-string col))))))
6689 (defun org-table-move-row-down ()
6690 "Move table row down."
6691 (interactive)
6692 (org-table-move-row nil))
6693 (defun org-table-move-row-up ()
6694 "Move table row up."
6695 (interactive)
6696 (org-table-move-row 'up))
6698 (defun org-table-move-row (&optional up)
6699 "Move the current table line down. With arg UP, move it up."
6700 (interactive "P")
6701 (let* ((col (current-column))
6702 (pos (point))
6703 (hline1p (save-excursion (beginning-of-line 1)
6704 (looking-at org-table-hline-regexp)))
6705 (dline1 (org-table-current-dline))
6706 (dline2 (+ dline1 (if up -1 1)))
6707 (tonew (if up 0 2))
6708 txt hline2p)
6709 (beginning-of-line tonew)
6710 (unless (org-at-table-p)
6711 (goto-char pos)
6712 (error "Cannot move row further"))
6713 (setq hline2p (looking-at org-table-hline-regexp))
6714 (goto-char pos)
6715 (beginning-of-line 1)
6716 (setq pos (point))
6717 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6718 (delete-region (point) (1+ (point-at-eol)))
6719 (beginning-of-line tonew)
6720 (insert txt)
6721 (beginning-of-line 0)
6722 (move-to-column col)
6723 (unless (or hline1p hline2p)
6724 (org-table-fix-formulas
6725 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6726 (cons (number-to-string dline2) (number-to-string dline1)))))))
6728 (defun org-table-insert-row (&optional arg)
6729 "Insert a new row above the current line into the table.
6730 With prefix ARG, insert below the current line."
6731 (interactive "P")
6732 (if (not (org-at-table-p))
6733 (error "Not at a table"))
6734 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6735 (new (org-table-clean-line line)))
6736 ;; Fix the first field if necessary
6737 (if (string-match "^[ \t]*| *[#$] *|" line)
6738 (setq new (replace-match (match-string 0 line) t t new)))
6739 (beginning-of-line (if arg 2 1))
6740 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6741 (beginning-of-line 0)
6742 (re-search-forward "| ?" (point-at-eol) t)
6743 (and (or org-table-may-need-update org-table-overlay-coordinates)
6744 (org-table-align))
6745 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6747 (defun org-table-insert-hline (&optional above)
6748 "Insert a horizontal-line below the current line into the table.
6749 With prefix ABOVE, insert above the current line."
6750 (interactive "P")
6751 (if (not (org-at-table-p))
6752 (error "Not at a table"))
6753 (let ((line (org-table-clean-line
6754 (buffer-substring (point-at-bol) (point-at-eol))))
6755 (col (current-column)))
6756 (while (string-match "|\\( +\\)|" line)
6757 (setq line (replace-match
6758 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6759 ?-) "|") t t line)))
6760 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6761 (beginning-of-line (if above 1 2))
6762 (insert line "\n")
6763 (beginning-of-line (if above 1 -1))
6764 (move-to-column col)
6765 (and org-table-overlay-coordinates (org-table-align))))
6767 (defun org-table-hline-and-move (&optional same-column)
6768 "Insert a hline and move to the row below that line."
6769 (interactive "P")
6770 (let ((col (org-table-current-column)))
6771 (org-table-maybe-eval-formula)
6772 (org-table-maybe-recalculate-line)
6773 (org-table-insert-hline)
6774 (end-of-line 2)
6775 (if (looking-at "\n[ \t]*|-")
6776 (progn (insert "\n|") (org-table-align))
6777 (org-table-next-field))
6778 (if same-column (org-table-goto-column col))))
6780 (defun org-table-clean-line (s)
6781 "Convert a table line S into a string with only \"|\" and space.
6782 In particular, this does handle wide and invisible characters."
6783 (if (string-match "^[ \t]*|-" s)
6784 ;; It's a hline, just map the characters
6785 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6786 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6787 (setq s (replace-match
6788 (concat "|" (make-string (org-string-width (match-string 1 s))
6789 ?\ ) "|")
6790 t t s)))
6793 (defun org-table-kill-row ()
6794 "Delete the current row or horizontal line from the table."
6795 (interactive)
6796 (if (not (org-at-table-p))
6797 (error "Not at a table"))
6798 (let ((col (current-column))
6799 (dline (org-table-current-dline)))
6800 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6801 (if (not (org-at-table-p)) (beginning-of-line 0))
6802 (move-to-column col)
6803 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6804 dline -1 dline)))
6807 (defun org-table-sort-lines (with-case &optional sorting-type)
6808 "Sort table lines according to the column at point.
6810 The position of point indicates the column to be used for
6811 sorting, and the range of lines is the range between the nearest
6812 horizontal separator lines, or the entire table of no such lines
6813 exist. If point is before the first column, you will be prompted
6814 for the sorting column. If there is an active region, the mark
6815 specifies the first line and the sorting column, while point
6816 should be in the last line to be included into the sorting.
6818 The command then prompts for the sorting type which can be
6819 alphabetically, numerically, or by time (as given in a time stamp
6820 in the field). Sorting in reverse order is also possible.
6822 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6824 If SORTING-TYPE is specified when this function is called from a Lisp
6825 program, no prompting will take place. SORTING-TYPE must be a character,
6826 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6827 should be done in reverse order."
6828 (interactive "P")
6829 (let* ((thisline (org-current-line))
6830 (thiscol (org-table-current-column))
6831 beg end bcol ecol tend tbeg column lns pos)
6832 (when (equal thiscol 0)
6833 (if (interactive-p)
6834 (setq thiscol
6835 (string-to-number
6836 (read-string "Use column N for sorting: ")))
6837 (setq thiscol 1))
6838 (org-table-goto-column thiscol))
6839 (org-table-check-inside-data-field)
6840 (if (org-region-active-p)
6841 (progn
6842 (setq beg (region-beginning) end (region-end))
6843 (goto-char beg)
6844 (setq column (org-table-current-column)
6845 beg (point-at-bol))
6846 (goto-char end)
6847 (setq end (point-at-bol 2)))
6848 (setq column (org-table-current-column)
6849 pos (point)
6850 tbeg (org-table-begin)
6851 tend (org-table-end))
6852 (if (re-search-backward org-table-hline-regexp tbeg t)
6853 (setq beg (point-at-bol 2))
6854 (goto-char tbeg)
6855 (setq beg (point-at-bol 1)))
6856 (goto-char pos)
6857 (if (re-search-forward org-table-hline-regexp tend t)
6858 (setq beg (point-at-bol 0))
6859 (goto-char tend)
6860 (setq end (point-at-bol))))
6861 (setq beg (move-marker (make-marker) beg)
6862 end (move-marker (make-marker) end))
6863 (untabify beg end)
6864 (goto-char beg)
6865 (org-table-goto-column column)
6866 (skip-chars-backward "^|")
6867 (setq bcol (current-column))
6868 (org-table-goto-column (1+ column))
6869 (skip-chars-backward "^|")
6870 (setq ecol (1- (current-column)))
6871 (org-table-goto-column column)
6872 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6873 (org-split-string (buffer-substring beg end) "\n")))
6874 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6875 (delete-region beg end)
6876 (move-marker beg nil)
6877 (move-marker end nil)
6878 (insert (mapconcat 'cdr lns "\n") "\n")
6879 (goto-line thisline)
6880 (org-table-goto-column thiscol)
6881 (message "%d lines sorted, based on column %d" (length lns) column)))
6883 (defun org-table-cut-region (beg end)
6884 "Copy region in table to the clipboard and blank all relevant fields."
6885 (interactive "r")
6886 (org-table-copy-region beg end 'cut))
6888 (defun org-table-copy-region (beg end &optional cut)
6889 "Copy rectangular region in table to clipboard.
6890 A special clipboard is used which can only be accessed
6891 with `org-table-paste-rectangle'."
6892 (interactive "rP")
6893 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6894 region cols
6895 (rpl (if cut " " nil)))
6896 (goto-char beg)
6897 (org-table-check-inside-data-field)
6898 (setq l01 (org-current-line)
6899 c01 (org-table-current-column))
6900 (goto-char end)
6901 (org-table-check-inside-data-field)
6902 (setq l02 (org-current-line)
6903 c02 (org-table-current-column))
6904 (setq l1 (min l01 l02) l2 (max l01 l02)
6905 c1 (min c01 c02) c2 (max c01 c02))
6906 (catch 'exit
6907 (while t
6908 (catch 'nextline
6909 (if (> l1 l2) (throw 'exit t))
6910 (goto-line l1)
6911 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6912 (setq cols nil ic1 c1 ic2 c2)
6913 (while (< ic1 (1+ ic2))
6914 (push (org-table-get-field ic1 rpl) cols)
6915 (setq ic1 (1+ ic1)))
6916 (push (nreverse cols) region)
6917 (setq l1 (1+ l1)))))
6918 (setq org-table-clip (nreverse region))
6919 (if cut (org-table-align))
6920 org-table-clip))
6922 (defun org-table-paste-rectangle ()
6923 "Paste a rectangular region into a table.
6924 The upper right corner ends up in the current field. All involved fields
6925 will be overwritten. If the rectangle does not fit into the present table,
6926 the table is enlarged as needed. The process ignores horizontal separator
6927 lines."
6928 (interactive)
6929 (unless (and org-table-clip (listp org-table-clip))
6930 (error "First cut/copy a region to paste!"))
6931 (org-table-check-inside-data-field)
6932 (let* ((clip org-table-clip)
6933 (line (org-current-line))
6934 (col (org-table-current-column))
6935 (org-enable-table-editor t)
6936 (org-table-automatic-realign nil)
6937 c cols field)
6938 (while (setq cols (pop clip))
6939 (while (org-at-table-hline-p) (beginning-of-line 2))
6940 (if (not (org-at-table-p))
6941 (progn (end-of-line 0) (org-table-next-field)))
6942 (setq c col)
6943 (while (setq field (pop cols))
6944 (org-table-goto-column c nil 'force)
6945 (org-table-get-field nil field)
6946 (setq c (1+ c)))
6947 (beginning-of-line 2))
6948 (goto-line line)
6949 (org-table-goto-column col)
6950 (org-table-align)))
6952 (defun org-table-convert ()
6953 "Convert from `org-mode' table to table.el and back.
6954 Obviously, this only works within limits. When an Org-mode table is
6955 converted to table.el, all horizontal separator lines get lost, because
6956 table.el uses these as cell boundaries and has no notion of horizontal lines.
6957 A table.el table can be converted to an Org-mode table only if it does not
6958 do row or column spanning. Multiline cells will become multiple cells.
6959 Beware, Org-mode does not test if the table can be successfully converted - it
6960 blindly applies a recipe that works for simple tables."
6961 (interactive)
6962 (require 'table)
6963 (if (org-at-table.el-p)
6964 ;; convert to Org-mode table
6965 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6966 (end (move-marker (make-marker) (org-table-end t))))
6967 (table-unrecognize-region beg end)
6968 (goto-char beg)
6969 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6970 (replace-match ""))
6971 (goto-char beg))
6972 (if (org-at-table-p)
6973 ;; convert to table.el table
6974 (let ((beg (move-marker (make-marker) (org-table-begin)))
6975 (end (move-marker (make-marker) (org-table-end))))
6976 ;; first, get rid of all horizontal lines
6977 (goto-char beg)
6978 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6979 (replace-match ""))
6980 ;; insert a hline before first
6981 (goto-char beg)
6982 (org-table-insert-hline 'above)
6983 (beginning-of-line -1)
6984 ;; insert a hline after each line
6985 (while (progn (beginning-of-line 3) (< (point) end))
6986 (org-table-insert-hline))
6987 (goto-char beg)
6988 (setq end (move-marker end (org-table-end)))
6989 ;; replace "+" at beginning and ending of hlines
6990 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6991 (replace-match "\\1+-"))
6992 (goto-char beg)
6993 (while (re-search-forward "-|[ \t]*$" end t)
6994 (replace-match "-+"))
6995 (goto-char beg)))))
6997 (defun org-table-wrap-region (arg)
6998 "Wrap several fields in a column like a paragraph.
6999 This is useful if you'd like to spread the contents of a field over several
7000 lines, in order to keep the table compact.
7002 If there is an active region, and both point and mark are in the same column,
7003 the text in the column is wrapped to minimum width for the given number of
7004 lines. Generally, this makes the table more compact. A prefix ARG may be
7005 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7006 formats the selected text to two lines. If the region was longer than two
7007 lines, the remaining lines remain empty. A negative prefix argument reduces
7008 the current number of lines by that amount. The wrapped text is pasted back
7009 into the table. If you formatted it to more lines than it was before, fields
7010 further down in the table get overwritten - so you might need to make space in
7011 the table first.
7013 If there is no region, the current field is split at the cursor position and
7014 the text fragment to the right of the cursor is prepended to the field one
7015 line down.
7017 If there is no region, but you specify a prefix ARG, the current field gets
7018 blank, and the content is appended to the field above."
7019 (interactive "P")
7020 (org-table-check-inside-data-field)
7021 (if (org-region-active-p)
7022 ;; There is a region: fill as a paragraph
7023 (let* ((beg (region-beginning))
7024 (cline (save-excursion (goto-char beg) (org-current-line)))
7025 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
7026 nlines)
7027 (org-table-cut-region (region-beginning) (region-end))
7028 (if (> (length (car org-table-clip)) 1)
7029 (error "Region must be limited to single column"))
7030 (setq nlines (if arg
7031 (if (< arg 1)
7032 (+ (length org-table-clip) arg)
7033 arg)
7034 (length org-table-clip)))
7035 (setq org-table-clip
7036 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7037 nil nlines)))
7038 (goto-line cline)
7039 (org-table-goto-column ccol)
7040 (org-table-paste-rectangle))
7041 ;; No region, split the current field at point
7042 (if arg
7043 ;; combine with field above
7044 (let ((s (org-table-blank-field))
7045 (col (org-table-current-column)))
7046 (beginning-of-line 0)
7047 (while (org-at-table-hline-p) (beginning-of-line 0))
7048 (org-table-goto-column col)
7049 (skip-chars-forward "^|")
7050 (skip-chars-backward " ")
7051 (insert " " (org-trim s))
7052 (org-table-align))
7053 ;; split field
7054 (when (looking-at "\\([^|]+\\)+|")
7055 (let ((s (match-string 1)))
7056 (replace-match " |")
7057 (goto-char (match-beginning 0))
7058 (org-table-next-row)
7059 (insert (org-trim s) " ")
7060 (org-table-align))))))
7062 (defvar org-field-marker nil)
7064 (defun org-table-edit-field (arg)
7065 "Edit table field in a different window.
7066 This is mainly useful for fields that contain hidden parts.
7067 When called with a \\[universal-argument] prefix, just make the full field visible so that
7068 it can be edited in place."
7069 (interactive "P")
7070 (if arg
7071 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
7072 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
7073 (remove-text-properties b e '(org-cwidth t invisible t
7074 display t intangible t))
7075 (if (and (boundp 'font-lock-mode) font-lock-mode)
7076 (font-lock-fontify-block)))
7077 (let ((pos (move-marker (make-marker) (point)))
7078 (field (org-table-get-field))
7079 (cw (current-window-configuration))
7081 (switch-to-buffer-other-window "*Org tmp*")
7082 (erase-buffer)
7083 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7084 (org-mode)
7085 (goto-char (setq p (point-max)))
7086 (insert (org-trim field))
7087 (remove-text-properties p (point-max)
7088 '(invisible t org-cwidth t display t
7089 intangible t))
7090 (goto-char p)
7091 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
7092 (org-set-local 'org-window-configuration cw)
7093 (org-set-local 'org-field-marker pos)
7094 (message "Edit and finish with C-c C-c"))))
7096 (defun org-table-finish-edit-field ()
7097 "Finish editing a table data field.
7098 Remove all newline characters, insert the result into the table, realign
7099 the table and kill the editing buffer."
7100 (let ((pos org-field-marker)
7101 (cw org-window-configuration)
7102 (cb (current-buffer))
7103 text)
7104 (goto-char (point-min))
7105 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
7106 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
7107 (replace-match " "))
7108 (setq text (org-trim (buffer-string)))
7109 (set-window-configuration cw)
7110 (kill-buffer cb)
7111 (select-window (get-buffer-window (marker-buffer pos)))
7112 (goto-char pos)
7113 (move-marker pos nil)
7114 (org-table-check-inside-data-field)
7115 (org-table-get-field nil text)
7116 (org-table-align)
7117 (message "New field value inserted")))
7119 (defun org-trim (s)
7120 "Remove whitespace at beginning and end of string."
7121 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7122 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7125 (defun org-wrap (string &optional width lines)
7126 "Wrap string to either a number of lines, or a width in characters.
7127 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7128 that costs. If there is a word longer than WIDTH, the text is actually
7129 wrapped to the length of that word.
7130 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7131 many lines, whatever width that takes.
7132 The return value is a list of lines, without newlines at the end."
7133 (let* ((words (org-split-string string "[ \t\n]+"))
7134 (maxword (apply 'max (mapcar 'org-string-width words)))
7135 w ll)
7136 (cond (width
7137 (org-do-wrap words (max maxword width)))
7138 (lines
7139 (setq w maxword)
7140 (setq ll (org-do-wrap words maxword))
7141 (if (<= (length ll) lines)
7143 (setq ll words)
7144 (while (> (length ll) lines)
7145 (setq w (1+ w))
7146 (setq ll (org-do-wrap words w)))
7147 ll))
7148 (t (error "Cannot wrap this")))))
7151 (defun org-do-wrap (words width)
7152 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7153 (let (lines line)
7154 (while words
7155 (setq line (pop words))
7156 (while (and words (< (+ (length line) (length (car words))) width))
7157 (setq line (concat line " " (pop words))))
7158 (setq lines (push line lines)))
7159 (nreverse lines)))
7161 (defun org-split-string (string &optional separators)
7162 "Splits STRING into substrings at SEPARATORS.
7163 No empty strings are returned if there are matches at the beginning
7164 and end of string."
7165 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7166 (start 0)
7167 notfirst
7168 (list nil))
7169 (while (and (string-match rexp string
7170 (if (and notfirst
7171 (= start (match-beginning 0))
7172 (< start (length string)))
7173 (1+ start) start))
7174 (< (match-beginning 0) (length string)))
7175 (setq notfirst t)
7176 (or (eq (match-beginning 0) 0)
7177 (and (eq (match-beginning 0) (match-end 0))
7178 (eq (match-beginning 0) start))
7179 (setq list
7180 (cons (substring string start (match-beginning 0))
7181 list)))
7182 (setq start (match-end 0)))
7183 (or (eq start (length string))
7184 (setq list
7185 (cons (substring string start)
7186 list)))
7187 (nreverse list)))
7189 (defun org-table-map-tables (function)
7190 "Apply FUNCTION to the start of all tables in the buffer."
7191 (save-excursion
7192 (save-restriction
7193 (widen)
7194 (goto-char (point-min))
7195 (while (re-search-forward org-table-any-line-regexp nil t)
7196 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7197 (beginning-of-line 1)
7198 (if (looking-at org-table-line-regexp)
7199 (save-excursion (funcall function)))
7200 (re-search-forward org-table-any-border-regexp nil 1))))
7201 (message "Mapping tables: done"))
7203 (defvar org-timecnt) ; dynamically scoped parameter
7205 (defun org-table-sum (&optional beg end nlast)
7206 "Sum numbers in region of current table column.
7207 The result will be displayed in the echo area, and will be available
7208 as kill to be inserted with \\[yank].
7210 If there is an active region, it is interpreted as a rectangle and all
7211 numbers in that rectangle will be summed. If there is no active
7212 region and point is located in a table column, sum all numbers in that
7213 column.
7215 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7216 numbers are assumed to be times as well (in decimal hours) and the
7217 numbers are added as such.
7219 If NLAST is a number, only the NLAST fields will actually be summed."
7220 (interactive)
7221 (save-excursion
7222 (let (col (org-timecnt 0) diff h m s org-table-clip)
7223 (cond
7224 ((and beg end)) ; beg and end given explicitly
7225 ((org-region-active-p)
7226 (setq beg (region-beginning) end (region-end)))
7228 (setq col (org-table-current-column))
7229 (goto-char (org-table-begin))
7230 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7231 (error "No table data"))
7232 (org-table-goto-column col)
7233 (setq beg (point))
7234 (goto-char (org-table-end))
7235 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7236 (error "No table data"))
7237 (org-table-goto-column col)
7238 (setq end (point))))
7239 (let* ((items (apply 'append (org-table-copy-region beg end)))
7240 (items1 (cond ((not nlast) items)
7241 ((>= nlast (length items)) items)
7242 (t (setq items (reverse items))
7243 (setcdr (nthcdr (1- nlast) items) nil)
7244 (nreverse items))))
7245 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7246 items1)))
7247 (res (apply '+ numbers))
7248 (sres (if (= org-timecnt 0)
7249 (format "%g" res)
7250 (setq diff (* 3600 res)
7251 h (floor (/ diff 3600)) diff (mod diff 3600)
7252 m (floor (/ diff 60)) diff (mod diff 60)
7253 s diff)
7254 (format "%d:%02d:%02d" h m s))))
7255 (kill-new sres)
7256 (if (interactive-p)
7257 (message "%s"
7258 (substitute-command-keys
7259 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7260 (length numbers) sres))))
7261 sres))))
7263 (defun org-table-get-number-for-summing (s)
7264 (let (n)
7265 (if (string-match "^ *|? *" s)
7266 (setq s (replace-match "" nil nil s)))
7267 (if (string-match " *|? *$" s)
7268 (setq s (replace-match "" nil nil s)))
7269 (setq n (string-to-number s))
7270 (cond
7271 ((and (string-match "0" s)
7272 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7273 ((string-match "\\`[ \t]+\\'" s) nil)
7274 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7275 (let ((h (string-to-number (or (match-string 1 s) "0")))
7276 (m (string-to-number (or (match-string 2 s) "0")))
7277 (s (string-to-number (or (match-string 4 s) "0"))))
7278 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7279 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7280 ((equal n 0) nil)
7281 (t n))))
7283 (defun org-table-current-field-formula (&optional key noerror)
7284 "Return the formula active for the current field.
7285 Assumes that specials are in place.
7286 If KEY is given, return the key to this formula.
7287 Otherwise return the formula preceeded with \"=\" or \":=\"."
7288 (let* ((name (car (rassoc (list (org-current-line)
7289 (org-table-current-column))
7290 org-table-named-field-locations)))
7291 (col (org-table-current-column))
7292 (scol (int-to-string col))
7293 (ref (format "@%d$%d" (org-table-current-dline) col))
7294 (stored-list (org-table-get-stored-formulas noerror))
7295 (ass (or (assoc name stored-list)
7296 (assoc ref stored-list)
7297 (assoc scol stored-list))))
7298 (if key
7299 (car ass)
7300 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7301 (cdr ass))))))
7303 (defun org-table-get-formula (&optional equation named)
7304 "Read a formula from the minibuffer, offer stored formula as default.
7305 When NAMED is non-nil, look for a named equation."
7306 (let* ((stored-list (org-table-get-stored-formulas))
7307 (name (car (rassoc (list (org-current-line)
7308 (org-table-current-column))
7309 org-table-named-field-locations)))
7310 (ref (format "@%d$%d" (org-table-current-dline)
7311 (org-table-current-column)))
7312 (refass (assoc ref stored-list))
7313 (scol (if named
7314 (if name name ref)
7315 (int-to-string (org-table-current-column))))
7316 (dummy (and (or name refass) (not named)
7317 (not (y-or-n-p "Replace field formula with column formula? " ))
7318 (error "Abort")))
7319 (name (or name ref))
7320 (org-table-may-need-update nil)
7321 (stored (cdr (assoc scol stored-list)))
7322 (eq (cond
7323 ((and stored equation (string-match "^ *=? *$" equation))
7324 stored)
7325 ((stringp equation)
7326 equation)
7327 (t (org-table-formula-from-user
7328 (read-string
7329 (org-table-formula-to-user
7330 (format "%s formula %s%s="
7331 (if named "Field" "Column")
7332 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
7333 scol))
7334 (if stored (org-table-formula-to-user stored) "")
7335 'org-table-formula-history
7336 )))))
7337 mustsave)
7338 (when (not (string-match "\\S-" eq))
7339 ;; remove formula
7340 (setq stored-list (delq (assoc scol stored-list) stored-list))
7341 (org-table-store-formulas stored-list)
7342 (error "Formula removed"))
7343 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7344 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7345 (if (and name (not named))
7346 ;; We set the column equation, delete the named one.
7347 (setq stored-list (delq (assoc name stored-list) stored-list)
7348 mustsave t))
7349 (if stored
7350 (setcdr (assoc scol stored-list) eq)
7351 (setq stored-list (cons (cons scol eq) stored-list)))
7352 (if (or mustsave (not (equal stored eq)))
7353 (org-table-store-formulas stored-list))
7354 eq))
7356 (defun org-table-store-formulas (alist)
7357 "Store the list of formulas below the current table."
7358 (setq alist (sort alist 'org-table-formula-less-p))
7359 (save-excursion
7360 (goto-char (org-table-end))
7361 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7362 (progn
7363 ;; don't overwrite TBLFM, we might use text properties to store stuff
7364 (goto-char (match-beginning 2))
7365 (delete-region (match-beginning 2) (match-end 0)))
7366 (insert "#+TBLFM:"))
7367 (insert " "
7368 (mapconcat (lambda (x)
7369 (concat
7370 (if (equal (string-to-char (car x)) ?@) "" "$")
7371 (car x) "=" (cdr x)))
7372 alist "::")
7373 "\n")))
7375 (defsubst org-table-formula-make-cmp-string (a)
7376 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
7377 (concat
7378 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
7379 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
7380 (if (match-end 5) (concat "@@" (match-string 5 a))))))
7382 (defun org-table-formula-less-p (a b)
7383 "Compare two formulas for sorting."
7384 (let ((as (org-table-formula-make-cmp-string (car a)))
7385 (bs (org-table-formula-make-cmp-string (car b))))
7386 (and as bs (string< as bs))))
7388 (defun org-table-get-stored-formulas (&optional noerror)
7389 "Return an alist with the stored formulas directly after current table."
7390 (interactive)
7391 (let (scol eq eq-alist strings string seen)
7392 (save-excursion
7393 (goto-char (org-table-end))
7394 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7395 (setq strings (org-split-string (match-string 2) " *:: *"))
7396 (while (setq string (pop strings))
7397 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7398 (setq scol (if (match-end 2)
7399 (match-string 2 string)
7400 (match-string 1 string))
7401 eq (match-string 3 string)
7402 eq-alist (cons (cons scol eq) eq-alist))
7403 (if (member scol seen)
7404 (if noerror
7405 (progn
7406 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7407 (ding)
7408 (sit-for 2))
7409 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
7410 (push scol seen))))))
7411 (nreverse eq-alist)))
7413 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7414 "Modify the equations after the table structure has been edited.
7415 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7416 For all numbers larger than LIMIT, shift them by DELTA."
7417 (save-excursion
7418 (goto-char (org-table-end))
7419 (when (looking-at "#\\+TBLFM:")
7420 (let ((re (concat key "\\([0-9]+\\)"))
7421 (re2
7422 (when remove
7423 (if (equal key "$")
7424 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7425 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7426 s n a)
7427 (when remove
7428 (while (re-search-forward re2 (point-at-eol) t)
7429 (replace-match "")))
7430 (while (re-search-forward re (point-at-eol) t)
7431 (setq s (match-string 1) n (string-to-number s))
7432 (cond
7433 ((setq a (assoc s replace))
7434 (replace-match (concat key (cdr a)) t t))
7435 ((and limit (> n limit))
7436 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7438 (defun org-table-get-specials ()
7439 "Get the column names and local parameters for this table."
7440 (save-excursion
7441 (let ((beg (org-table-begin)) (end (org-table-end))
7442 names name fields fields1 field cnt
7443 c v l line col types dlines hlines)
7444 (setq org-table-column-names nil
7445 org-table-local-parameters nil
7446 org-table-named-field-locations nil
7447 org-table-current-begin-line nil
7448 org-table-current-begin-pos nil
7449 org-table-current-line-types nil)
7450 (goto-char beg)
7451 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7452 (setq names (org-split-string (match-string 1) " *| *")
7453 cnt 1)
7454 (while (setq name (pop names))
7455 (setq cnt (1+ cnt))
7456 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7457 (push (cons name (int-to-string cnt)) org-table-column-names))))
7458 (setq org-table-column-names (nreverse org-table-column-names))
7459 (setq org-table-column-name-regexp
7460 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7461 (goto-char beg)
7462 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7463 (setq fields (org-split-string (match-string 1) " *| *"))
7464 (while (setq field (pop fields))
7465 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7466 (push (cons (match-string 1 field) (match-string 2 field))
7467 org-table-local-parameters))))
7468 (goto-char beg)
7469 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7470 (setq c (match-string 1)
7471 fields (org-split-string (match-string 2) " *| *"))
7472 (save-excursion
7473 (beginning-of-line (if (equal c "_") 2 0))
7474 (setq line (org-current-line) col 1)
7475 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7476 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7477 (while (and fields1 (setq field (pop fields)))
7478 (setq v (pop fields1) col (1+ col))
7479 (when (and (stringp field) (stringp v)
7480 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7481 (push (cons field v) org-table-local-parameters)
7482 (push (list field line col) org-table-named-field-locations))))
7483 ;; Analyse the line types
7484 (goto-char beg)
7485 (setq org-table-current-begin-line (org-current-line)
7486 org-table-current-begin-pos (point)
7487 l org-table-current-begin-line)
7488 (while (looking-at "[ \t]*|\\(-\\)?")
7489 (push (if (match-end 1) 'hline 'dline) types)
7490 (if (match-end 1) (push l hlines) (push l dlines))
7491 (beginning-of-line 2)
7492 (setq l (1+ l)))
7493 (setq org-table-current-line-types (apply 'vector (nreverse types))
7494 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7495 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7497 (defun org-table-maybe-eval-formula ()
7498 "Check if the current field starts with \"=\" or \":=\".
7499 If yes, store the formula and apply it."
7500 ;; We already know we are in a table. Get field will only return a formula
7501 ;; when appropriate. It might return a separator line, but no problem.
7502 (when org-table-formula-evaluate-inline
7503 (let* ((field (org-trim (or (org-table-get-field) "")))
7504 named eq)
7505 (when (string-match "^:?=\\(.*\\)" field)
7506 (setq named (equal (string-to-char field) ?:)
7507 eq (match-string 1 field))
7508 (if (or (fboundp 'calc-eval)
7509 (equal (substring eq 0 (min 2 (length eq))) "'("))
7510 (org-table-eval-formula (if named '(4) nil)
7511 (org-table-formula-from-user eq))
7512 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7514 (defvar org-recalc-commands nil
7515 "List of commands triggering the recalculation of a line.
7516 Will be filled automatically during use.")
7518 (defvar org-recalc-marks
7519 '((" " . "Unmarked: no special line, no automatic recalculation")
7520 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7521 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7522 ("!" . "Column name definition line. Reference in formula as $name.")
7523 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7524 ("_" . "Names for values in row below this one.")
7525 ("^" . "Names for values in row above this one.")))
7527 (defun org-table-rotate-recalc-marks (&optional newchar)
7528 "Rotate the recalculation mark in the first column.
7529 If in any row, the first field is not consistent with a mark,
7530 insert a new column for the markers.
7531 When there is an active region, change all the lines in the region,
7532 after prompting for the marking character.
7533 After each change, a message will be displayed indicating the meaning
7534 of the new mark."
7535 (interactive)
7536 (unless (org-at-table-p) (error "Not at a table"))
7537 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7538 (beg (org-table-begin))
7539 (end (org-table-end))
7540 (l (org-current-line))
7541 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7542 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7543 (have-col
7544 (save-excursion
7545 (goto-char beg)
7546 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7547 (col (org-table-current-column))
7548 (forcenew (car (assoc newchar org-recalc-marks)))
7549 epos new)
7550 (when l1
7551 (message "Change region to what mark? Type # * ! $ or SPC: ")
7552 (setq newchar (char-to-string (read-char-exclusive))
7553 forcenew (car (assoc newchar org-recalc-marks))))
7554 (if (and newchar (not forcenew))
7555 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7556 newchar))
7557 (if l1 (goto-line l1))
7558 (save-excursion
7559 (beginning-of-line 1)
7560 (unless (looking-at org-table-dataline-regexp)
7561 (error "Not at a table data line")))
7562 (unless have-col
7563 (org-table-goto-column 1)
7564 (org-table-insert-column)
7565 (org-table-goto-column (1+ col)))
7566 (setq epos (point-at-eol))
7567 (save-excursion
7568 (beginning-of-line 1)
7569 (org-table-get-field
7570 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7571 (concat " "
7572 (setq new (or forcenew
7573 (cadr (member (match-string 1) marks))))
7574 " ")
7575 " # ")))
7576 (if (and l1 l2)
7577 (progn
7578 (goto-line l1)
7579 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7580 (and (looking-at org-table-dataline-regexp)
7581 (org-table-get-field 1 (concat " " new " "))))
7582 (goto-line l1)))
7583 (if (not (= epos (point-at-eol))) (org-table-align))
7584 (goto-line l)
7585 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7587 (defun org-table-maybe-recalculate-line ()
7588 "Recompute the current line if marked for it, and if we haven't just done it."
7589 (interactive)
7590 (and org-table-allow-automatic-line-recalculation
7591 (not (and (memq last-command org-recalc-commands)
7592 (equal org-last-recalc-line (org-current-line))))
7593 (save-excursion (beginning-of-line 1)
7594 (looking-at org-table-auto-recalculate-regexp))
7595 (org-table-recalculate) t))
7597 (defvar org-table-formula-debug nil
7598 "Non-nil means, debug table formulas.
7599 When nil, simply write \"#ERROR\" in corrupted fields.")
7600 (make-variable-buffer-local 'org-table-formula-debug)
7602 (defvar modes)
7603 (defsubst org-set-calc-mode (var &optional value)
7604 (if (stringp var)
7605 (setq var (assoc var '(("D" calc-angle-mode deg)
7606 ("R" calc-angle-mode rad)
7607 ("F" calc-prefer-frac t)
7608 ("S" calc-symbolic-mode t)))
7609 value (nth 2 var) var (nth 1 var)))
7610 (if (memq var modes)
7611 (setcar (cdr (memq var modes)) value)
7612 (cons var (cons value modes)))
7613 modes)
7615 (defun org-table-eval-formula (&optional arg equation
7616 suppress-align suppress-const
7617 suppress-store suppress-analysis)
7618 "Replace the table field value at the cursor by the result of a calculation.
7620 This function makes use of Dave Gillespie's Calc package, in my view the
7621 most exciting program ever written for GNU Emacs. So you need to have Calc
7622 installed in order to use this function.
7624 In a table, this command replaces the value in the current field with the
7625 result of a formula. It also installs the formula as the \"current\" column
7626 formula, by storing it in a special line below the table. When called
7627 with a `C-u' prefix, the current field must ba a named field, and the
7628 formula is installed as valid in only this specific field.
7630 When called with two `C-u' prefixes, insert the active equation
7631 for the field back into the current field, so that it can be
7632 edited there. This is useful in order to use \\[org-table-show-reference]
7633 to check the referenced fields.
7635 When called, the command first prompts for a formula, which is read in
7636 the minibuffer. Previously entered formulas are available through the
7637 history list, and the last used formula is offered as a default.
7638 These stored formulas are adapted correctly when moving, inserting, or
7639 deleting columns with the corresponding commands.
7641 The formula can be any algebraic expression understood by the Calc package.
7642 For details, see the Org-mode manual.
7644 This function can also be called from Lisp programs and offers
7645 additional arguments: EQUATION can be the formula to apply. If this
7646 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7647 used to speed-up recursive calls by by-passing unnecessary aligns.
7648 SUPPRESS-CONST suppresses the interpretation of constants in the
7649 formula, assuming that this has been done already outside the function.
7650 SUPPRESS-STORE means the formula should not be stored, either because
7651 it is already stored, or because it is a modified equation that should
7652 not overwrite the stored one."
7653 (interactive "P")
7654 (org-table-check-inside-data-field)
7655 (or suppress-analysis (org-table-get-specials))
7656 (if (equal arg '(16))
7657 (let ((eq (org-table-current-field-formula)))
7658 (or eq (error "No equation active for current field"))
7659 (org-table-get-field nil eq)
7660 (org-table-align)
7661 (setq org-table-may-need-update t))
7662 (let* (fields
7663 (ndown (if (integerp arg) arg 1))
7664 (org-table-automatic-realign nil)
7665 (case-fold-search nil)
7666 (down (> ndown 1))
7667 (formula (if (and equation suppress-store)
7668 equation
7669 (org-table-get-formula equation (equal arg '(4)))))
7670 (n0 (org-table-current-column))
7671 (modes (copy-sequence org-calc-default-modes))
7672 (numbers nil) ; was a variable, now fixed default
7673 (keep-empty nil)
7674 n form form0 bw fmt x ev orig c lispp)
7675 ;; Parse the format string. Since we have a lot of modes, this is
7676 ;; a lot of work. However, I think calc still uses most of the time.
7677 (if (string-match ";" formula)
7678 (let ((tmp (org-split-string formula ";")))
7679 (setq formula (car tmp)
7680 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7681 (nth 1 tmp)))
7682 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7683 (setq c (string-to-char (match-string 1 fmt))
7684 n (string-to-number (match-string 2 fmt)))
7685 (if (= c ?p)
7686 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7687 (setq modes (org-set-calc-mode
7688 'calc-float-format
7689 (list (cdr (assoc c '((?n . float) (?f . fix)
7690 (?s . sci) (?e . eng))))
7691 n))))
7692 (setq fmt (replace-match "" t t fmt)))
7693 (if (string-match "[NT]" fmt)
7694 (setq numbers (equal (match-string 0 fmt) "N")
7695 fmt (replace-match "" t t fmt)))
7696 (if (string-match "E" fmt)
7697 (setq keep-empty t
7698 fmt (replace-match "" t t fmt)))
7699 (while (string-match "[DRFS]" fmt)
7700 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7701 (setq fmt (replace-match "" t t fmt)))
7702 (unless (string-match "\\S-" fmt)
7703 (setq fmt nil))))
7704 (if (and (not suppress-const) org-table-formula-use-constants)
7705 (setq formula (org-table-formula-substitute-names formula)))
7706 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7707 (while (> ndown 0)
7708 (setq fields (org-split-string
7709 (org-no-properties
7710 (buffer-substring (point-at-bol) (point-at-eol)))
7711 " *| *"))
7712 (if numbers
7713 (setq fields (mapcar
7714 (lambda (x) (number-to-string (string-to-number x)))
7715 fields)))
7716 (setq ndown (1- ndown))
7717 (setq form (copy-sequence formula)
7718 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7719 ;; Check for old vertical references
7720 (setq form (org-rewrite-old-row-references form))
7721 ;; Insert complex ranges
7722 (while (string-match org-table-range-regexp form)
7723 (setq form
7724 (replace-match
7725 (save-match-data
7726 (org-table-make-reference
7727 (org-table-get-range (match-string 0 form) nil n0)
7728 keep-empty numbers lispp))
7729 t t form)))
7730 ;; Insert simple ranges
7731 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
7732 (setq form
7733 (replace-match
7734 (save-match-data
7735 (org-table-make-reference
7736 (org-sublist
7737 fields (string-to-number (match-string 1 form))
7738 (string-to-number (match-string 2 form)))
7739 keep-empty numbers lispp))
7740 t t form)))
7741 (setq form0 form)
7742 ;; Insert the references to fields in same row
7743 (while (string-match "\\$\\([0-9]+\\)" form)
7744 (setq n (string-to-number (match-string 1 form))
7745 x (nth (1- (if (= n 0) n0 n)) fields))
7746 (unless x (error "Invalid field specifier \"%s\""
7747 (match-string 0 form)))
7748 (setq form (replace-match
7749 (save-match-data
7750 (org-table-make-reference x nil numbers lispp))
7751 t t form)))
7753 (if lispp
7754 (setq ev (condition-case nil
7755 (eval (eval (read form)))
7756 (error "#ERROR"))
7757 ev (if (numberp ev) (number-to-string ev) ev))
7758 (or (fboundp 'calc-eval)
7759 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7760 (setq ev (calc-eval (cons form modes)
7761 (if numbers 'num))))
7763 (when org-table-formula-debug
7764 (with-output-to-temp-buffer "*Substitution History*"
7765 (princ (format "Substitution history of formula
7766 Orig: %s
7767 $xyz-> %s
7768 @r$c-> %s
7769 $1-> %s\n" orig formula form0 form))
7770 (if (listp ev)
7771 (princ (format " %s^\nError: %s"
7772 (make-string (car ev) ?\-) (nth 1 ev)))
7773 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7774 ev (or fmt "NONE")
7775 (if fmt (format fmt (string-to-number ev)) ev)))))
7776 (setq bw (get-buffer-window "*Substitution History*"))
7777 (shrink-window-if-larger-than-buffer bw)
7778 (unless (and (interactive-p) (not ndown))
7779 (unless (let (inhibit-redisplay)
7780 (y-or-n-p "Debugging Formula. Continue to next? "))
7781 (org-table-align)
7782 (error "Abort"))
7783 (delete-window bw)
7784 (message "")))
7785 (if (listp ev) (setq fmt nil ev "#ERROR"))
7786 (org-table-justify-field-maybe
7787 (if fmt (format fmt (string-to-number ev)) ev))
7788 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7789 (call-interactively 'org-return)
7790 (setq ndown 0)))
7791 (and down (org-table-maybe-recalculate-line))
7792 (or suppress-align (and org-table-may-need-update
7793 (org-table-align))))))
7795 (defun org-table-get-range (desc &optional tbeg col highlight)
7796 "Get a calc vector from a column, accorting to descriptor DESC.
7797 Optional arguments TBEG and COL can give the beginning of the table and
7798 the current column, to avoid unnecessary parsing.
7799 HIGHLIGHT means, just highlight the range."
7800 (if (not (equal (string-to-char desc) ?@))
7801 (setq desc (concat "@" desc)))
7802 (save-excursion
7803 (or tbeg (setq tbeg (org-table-begin)))
7804 (or col (setq col (org-table-current-column)))
7805 (let ((thisline (org-current-line))
7806 beg end c1 c2 r1 r2 rangep tmp)
7807 (unless (string-match org-table-range-regexp desc)
7808 (error "Invalid table range specifier `%s'" desc))
7809 (setq rangep (match-end 3)
7810 r1 (and (match-end 1) (match-string 1 desc))
7811 r2 (and (match-end 4) (match-string 4 desc))
7812 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7813 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7815 (and c1 (setq c1 (+ (string-to-number c1)
7816 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7817 (and c2 (setq c2 (+ (string-to-number c2)
7818 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7819 (if (equal r1 "") (setq r1 nil))
7820 (if (equal r2 "") (setq r2 nil))
7821 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7822 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7823 ; (setq r2 (or r2 r1) c2 (or c2 c1))
7824 (if (not r1) (setq r1 thisline))
7825 (if (not r2) (setq r2 thisline))
7826 (if (not c1) (setq c1 col))
7827 (if (not c2) (setq c2 col))
7828 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7829 ;; just one field
7830 (progn
7831 (goto-line r1)
7832 (while (not (looking-at org-table-dataline-regexp))
7833 (beginning-of-line 2))
7834 (prog1 (org-table-get-field c1)
7835 (if highlight (org-table-highlight-rectangle (point) (point)))))
7836 ;; A range, return a vector
7837 ;; First sort the numbers to get a regular ractangle
7838 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7839 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7840 (goto-line r1)
7841 (while (not (looking-at org-table-dataline-regexp))
7842 (beginning-of-line 2))
7843 (org-table-goto-column c1)
7844 (setq beg (point))
7845 (goto-line r2)
7846 (while (not (looking-at org-table-dataline-regexp))
7847 (beginning-of-line 0))
7848 (org-table-goto-column c2)
7849 (setq end (point))
7850 (if highlight
7851 (org-table-highlight-rectangle
7852 beg (progn (skip-chars-forward "^|\n") (point))))
7853 ;; return string representation of calc vector
7854 (apply 'append (org-table-copy-region beg end))))))
7856 (defun org-table-get-descriptor-line (desc &optional cline bline table)
7857 "Analyze descriptor DESC and retrieve the corresponding line number.
7858 The cursor is currently in line CLINE, the table begins in line BLINE,
7859 and TABLE is a vector with line types."
7860 (if (string-match "^[0-9]+$" desc)
7861 (aref org-table-dlines (string-to-number desc))
7862 (setq cline (or cline (org-current-line))
7863 bline (or bline org-table-current-begin-line)
7864 table (or table org-table-current-line-types))
7865 (if (or
7866 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
7867 ;; 1 2 3 4 5 6
7868 (and (not (match-end 3)) (not (match-end 6)))
7869 (and (match-end 3) (match-end 6) (not (match-end 5))))
7870 (error "invalid row descriptor `%s'" desc))
7871 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
7872 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
7873 (odir (and (match-end 5) (match-string 5 desc)))
7874 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
7875 (i (- cline bline))
7876 (rel (and (match-end 6)
7877 (or (and (match-end 1) (not (match-end 3)))
7878 (match-end 5)))))
7879 (if (and hn (not hdir))
7880 (progn
7881 (setq i 0 hdir "+")
7882 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
7883 (if (and (not hn) on (not odir))
7884 (error "should never happen");;(aref org-table-dlines on) FIXME
7885 (if (and hn (> hn 0))
7886 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
7887 (if on
7888 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
7889 (+ bline i)))))
7891 (defun org-find-row-type (table i type backwards relative n)
7892 (let ((l (length table)))
7893 (while (> n 0)
7894 (while (and (setq i (+ i (if backwards -1 1)))
7895 (>= i 0) (< i l)
7896 (not (eq (aref table i) type))
7897 (if (and relative (eq (aref table i) 'hline))
7898 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
7899 t)))
7900 (setq n (1- n)))
7901 (if (or (< i 0) (>= i l))
7902 (error "Row descriptior leads outside table")
7903 i)))
7905 (defun org-rewrite-old-row-references (s)
7906 (if (string-match "&[-+0-9I]" s)
7907 (error "Formula contains old &row reference, please rewrite using @-syntax")
7910 (defun org-table-make-reference (elements keep-empty numbers lispp)
7911 "Convert list ELEMENTS to something appropriate to insert into formula.
7912 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
7913 NUMBERS indicates that everything should be converted to numbers.
7914 LISPP means to return something appropriate for a Lisp list."
7915 (if (stringp elements) ; just a single val
7916 (if lispp
7917 (prin1-to-string (if numbers (string-to-number elements) elements))
7918 (if (equal elements "") (setq elements "0"))
7919 (if numbers (number-to-string (string-to-number elements)) elements))
7920 (unless keep-empty
7921 (setq elements
7922 (delq nil
7923 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
7924 elements))))
7925 (setq elements (or elements '("0")))
7926 (if lispp
7927 (mapconcat 'prin1-to-string
7928 (if numbers (mapcar 'string-to-number elements) elements)
7929 " ")
7930 (concat "[" (mapconcat
7931 (lambda (x)
7932 (if numbers (number-to-string (string-to-number x)) x))
7933 elements
7934 ",") "]"))))
7936 (defun org-table-recalculate (&optional all noalign)
7937 "Recalculate the current table line by applying all stored formulas.
7938 With prefix arg ALL, do this for all lines in the table."
7939 (interactive "P")
7940 (or (memq this-command org-recalc-commands)
7941 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7942 (unless (org-at-table-p) (error "Not at a table"))
7943 (if (equal all '(16))
7944 (org-table-iterate)
7945 (org-table-get-specials)
7946 (let* ((eqlist (sort (org-table-get-stored-formulas)
7947 (lambda (a b) (string< (car a) (car b)))))
7948 (inhibit-redisplay (not debug-on-error))
7949 (line-re org-table-dataline-regexp)
7950 (thisline (org-current-line))
7951 (thiscol (org-table-current-column))
7952 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7953 ;; Insert constants in all formulas
7954 (setq eqlist
7955 (mapcar (lambda (x)
7956 (setcdr x (org-table-formula-substitute-names (cdr x)))
7958 eqlist))
7959 ;; Split the equation list
7960 (while (setq eq (pop eqlist))
7961 (if (<= (string-to-char (car eq)) ?9)
7962 (push eq eqlnum)
7963 (push eq eqlname)))
7964 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7965 (if all
7966 (progn
7967 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7968 (goto-char (setq beg (org-table-begin)))
7969 (if (re-search-forward org-table-calculate-mark-regexp end t)
7970 ;; This is a table with marked lines, compute selected lines
7971 (setq line-re org-table-recalculate-regexp)
7972 ;; Move forward to the first non-header line
7973 (if (and (re-search-forward org-table-dataline-regexp end t)
7974 (re-search-forward org-table-hline-regexp end t)
7975 (re-search-forward org-table-dataline-regexp end t))
7976 (setq beg (match-beginning 0))
7977 nil))) ;; just leave beg where it is
7978 (setq beg (point-at-bol)
7979 end (move-marker (make-marker) (1+ (point-at-eol)))))
7980 (goto-char beg)
7981 (and all (message "Re-applying formulas to full table..."))
7982 (while (re-search-forward line-re end t)
7983 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7984 ;; Unprotected line, recalculate
7985 (and all (message "Re-applying formulas to full table...(line %d)"
7986 (setq cnt (1+ cnt))))
7987 (setq org-last-recalc-line (org-current-line))
7988 (setq eql eqlnum)
7989 (while (setq entry (pop eql))
7990 (goto-line org-last-recalc-line)
7991 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7992 (org-table-eval-formula nil (cdr entry)
7993 'noalign 'nocst 'nostore 'noanalysis))))
7994 (goto-line thisline)
7995 (org-table-goto-column thiscol)
7996 (or noalign (and org-table-may-need-update (org-table-align))
7997 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7998 ;; Now do the named fields
7999 (while (setq eq (pop eqlname))
8000 (setq name (car eq)
8001 a (assoc name org-table-named-field-locations))
8002 (and (not a)
8003 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
8004 (setq a
8005 (list
8006 name
8007 (aref org-table-dlines
8008 (string-to-number (match-string 1 name)))
8009 (string-to-number (match-string 2 name)))))
8010 (when (and a (or all (equal (nth 1 a) thisline)))
8011 (message "Re-applying formula to field: %s" name)
8012 (goto-line (nth 1 a))
8013 (org-table-goto-column (nth 2 a))
8014 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
8015 'nostore 'noanalysis)))
8016 ;; back to initial position
8017 (message "Re-applying formulas...done")
8018 (goto-line thisline)
8019 (org-table-goto-column thiscol)
8020 (or noalign (and org-table-may-need-update (org-table-align))
8021 (and all (message "Re-applying formulas...done"))))))
8023 (defun org-table-iterate (&optional arg)
8024 "Recalculate the table until it does not change anymore."
8025 (interactive "P")
8026 (let ((imax (if arg (prefix-numeric-value arg) 10))
8027 (i 0)
8028 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
8029 thistbl)
8030 (catch 'exit
8031 (while (< i imax)
8032 (setq i (1+ i))
8033 (org-table-recalculate 'all)
8034 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
8035 (if (not (string= lasttbl thistbl))
8036 (setq lasttbl thistbl)
8037 (if (> i 1)
8038 (message "Convergence after %d iterations" i)
8039 (message "Table was already stable"))
8040 (throw 'exit t)))
8041 (error "No convergence after %d iterations" i))))
8043 (defun org-table-formula-substitute-names (f)
8044 "Replace $const with values in string F."
8045 (let ((start 0) a (f1 f))
8046 ;; First, check for column names
8047 (while (setq start (string-match org-table-column-name-regexp f start))
8048 (setq start (1+ start))
8049 (setq a (assoc (match-string 1 f) org-table-column-names))
8050 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8051 ;; Parameters and constants
8052 (setq start 0)
8053 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8054 (setq start (1+ start))
8055 (if (setq a (save-match-data
8056 (org-table-get-constant (match-string 1 f))))
8057 (setq f (replace-match (concat "(" a ")") t t f))))
8058 (if org-table-formula-debug
8059 (put-text-property 0 (length f) :orig-formula f1 f))
8062 (defun org-table-get-constant (const)
8063 "Find the value for a parameter or constant in a formula.
8064 Parameters get priority."
8065 (or (cdr (assoc const org-table-local-parameters))
8066 (cdr (assoc const org-table-formula-constants))
8067 (and (fboundp 'constants-get) (constants-get const))
8068 "#UNDEFINED_NAME"))
8070 (defvar org-table-fedit-map (make-sparse-keymap))
8071 (define-key org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
8072 (define-key org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
8073 (define-key org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
8074 (define-key org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
8075 (define-key org-table-fedit-map "\C-c?" 'org-table-show-reference)
8076 (define-key org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
8077 (define-key org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
8078 (define-key org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
8079 (define-key org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
8080 (define-key org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
8081 (define-key org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
8082 (define-key org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
8083 (define-key org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
8084 (define-key org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
8085 (define-key org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
8086 (define-key org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
8087 (define-key org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
8088 (define-key org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
8089 (define-key org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
8091 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
8092 '("Edit-Formulas"
8093 ["Finish and Install" org-table-fedit-finish t]
8094 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
8095 ["Abort" org-table-fedit-abort t]
8096 "--"
8097 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
8098 ["Complete Lisp Symbol" lisp-complete-symbol t]
8099 "--"
8100 "Shift Reference at Point"
8101 ["Up" org-table-fedit-ref-up t]
8102 ["Down" org-table-fedit-ref-down t]
8103 ["Left" org-table-fedit-ref-left t]
8104 ["Right" org-table-fedit-ref-right t]
8106 "Change Test Row for Column Formulas"
8107 ["Up" org-table-fedit-line-up t]
8108 ["Down" org-table-fedit-line-down t]
8109 "--"
8110 ["Scroll Table Window" org-table-fedit-scroll t]
8111 ["Scroll Table Window down" org-table-fedit-scroll-down t]
8112 ["Show Table Grid" org-table-fedit-toggle-coordinates
8113 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
8114 org-table-overlay-coordinates)]
8115 "--"
8116 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
8117 :style toggle :selected org-table-buffer-is-an]))
8119 (defvar org-pos)
8121 (defun org-table-edit-formulas ()
8122 "Edit the formulas of the current table in a separate buffer."
8123 (interactive)
8124 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
8125 (beginning-of-line 0))
8126 (unless (org-at-table-p) (error "Not at a table"))
8127 (org-table-get-specials)
8128 (let ((key (org-table-current-field-formula 'key 'noerror))
8129 (eql (sort (org-table-get-stored-formulas 'noerror)
8130 'org-table-formula-less-p))
8131 (pos (move-marker (make-marker) (point)))
8132 (startline 1)
8133 (wc (current-window-configuration))
8134 (titles '((column . "# Column Formulas\n")
8135 (field . "# Field Formulas\n")
8136 (named . "# Named Field Formulas\n")))
8137 entry s type title)
8138 (switch-to-buffer-other-window "*Edit Formulas*")
8139 (erase-buffer)
8140 (fundamental-mode)
8141 (org-set-local 'org-pos pos)
8142 (org-set-local 'org-window-configuration wc)
8143 (use-local-map org-table-fedit-map)
8144 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
8145 (easy-menu-add org-table-fedit-menu)
8146 (setq startline (org-current-line))
8147 (while (setq entry (pop eql))
8148 (setq type (cond
8149 ((equal (string-to-char (car entry)) ?@) 'field)
8150 ((string-match "^[0-9]" (car entry)) 'column)
8151 (t 'named)))
8152 (when (setq title (assq type titles))
8153 (or (bobp) (insert "\n"))
8154 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
8155 (setq titles (delq title titles)))
8156 (if (equal key (car entry)) (setq startline (org-current-line)))
8157 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
8158 (car entry) " = " (cdr entry) "\n"))
8159 (remove-text-properties 0 (length s) '(face nil) s)
8160 (insert s))
8161 (if (eq org-table-use-standard-references t)
8162 (org-table-fedit-toggle-ref-type))
8163 (goto-line startline)
8164 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
8166 (defun org-table-fedit-post-command ()
8167 (when (not (memq this-command '(lisp-complete-symbol)))
8168 (let ((win (selected-window)))
8169 (save-excursion
8170 (condition-case nil
8171 (org-table-show-reference)
8172 (error nil))
8173 (select-window win)))))
8175 (defun org-table-formula-to-user (s)
8176 "Convert a formula from internal to user representation."
8177 (if (eq org-table-use-standard-references t)
8178 (org-table-convert-refs-to-an s)
8181 (defun org-table-formula-from-user (s)
8182 "Convert a formula from user to internal representation."
8183 (if org-table-use-standard-references
8184 (org-table-convert-refs-to-rc s)
8187 (defun org-table-convert-refs-to-rc (s)
8188 "Convert spreadsheet references from AB7 to @7$28.
8189 Works for single references, but also for entire formulas and even the
8190 full TBLFM line."
8191 (let ((start 0))
8192 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
8193 (if (match-end 3)
8194 ;; format match, just advance
8195 (setq start (match-end 0))
8196 (setq start (match-beginning 0)
8197 s (replace-match
8198 (if (equal (match-string 2 s) "&")
8199 (format "$%d" (org-letters-to-number (match-string 1 s)))
8200 (format "@%d$%d"
8201 (string-to-number (match-string 2 s))
8202 (org-letters-to-number (match-string 1 s))))
8203 t t s))))
8206 (defun org-table-convert-refs-to-an (s)
8207 "Convert spreadsheet references from to @7$28 to AB7.
8208 Works for single references, but also for entire formulas and even the
8209 full TBLFM line."
8210 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
8211 (setq s (replace-match
8212 (format "%s%d"
8213 (org-number-to-letters
8214 (string-to-number (match-string 2 s)))
8215 (string-to-number (match-string 1 s)))
8216 t t s)))
8217 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
8218 (setq s (replace-match (concat "\\1"
8219 (org-number-to-letters
8220 (string-to-number (match-string 2 s))) "&")
8221 t nil s)))
8224 (defun org-letters-to-number (s)
8225 "Convert a base 26 number represented by letters into an integer.
8226 For example: AB -> 28."
8227 (let ((n 0))
8228 (setq s (upcase s))
8229 (while (> (length s) 0)
8230 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
8231 s (substring s 1)))
8234 (defun org-number-to-letters (n)
8235 "Convert an integer into a base 26 number represented by letters.
8236 For example: 28 -> AB."
8237 (let ((s ""))
8238 (while (> n 0)
8239 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
8240 n (/ (1- n) 26)))
8243 (defun org-table-fedit-convert-buffer (function)
8244 "Convert all references in this buffer, using FUNTION."
8245 (let ((line (org-current-line)))
8246 (goto-char (point-min))
8247 (while (not (eobp))
8248 (insert (funcall function (buffer-substring (point) (point-at-eol))))
8249 (delete-region (point) (point-at-eol))
8250 (or (eobp) (forward-char 1)))
8251 (goto-line line)))
8253 (defun org-table-fedit-toggle-ref-type ()
8254 "Convert all references in the buffer from B3 to @3$2 and back."
8255 (interactive)
8256 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
8257 (org-table-fedit-convert-buffer
8258 (if org-table-buffer-is-an
8259 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
8260 (message "Reference type switched to %s"
8261 (if org-table-buffer-is-an "A1 etc" "@row$column")))
8263 (defun org-table-fedit-ref-up ()
8264 "Shift the reference at point one row/hline up."
8265 (interactive)
8266 (org-table-fedit-shift-reference 'up))
8267 (defun org-table-fedit-ref-down ()
8268 "Shift the reference at point one row/hline down."
8269 (interactive)
8270 (org-table-fedit-shift-reference 'down))
8271 (defun org-table-fedit-ref-left ()
8272 "Shift the reference at point one field to the left."
8273 (interactive)
8274 (org-table-fedit-shift-reference 'left))
8275 (defun org-table-fedit-ref-right ()
8276 "Shift the reference at point one field to the right."
8277 (interactive)
8278 (org-table-fedit-shift-reference 'right))
8280 (defun org-table-fedit-shift-reference (dir)
8281 (cond
8282 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
8283 (if (memq dir '(left right))
8284 (org-rematch-and-replace 1 (eq dir 'left))
8285 (error "Cannot shift reference in this direction")))
8286 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
8287 ;; A B3-like reference
8288 (if (memq dir '(up down))
8289 (org-rematch-and-replace 2 (eq dir 'up))
8290 (org-rematch-and-replace 1 (eq dir 'left))))
8291 ((org-at-regexp-p
8292 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
8293 ;; An internal reference
8294 (if (memq dir '(up down))
8295 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
8296 (org-rematch-and-replace 5 (eq dir 'left))))))
8298 (defun org-rematch-and-replace (n &optional decr hline)
8299 "Re-match the group N, and replace it with the shifted refrence."
8300 (or (match-end n) (error "Cannot shift reference in this direction"))
8301 (goto-char (match-beginning n))
8302 (and (looking-at (regexp-quote (match-string n)))
8303 (replace-match (org-shift-refpart (match-string 0) decr hline)
8304 t t)))
8306 (defun org-shift-refpart (ref &optional decr hline)
8307 "Shift a refrence part REF.
8308 If DECR is set, decrease the references row/column, else increase.
8309 If HLINE is set, this may be a hline reference, it certainly is not
8310 a translation reference."
8311 (save-match-data
8312 (let* ((sign (string-match "^[-+]" ref)) n)
8314 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
8315 (cond
8316 ((and hline (string-match "^I+" ref))
8317 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
8318 (setq n (+ n (if decr -1 1)))
8319 (if (= n 0) (setq n (+ n (if decr -1 1))))
8320 (if sign
8321 (setq sign (if (< n 0) "-" "+") n (abs n))
8322 (setq n (max 1 n)))
8323 (concat sign (make-string n ?I)))
8325 ((string-match "^[0-9]+" ref)
8326 (setq n (string-to-number (concat sign ref)))
8327 (setq n (+ n (if decr -1 1)))
8328 (if sign
8329 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
8330 (number-to-string (max 1 n))))
8332 ((string-match "^[a-zA-Z]+" ref)
8333 (org-number-to-letters
8334 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
8336 (t (error "Cannot shift reference"))))))
8338 (defun org-table-fedit-toggle-coordinates ()
8339 "Toggle the display of coordinates in the refrenced table."
8340 (interactive)
8341 (let ((pos (marker-position org-pos)))
8342 (with-current-buffer (marker-buffer org-pos)
8343 (save-excursion
8344 (goto-char pos)
8345 (org-table-toggle-coordinate-overlays)))))
8347 (defvar org-table-buffer-is-an nil)
8348 (defun org-table-fedit-finish (&optional arg)
8349 "Parse the buffer for formula definitions and install them.
8350 With prefix ARG, apply the new formulas to the table."
8351 (interactive "P")
8352 (org-table-remove-rectangle-highlight)
8353 (if org-table-use-standard-references
8354 (progn
8355 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
8356 (setq org-table-buffer-is-an nil)))
8357 (let ((pos org-pos) eql var form)
8358 (goto-char (point-min))
8359 (while (re-search-forward
8360 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
8361 nil t)
8362 (setq var (if (match-end 2) (match-string 2) (match-string 1))
8363 form (match-string 3))
8364 (setq form (org-trim form))
8365 (when (not (equal form ""))
8366 (while (string-match "[ \t]*\n[ \t]*" form)
8367 (setq form (replace-match " " t t form)))
8368 (when (assoc var eql)
8369 (error "Double formulas for %s" var))
8370 (push (cons var form) eql)))
8371 (setq org-pos nil)
8372 (set-window-configuration org-window-configuration)
8373 (select-window (get-buffer-window (marker-buffer pos)))
8374 (goto-char pos)
8375 (unless (org-at-table-p)
8376 (error "Lost table position - cannot install formulae"))
8377 (org-table-store-formulas eql)
8378 (move-marker pos nil)
8379 (kill-buffer "*Edit Formulas*")
8380 (if arg
8381 (org-table-recalculate 'all)
8382 (message "New formulas installed - press C-u C-c C-c to apply."))))
8384 (defun org-table-fedit-abort ()
8385 "Abort editing formulas, without installing the changes."
8386 (interactive)
8387 (org-table-remove-rectangle-highlight)
8388 (let ((pos org-pos))
8389 (set-window-configuration org-window-configuration)
8390 (select-window (get-buffer-window (marker-buffer pos)))
8391 (goto-char pos)
8392 (move-marker pos nil)
8393 (message "Formula editing aborted without installing changes")))
8395 (defun org-table-fedit-lisp-indent ()
8396 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8397 (interactive)
8398 (let ((pos (point)) beg end ind)
8399 (beginning-of-line 1)
8400 (cond
8401 ((looking-at "[ \t]")
8402 (goto-char pos)
8403 (call-interactively 'lisp-indent-line))
8404 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8405 ((not (fboundp 'pp-buffer))
8406 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8407 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8408 (goto-char (- (match-end 0) 2))
8409 (setq beg (point))
8410 (setq ind (make-string (current-column) ?\ ))
8411 (condition-case nil (forward-sexp 1)
8412 (error
8413 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8414 (setq end (point))
8415 (save-restriction
8416 (narrow-to-region beg end)
8417 (if (eq last-command this-command)
8418 (progn
8419 (goto-char (point-min))
8420 (setq this-command nil)
8421 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8422 (replace-match " ")))
8423 (pp-buffer)
8424 (untabify (point-min) (point-max))
8425 (goto-char (1+ (point-min)))
8426 (while (re-search-forward "^." nil t)
8427 (beginning-of-line 1)
8428 (insert ind))
8429 (goto-char (point-max))
8430 (backward-delete-char 1)))
8431 (goto-char beg))
8432 (t nil))))
8434 (defvar org-show-positions nil)
8436 (defun org-table-show-reference (&optional local)
8437 "Show the location/value of the $ expression at point."
8438 (interactive)
8439 (org-table-remove-rectangle-highlight)
8440 (catch 'exit
8441 (let ((pos (if local (point) org-pos))
8442 (face2 'highlight)
8443 (org-inhibit-highlight-removal t)
8444 (win (selected-window))
8445 (org-show-positions nil)
8446 var name e what match dest)
8447 (if local (org-table-get-specials))
8448 (setq what (cond
8449 ((or (org-at-regexp-p org-table-range-regexp2)
8450 (org-at-regexp-p org-table-translate-regexp)
8451 (org-at-regexp-p org-table-range-regexp))
8452 (setq match
8453 (save-match-data
8454 (org-table-convert-refs-to-rc (match-string 0))))
8455 'range)
8456 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8457 ((org-at-regexp-p "\\$[0-9]+") 'column)
8458 ((not local) nil)
8459 (t (error "No reference at point")))
8460 match (and what (or match (match-string 0))))
8461 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8462 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8463 'secondary-selection))
8464 (org-add-hook 'before-change-functions
8465 'org-table-remove-rectangle-highlight)
8466 (if (eq what 'name) (setq var (substring match 1)))
8467 (when (eq what 'range)
8468 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8469 (setq match (org-table-formula-substitute-names match)))
8470 (unless local
8471 (save-excursion
8472 (end-of-line 1)
8473 (re-search-backward "^\\S-" nil t)
8474 (beginning-of-line 1)
8475 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
8476 (setq dest
8477 (save-match-data
8478 (org-table-convert-refs-to-rc (match-string 1))))
8479 (org-table-add-rectangle-overlay
8480 (match-beginning 1) (match-end 1) face2))))
8481 (if (and (markerp pos) (marker-buffer pos))
8482 (if (get-buffer-window (marker-buffer pos))
8483 (select-window (get-buffer-window (marker-buffer pos)))
8484 (switch-to-buffer-other-window (get-buffer-window
8485 (marker-buffer pos)))))
8486 (goto-char pos)
8487 (org-table-force-dataline)
8488 (when dest
8489 (setq name (substring dest 1))
8490 (cond
8491 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8492 (setq e (assoc name org-table-named-field-locations))
8493 (goto-line (nth 1 e))
8494 (org-table-goto-column (nth 2 e)))
8495 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8496 (let ((l (string-to-number (match-string 1 dest)))
8497 (c (string-to-number (match-string 2 dest))))
8498 (goto-line (aref org-table-dlines l))
8499 (org-table-goto-column c)))
8500 (t (org-table-goto-column (string-to-number name))))
8501 (move-marker pos (point))
8502 (org-table-highlight-rectangle nil nil face2))
8503 (cond
8504 ((equal dest match))
8505 ((not match))
8506 ((eq what 'range)
8507 (condition-case nil
8508 (save-excursion
8509 (org-table-get-range match nil nil 'highlight))
8510 (error nil)))
8511 ((setq e (assoc var org-table-named-field-locations))
8512 (goto-line (nth 1 e))
8513 (org-table-goto-column (nth 2 e))
8514 (org-table-highlight-rectangle (point) (point))
8515 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8516 ((setq e (assoc var org-table-column-names))
8517 (org-table-goto-column (string-to-number (cdr e)))
8518 (org-table-highlight-rectangle (point) (point))
8519 (goto-char (org-table-begin))
8520 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8521 (org-table-end) t)
8522 (progn
8523 (goto-char (match-beginning 1))
8524 (org-table-highlight-rectangle)
8525 (message "Named column (column %s)" (cdr e)))
8526 (error "Column name not found")))
8527 ((eq what 'column)
8528 ;; column number
8529 (org-table-goto-column (string-to-number (substring match 1)))
8530 (org-table-highlight-rectangle (point) (point))
8531 (message "Column %s" (substring match 1)))
8532 ((setq e (assoc var org-table-local-parameters))
8533 (goto-char (org-table-begin))
8534 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8535 (progn
8536 (goto-char (match-beginning 1))
8537 (org-table-highlight-rectangle)
8538 (message "Local parameter."))
8539 (error "Parameter not found")))
8541 (cond
8542 ((not var) (error "No reference at point"))
8543 ((setq e (assoc var org-table-formula-constants))
8544 (message "Constant: $%s=%s in `org-table-formula-constants'."
8545 var (cdr e)))
8546 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8547 (message "Constant: $%s=%s, from `constants.el'%s."
8548 var e (format " (%s units)" constants-unit-system)))
8549 (t (error "Undefined name $%s" var)))))
8550 (goto-char pos)
8551 (when (and org-show-positions
8552 (not (memq this-command '(org-table-fedit-scroll
8553 org-table-fedit-scroll-down))))
8554 (push pos org-show-positions)
8555 (push org-table-current-begin-pos org-show-positions)
8556 (let ((min (apply 'min org-show-positions))
8557 (max (apply 'max org-show-positions)))
8558 (goto-char min) (recenter 0)
8559 (goto-char max)
8560 (or (pos-visible-in-window-p max) (recenter -1))))
8561 (select-window win))))
8563 (defun org-table-force-dataline ()
8564 "Make sure the cursor is in a dataline in a table."
8565 (unless (save-excursion
8566 (beginning-of-line 1)
8567 (looking-at org-table-dataline-regexp))
8568 (let* ((re org-table-dataline-regexp)
8569 (p1 (save-excursion (re-search-forward re nil 'move)))
8570 (p2 (save-excursion (re-search-backward re nil 'move))))
8571 (cond ((and p1 p2)
8572 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8573 p1 p2)))
8574 ((or p1 p2) (goto-char (or p1 p2)))
8575 (t (error "No table dataline around here"))))))
8577 (defun org-table-fedit-line-up ()
8578 "Move cursor one line up in the window showing the table."
8579 (interactive)
8580 (org-table-fedit-move 'previous-line))
8582 (defun org-table-fedit-line-down ()
8583 "Move cursor one line down in the window showing the table."
8584 (interactive)
8585 (org-table-fedit-move 'next-line))
8587 (defun org-table-fedit-move (command)
8588 "Move the cursor in the window shoinw the table.
8589 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8590 (let ((org-table-allow-automatic-line-recalculation nil)
8591 (pos org-pos) (win (selected-window)) p)
8592 (select-window (get-buffer-window (marker-buffer org-pos)))
8593 (setq p (point))
8594 (call-interactively command)
8595 (while (and (org-at-table-p)
8596 (org-at-table-hline-p))
8597 (call-interactively command))
8598 (or (org-at-table-p) (goto-char p))
8599 (move-marker pos (point))
8600 (select-window win)))
8602 (defun org-table-fedit-scroll (N)
8603 (interactive "p")
8604 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8605 (scroll-other-window N)))
8607 (defun org-table-fedit-scroll-down (N)
8608 (interactive "p")
8609 (org-table-fedit-scroll (- N)))
8611 (defvar org-table-rectangle-overlays nil)
8613 (defun org-table-add-rectangle-overlay (beg end &optional face)
8614 "Add a new overlay."
8615 (let ((ov (org-make-overlay beg end)))
8616 (org-overlay-put ov 'face (or face 'secondary-selection))
8617 (push ov org-table-rectangle-overlays)))
8619 (defun org-table-highlight-rectangle (&optional beg end face)
8620 "Highlight rectangular region in a table."
8621 (setq beg (or beg (point)) end (or end (point)))
8622 (let ((b (min beg end))
8623 (e (max beg end))
8624 l1 c1 l2 c2 tmp)
8625 (and (boundp 'org-show-positions)
8626 (setq org-show-positions (cons b (cons e org-show-positions))))
8627 (goto-char (min beg end))
8628 (setq l1 (org-current-line)
8629 c1 (org-table-current-column))
8630 (goto-char (max beg end))
8631 (setq l2 (org-current-line)
8632 c2 (org-table-current-column))
8633 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8634 (goto-line l1)
8635 (beginning-of-line 1)
8636 (loop for line from l1 to l2 do
8637 (when (looking-at org-table-dataline-regexp)
8638 (org-table-goto-column c1)
8639 (skip-chars-backward "^|\n") (setq beg (point))
8640 (org-table-goto-column c2)
8641 (skip-chars-forward "^|\n") (setq end (point))
8642 (org-table-add-rectangle-overlay beg end face))
8643 (beginning-of-line 2))
8644 (goto-char b))
8645 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8647 (defun org-table-remove-rectangle-highlight (&rest ignore)
8648 "Remove the rectangle overlays."
8649 (unless org-inhibit-highlight-removal
8650 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8651 (mapc 'org-delete-overlay org-table-rectangle-overlays)
8652 (setq org-table-rectangle-overlays nil)))
8654 (defvar org-table-coordinate-overlays nil
8655 "Collects the cooordinate grid overlays, so that they can be removed.")
8656 (make-variable-buffer-local 'org-table-coordinate-overlays)
8658 (defun org-table-overlay-coordinates ()
8659 "Add overlays to the table at point, to show row/column coordinates."
8660 (interactive)
8661 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8662 (setq org-table-coordinate-overlays nil)
8663 (save-excursion
8664 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
8665 (goto-char (org-table-begin))
8666 (while (org-at-table-p)
8667 (setq eol (point-at-eol))
8668 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8669 (push ov org-table-coordinate-overlays)
8670 (setq hline (looking-at org-table-hline-regexp))
8671 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8672 (format "%4d" (setq id (1+ id)))))
8673 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
8674 (when hline
8675 (setq ic 0)
8676 (while (re-search-forward "[+|]\\(-+\\)" eol t)
8677 (setq beg (1+ (match-beginning 0))
8678 ic (1+ ic)
8679 s1 (concat "$" (int-to-string ic))
8680 s2 (org-number-to-letters ic)
8681 str (if org-table-use-standard-references s2 s1))
8682 (setq ov (org-make-overlay beg (+ beg (length str))))
8683 (push ov org-table-coordinate-overlays)
8684 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
8685 (beginning-of-line 2)))))
8687 (defun org-table-toggle-coordinate-overlays ()
8688 "Toggle the display of Row/Column numbers in tables."
8689 (interactive)
8690 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8691 (message "Row/Column number display turned %s"
8692 (if org-table-overlay-coordinates "on" "off"))
8693 (if (and (org-at-table-p) org-table-overlay-coordinates)
8694 (org-table-align))
8695 (unless org-table-overlay-coordinates
8696 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8697 (setq org-table-coordinate-overlays nil)))
8699 (defun org-table-toggle-formula-debugger ()
8700 "Toggle the formula debugger in tables."
8701 (interactive)
8702 (setq org-table-formula-debug (not org-table-formula-debug))
8703 (message "Formula debugging has been turned %s"
8704 (if org-table-formula-debug "on" "off")))
8706 ;;; The orgtbl minor mode
8708 ;; Define a minor mode which can be used in other modes in order to
8709 ;; integrate the org-mode table editor.
8711 ;; This is really a hack, because the org-mode table editor uses several
8712 ;; keys which normally belong to the major mode, for example the TAB and
8713 ;; RET keys. Here is how it works: The minor mode defines all the keys
8714 ;; necessary to operate the table editor, but wraps the commands into a
8715 ;; function which tests if the cursor is currently inside a table. If that
8716 ;; is the case, the table editor command is executed. However, when any of
8717 ;; those keys is used outside a table, the function uses `key-binding' to
8718 ;; look up if the key has an associated command in another currently active
8719 ;; keymap (minor modes, major mode, global), and executes that command.
8720 ;; There might be problems if any of the keys used by the table editor is
8721 ;; otherwise used as a prefix key.
8723 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8724 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8725 ;; addresses this by checking explicitly for both bindings.
8727 ;; The optimized version (see variable `orgtbl-optimized') takes over
8728 ;; all keys which are bound to `self-insert-command' in the *global map*.
8729 ;; Some modes bind other commands to simple characters, for example
8730 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8731 ;; active, this binding is ignored inside tables and replaced with a
8732 ;; modified self-insert.
8734 (defvar orgtbl-mode nil
8735 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8736 table editor in arbitrary modes.")
8737 (make-variable-buffer-local 'orgtbl-mode)
8739 (defvar orgtbl-mode-map (make-keymap)
8740 "Keymap for `orgtbl-mode'.")
8742 ;;;###autoload
8743 (defun turn-on-orgtbl ()
8744 "Unconditionally turn on `orgtbl-mode'."
8745 (orgtbl-mode 1))
8747 (defvar org-old-auto-fill-inhibit-regexp nil
8748 "Local variable used by `orgtbl-mode'")
8750 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8751 "Matches a line belonging to an orgtbl.")
8753 (defconst orgtbl-extra-font-lock-keywords
8754 (list (list (concat "^" orgtbl-line-start-regexp ".*")
8755 0 (quote 'org-table) 'prepend))
8756 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8758 ;;;###autoload
8759 (defun orgtbl-mode (&optional arg)
8760 "The `org-mode' table editor as a minor mode for use in other modes."
8761 (interactive)
8762 (if (org-mode-p)
8763 ;; Exit without error, in case some hook functions calls this
8764 ;; by accident in org-mode.
8765 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8766 (setq orgtbl-mode
8767 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8768 (if orgtbl-mode
8769 (progn
8770 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8771 ;; Make sure we are first in minor-mode-map-alist
8772 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8773 (and c (setq minor-mode-map-alist
8774 (cons c (delq c minor-mode-map-alist)))))
8775 (org-set-local (quote org-table-may-need-update) t)
8776 (org-add-hook 'before-change-functions 'org-before-change-function
8777 nil 'local)
8778 (org-set-local 'org-old-auto-fill-inhibit-regexp
8779 auto-fill-inhibit-regexp)
8780 (org-set-local 'auto-fill-inhibit-regexp
8781 (if auto-fill-inhibit-regexp
8782 (concat orgtbl-line-start-regexp "\\|"
8783 auto-fill-inhibit-regexp)
8784 orgtbl-line-start-regexp))
8785 (org-add-to-invisibility-spec '(org-cwidth))
8786 (when (fboundp 'font-lock-add-keywords)
8787 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8788 (org-restart-font-lock))
8789 (easy-menu-add orgtbl-mode-menu)
8790 (run-hooks 'orgtbl-mode-hook))
8791 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8792 (org-cleanup-narrow-column-properties)
8793 (org-remove-from-invisibility-spec '(org-cwidth))
8794 (remove-hook 'before-change-functions 'org-before-change-function t)
8795 (when (fboundp 'font-lock-remove-keywords)
8796 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8797 (org-restart-font-lock))
8798 (easy-menu-remove orgtbl-mode-menu)
8799 (force-mode-line-update 'all))))
8801 (defun org-cleanup-narrow-column-properties ()
8802 "Remove all properties related to narrow-column invisibility."
8803 (let ((s 1))
8804 (while (setq s (text-property-any s (point-max)
8805 'display org-narrow-column-arrow))
8806 (remove-text-properties s (1+ s) '(display t)))
8807 (setq s 1)
8808 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8809 (remove-text-properties s (1+ s) '(org-cwidth t)))
8810 (setq s 1)
8811 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8812 (remove-text-properties s (1+ s) '(invisible t)))))
8814 ;; Install it as a minor mode.
8815 (put 'orgtbl-mode :included t)
8816 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8817 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8819 (defun orgtbl-make-binding (fun n &rest keys)
8820 "Create a function for binding in the table minor mode.
8821 FUN is the command to call inside a table. N is used to create a unique
8822 command name. KEYS are keys that should be checked in for a command
8823 to execute outside of tables."
8824 (eval
8825 (list 'defun
8826 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8827 '(arg)
8828 (concat "In tables, run `" (symbol-name fun) "'.\n"
8829 "Outside of tables, run the binding of `"
8830 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8831 "'.")
8832 '(interactive "p")
8833 (list 'if
8834 '(org-at-table-p)
8835 (list 'call-interactively (list 'quote fun))
8836 (list 'let '(orgtbl-mode)
8837 (list 'call-interactively
8838 (append '(or)
8839 (mapcar (lambda (k)
8840 (list 'key-binding k))
8841 keys)
8842 '('orgtbl-error))))))))
8844 (defun orgtbl-error ()
8845 "Error when there is no default binding for a table key."
8846 (interactive)
8847 (error "This key is has no function outside tables"))
8849 (defun orgtbl-setup ()
8850 "Setup orgtbl keymaps."
8851 (let ((nfunc 0)
8852 (bindings
8853 (list
8854 '([(meta shift left)] org-table-delete-column)
8855 '([(meta left)] org-table-move-column-left)
8856 '([(meta right)] org-table-move-column-right)
8857 '([(meta shift right)] org-table-insert-column)
8858 '([(meta shift up)] org-table-kill-row)
8859 '([(meta shift down)] org-table-insert-row)
8860 '([(meta up)] org-table-move-row-up)
8861 '([(meta down)] org-table-move-row-down)
8862 '("\C-c\C-w" org-table-cut-region)
8863 '("\C-c\M-w" org-table-copy-region)
8864 '("\C-c\C-y" org-table-paste-rectangle)
8865 '("\C-c-" org-table-insert-hline)
8866 '("\C-c}" org-table-toggle-coordinate-overlays)
8867 '("\C-c{" org-table-toggle-formula-debugger)
8868 '("\C-m" org-table-next-row)
8869 (list (org-key 'S-return) 'org-table-copy-down)
8870 '("\C-c\C-q" org-table-wrap-region)
8871 '("\C-c?" org-table-field-info)
8872 '("\C-c " org-table-blank-field)
8873 '("\C-c+" org-table-sum)
8874 '("\C-c=" org-table-eval-formula)
8875 '("\C-c'" org-table-edit-formulas)
8876 '("\C-c`" org-table-edit-field)
8877 '("\C-c*" org-table-recalculate)
8878 '("\C-c|" org-table-create-or-convert-from-region)
8879 '("\C-c^" org-table-sort-lines)
8880 '([(control ?#)] org-table-rotate-recalc-marks)))
8881 elt key fun cmd)
8882 (while (setq elt (pop bindings))
8883 (setq nfunc (1+ nfunc))
8884 (setq key (car elt)
8885 fun (nth 1 elt)
8886 cmd (orgtbl-make-binding fun nfunc key))
8887 (define-key orgtbl-mode-map key cmd))
8889 ;; Special treatment needed for TAB and RET
8890 (define-key orgtbl-mode-map [(return)]
8891 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8892 (define-key orgtbl-mode-map "\C-m"
8893 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8895 (define-key orgtbl-mode-map [(tab)]
8896 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8897 (define-key orgtbl-mode-map "\C-i"
8898 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
8900 (define-key orgtbl-mode-map [(shift tab)]
8901 (orgtbl-make-binding 'org-table-previous-field 104
8902 [(shift tab)] [(tab)] "\C-i"))
8904 (define-key orgtbl-mode-map "\M-\C-m"
8905 (orgtbl-make-binding 'org-table-wrap-region 105
8906 "\M-\C-m" [(meta return)]))
8907 (define-key orgtbl-mode-map [(meta return)]
8908 (orgtbl-make-binding 'org-table-wrap-region 106
8909 [(meta return)] "\M-\C-m"))
8911 (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
8912 (when orgtbl-optimized
8913 ;; If the user wants maximum table support, we need to hijack
8914 ;; some standard editing functions
8915 (org-remap orgtbl-mode-map
8916 'self-insert-command 'orgtbl-self-insert-command
8917 'delete-char 'org-delete-char
8918 'delete-backward-char 'org-delete-backward-char)
8919 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8920 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8921 '("OrgTbl"
8922 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8923 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8924 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8925 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8926 "--"
8927 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8928 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8929 ["Copy Field from Above"
8930 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8931 "--"
8932 ("Column"
8933 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8934 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8935 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8936 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8937 ("Row"
8938 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8939 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8940 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8941 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8942 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8943 "--"
8944 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8945 ("Rectangle"
8946 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8947 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8948 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8949 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8950 "--"
8951 ("Radio tables"
8952 ["Insert table template" orgtbl-insert-radio-table
8953 (assq major-mode orgtbl-radio-table-templates)]
8954 ["Comment/uncomment table" orgtbl-toggle-comment t])
8955 "--"
8956 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8957 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8958 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8959 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8960 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8961 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
8962 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8963 ["Sum Column/Rectangle" org-table-sum
8964 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8965 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8966 ["Debug Formulas"
8967 org-table-toggle-formula-debugger :active (org-at-table-p)
8968 :keys "C-c {"
8969 :style toggle :selected org-table-formula-debug]
8970 ["Show Col/Row Numbers"
8971 org-table-toggle-coordinate-overlays :active (org-at-table-p)
8972 :keys "C-c }"
8973 :style toggle :selected org-table-overlay-coordinates]
8977 (defun orgtbl-ctrl-c-ctrl-c (arg)
8978 "If the cursor is inside a table, realign the table.
8979 It it is a table to be sent away to a receiver, do it.
8980 With prefix arg, also recompute table."
8981 (interactive "P")
8982 (let ((pos (point)) action)
8983 (save-excursion
8984 (beginning-of-line 1)
8985 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
8986 ((looking-at "[ \t]*|") pos)
8987 ((looking-at "#\\+TBLFM:") 'recalc))))
8988 (cond
8989 ((integerp action)
8990 (goto-char action)
8991 (org-table-maybe-eval-formula)
8992 (if arg
8993 (call-interactively 'org-table-recalculate)
8994 (org-table-maybe-recalculate-line))
8995 (call-interactively 'org-table-align)
8996 (orgtbl-send-table 'maybe))
8997 ((eq action 'recalc)
8998 (save-excursion
8999 (beginning-of-line 1)
9000 (skip-chars-backward " \r\n\t")
9001 (if (org-at-table-p)
9002 (org-call-with-arg 'org-table-recalculate t))))
9003 (t (let (orgtbl-mode)
9004 (call-interactively (key-binding "\C-c\C-c")))))))
9006 (defun orgtbl-tab (arg)
9007 "Justification and field motion for `orgtbl-mode'."
9008 (interactive "P")
9009 (if arg (org-table-edit-field t)
9010 (org-table-justify-field-maybe)
9011 (org-table-next-field)))
9013 (defun orgtbl-ret ()
9014 "Justification and field motion for `orgtbl-mode'."
9015 (interactive)
9016 (org-table-justify-field-maybe)
9017 (org-table-next-row))
9019 (defun orgtbl-self-insert-command (N)
9020 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9021 If the cursor is in a table looking at whitespace, the whitespace is
9022 overwritten, and the table is not marked as requiring realignment."
9023 (interactive "p")
9024 (if (and (org-at-table-p)
9026 (and org-table-auto-blank-field
9027 (member last-command
9028 '(orgtbl-hijacker-command-100
9029 orgtbl-hijacker-command-101
9030 orgtbl-hijacker-command-102
9031 orgtbl-hijacker-command-103
9032 orgtbl-hijacker-command-104
9033 orgtbl-hijacker-command-105))
9034 (org-table-blank-field))
9036 (eq N 1)
9037 (looking-at "[^|\n]* +|"))
9038 (let (org-table-may-need-update)
9039 (goto-char (1- (match-end 0)))
9040 (delete-backward-char 1)
9041 (goto-char (match-beginning 0))
9042 (self-insert-command N))
9043 (setq org-table-may-need-update t)
9044 (let (orgtbl-mode)
9045 (call-interactively (key-binding (vector last-input-event))))))
9047 (defun org-force-self-insert (N)
9048 "Needed to enforce self-insert under remapping."
9049 (interactive "p")
9050 (self-insert-command N))
9052 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
9053 "Regula expression matching exponentials as produced by calc.")
9055 (defvar org-table-clean-did-remove-column-1 nil)
9057 (defun orgtbl-send-table (&optional maybe)
9058 "Send a tranformed version of this table to the receiver position.
9059 With argument MAYBE, fail quietly if no transformation is defined for
9060 this table."
9061 (interactive)
9062 (catch 'exit
9063 (unless (org-at-table-p) (error "Not at a table"))
9064 ;; when non-interactive, we assume align has just happened.
9065 (when (interactive-p) (org-table-align))
9066 (save-excursion
9067 (goto-char (org-table-begin))
9068 (beginning-of-line 0)
9069 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
9070 (if maybe
9071 (throw 'exit nil)
9072 (error "Don't know how to transform this table."))))
9073 (let* ((name (match-string 1))
9075 (transform (intern (match-string 2)))
9076 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
9077 (skip (plist-get params :skip))
9078 (skipcols (plist-get params :skipcols))
9079 (txt (buffer-substring-no-properties
9080 (org-table-begin) (org-table-end)))
9081 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
9082 (lines (org-table-clean-before-export lines))
9083 (i0 (if org-table-clean-did-remove-column-1 2 1))
9084 (table (mapcar
9085 (lambda (x)
9086 (if (string-match org-table-hline-regexp x)
9087 'hline
9088 (org-remove-by-index
9089 (org-split-string (org-trim x) "\\s-*|\\s-*")
9090 skipcols i0)))
9091 lines))
9092 (fun (if (= i0 2) 'cdr 'identity))
9093 (org-table-last-alignment
9094 (org-remove-by-index (funcall fun org-table-last-alignment)
9095 skipcols i0))
9096 (org-table-last-column-widths
9097 (org-remove-by-index (funcall fun org-table-last-column-widths)
9098 skipcols i0)))
9100 (unless (fboundp transform)
9101 (error "No such transformation function %s" transform))
9102 (setq txt (funcall transform table params))
9103 ;; Find the insertion place
9104 (save-excursion
9105 (goto-char (point-min))
9106 (unless (re-search-forward
9107 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
9108 (error "Don't know where to insert translated table"))
9109 (goto-char (match-beginning 0))
9110 (beginning-of-line 2)
9111 (setq beg (point))
9112 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
9113 (error "Cannot find end of insertion region"))
9114 (beginning-of-line 1)
9115 (delete-region beg (point))
9116 (goto-char beg)
9117 (insert txt "\n"))
9118 (message "Table converted and installed at receiver location"))))
9120 (defun org-remove-by-index (list indices &optional i0)
9121 "Remove the elements in LIST with indices in INDICES.
9122 First element has index 0, or I0 if given."
9123 (if (not indices)
9124 list
9125 (if (integerp indices) (setq indices (list indices)))
9126 (setq i0 (1- (or i0 0)))
9127 (delq :rm (mapcar (lambda (x)
9128 (setq i0 (1+ i0))
9129 (if (memq i0 indices) :rm x))
9130 list))))
9132 (defun orgtbl-toggle-comment ()
9133 "Comment or uncomment the orgtbl at point."
9134 (interactive)
9135 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
9136 (re2 (concat "^" orgtbl-line-start-regexp))
9137 (commented (save-excursion (beginning-of-line 1)
9138 (cond ((looking-at re1) t)
9139 ((looking-at re2) nil)
9140 (t (error "Not at an org table")))))
9141 (re (if commented re1 re2))
9142 beg end)
9143 (save-excursion
9144 (beginning-of-line 1)
9145 (while (looking-at re) (beginning-of-line 0))
9146 (beginning-of-line 2)
9147 (setq beg (point))
9148 (while (looking-at re) (beginning-of-line 2))
9149 (setq end (point)))
9150 (comment-region beg end (if commented '(4) nil))))
9152 (defun orgtbl-insert-radio-table ()
9153 "Insert a radio table template appropriate for this major mode."
9154 (interactive)
9155 (let* ((e (assq major-mode orgtbl-radio-table-templates))
9156 (txt (nth 1 e))
9157 name pos)
9158 (unless e (error "No radio table setup defined for %s" major-mode))
9159 (setq name (read-string "Table name: "))
9160 (while (string-match "%n" txt)
9161 (setq txt (replace-match name t t txt)))
9162 (or (bolp) (insert "\n"))
9163 (setq pos (point))
9164 (insert txt)
9165 (goto-char pos)))
9167 (defun org-get-param (params header i sym &optional hsym)
9168 "Get parameter value for symbol SYM.
9169 If this is a header line, actually get the value for the symbol with an
9170 additional \"h\" inserted after the colon.
9171 If the value is a protperty list, get the element for the current column.
9172 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
9173 (let ((val (plist-get params sym)))
9174 (and hsym header (setq val (or (plist-get params hsym) val)))
9175 (if (consp val) (plist-get val i) val)))
9177 (defun orgtbl-to-generic (table params)
9178 "Convert the orgtbl-mode TABLE to some other format.
9179 This generic routine can be used for many standard cases.
9180 TABLE is a list, each entry either the symbol `hline' for a horizontal
9181 separator line, or a list of fields for that line.
9182 PARAMS is a property list of parameters that can influence the conversion.
9183 For the generic converter, some parameters are obligatory: You need to
9184 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
9185 :splice, you must have :tstart and :tend.
9187 Valid parameters are
9189 :tstart String to start the table. Ignored when :splice is t.
9190 :tend String to end the table. Ignored when :splice is t.
9192 :splice When set to t, return only table body lines, don't wrap
9193 them into :tstart and :tend. Default is nil.
9195 :hline String to be inserted on horizontal separation lines.
9196 May be nil to ignore hlines.
9198 :lstart String to start a new table line.
9199 :lend String to end a table line
9200 :sep Separator between two fields
9201 :lfmt Format for entire line, with enough %s to capture all fields.
9202 If this is present, :lstart, :lend, and :sep are ignored.
9203 :fmt A format to be used to wrap the field, should contain
9204 %s for the original field value. For example, to wrap
9205 everything in dollars, you could use :fmt \"$%s$\".
9206 This may also be a property list with column numbers and
9207 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9209 :hlstart :hlend :hlsep :hlfmt :hfmt
9210 Same as above, specific for the header lines in the table.
9211 All lines before the first hline are treated as header.
9212 If any of these is not present, the data line value is used.
9214 :efmt Use this format to print numbers with exponentials.
9215 The format should have %s twice for inserting mantissa
9216 and exponent, for example \"%s\\\\times10^{%s}\". This
9217 may also be a property list with column numbers and
9218 formats. :fmt will still be applied after :efmt.
9220 In addition to this, the parameters :skip and :skipcols are always handled
9221 directly by `orgtbl-send-table'. See manual."
9222 (interactive)
9223 (let* ((p params)
9224 (splicep (plist-get p :splice))
9225 (hline (plist-get p :hline))
9226 rtn line i fm efm lfmt h)
9228 ;; Do we have a header?
9229 (if (and (not splicep) (listp (car table)) (memq 'hline table))
9230 (setq h t))
9232 ;; Put header
9233 (unless splicep
9234 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
9236 ;; Now loop over all lines
9237 (while (setq line (pop table))
9238 (if (eq line 'hline)
9239 ;; A horizontal separator line
9240 (progn (if hline (push hline rtn))
9241 (setq h nil)) ; no longer in header
9242 ;; A normal line. Convert the fields, push line onto the result list
9243 (setq i 0)
9244 (setq line
9245 (mapcar
9246 (lambda (f)
9247 (setq i (1+ i)
9248 fm (org-get-param p h i :fmt :hfmt)
9249 efm (org-get-param p h i :efmt))
9250 (if (and efm (string-match orgtbl-exp-regexp f))
9251 (setq f (format
9252 efm (match-string 1 f) (match-string 2 f))))
9253 (if fm (setq f (format fm f)))
9255 line))
9256 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
9257 (push (apply 'format lfmt line) rtn)
9258 (push (concat
9259 (org-get-param p h i :lstart :hlstart)
9260 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
9261 (org-get-param p h i :lend :hlend))
9262 rtn))))
9264 (unless splicep
9265 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
9267 (mapconcat 'identity (nreverse rtn) "\n")))
9269 (defun orgtbl-to-latex (table params)
9270 "Convert the orgtbl-mode TABLE to LaTeX.
9271 TABLE is a list, each entry either the symbol `hline' for a horizontal
9272 separator line, or a list of fields for that line.
9273 PARAMS is a property list of parameters that can influence the conversion.
9274 Supports all parameters from `orgtbl-to-generic'. Most important for
9275 LaTeX are:
9277 :splice When set to t, return only table body lines, don't wrap
9278 them into a tabular environment. Default is nil.
9280 :fmt A format to be used to wrap the field, should contain %s for the
9281 original field value. For example, to wrap everything in dollars,
9282 use :fmt \"$%s$\". This may also be a property list with column
9283 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9285 :efmt Format for transforming numbers with exponentials. The format
9286 should have %s twice for inserting mantissa and exponent, for
9287 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
9288 This may also be a property list with column numbers and formats.
9290 The general parameters :skip and :skipcols have already been applied when
9291 this function is called."
9292 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
9293 org-table-last-alignment ""))
9294 (params2
9295 (list
9296 :tstart (concat "\\begin{tabular}{" alignment "}")
9297 :tend "\\end{tabular}"
9298 :lstart "" :lend " \\\\" :sep " & "
9299 :efmt "%s\\,(%s)" :hline "\\hline")))
9300 (orgtbl-to-generic table (org-combine-plists params2 params))))
9302 (defun orgtbl-to-html (table params)
9303 "Convert the orgtbl-mode TABLE to LaTeX.
9304 TABLE is a list, each entry either the symbol `hline' for a horizontal
9305 separator line, or a list of fields for that line.
9306 PARAMS is a property list of parameters that can influence the conversion.
9307 Currently this function recognizes the following parameters:
9309 :splice When set to t, return only table body lines, don't wrap
9310 them into a <table> environment. Default is nil.
9312 The general parameters :skip and :skipcols have already been applied when
9313 this function is called. The function does *not* use `orgtbl-to-generic',
9314 so you cannot specify parameters for it."
9315 (let* ((splicep (plist-get params :splice))
9316 html)
9317 ;; Just call the formatter we already have
9318 ;; We need to make text lines for it, so put the fields back together.
9319 (setq html (org-format-org-table-html
9320 (mapcar
9321 (lambda (x)
9322 (if (eq x 'hline)
9323 "|----+----|"
9324 (concat "| " (mapconcat 'identity x " | ") " |")))
9325 table)
9326 splicep))
9327 (if (string-match "\n+\\'" html)
9328 (setq html (replace-match "" t t html)))
9329 html))
9331 (defun orgtbl-to-texinfo (table params)
9332 "Convert the orgtbl-mode TABLE to TeXInfo.
9333 TABLE is a list, each entry either the symbol `hline' for a horizontal
9334 separator line, or a list of fields for that line.
9335 PARAMS is a property list of parameters that can influence the conversion.
9336 Supports all parameters from `orgtbl-to-generic'. Most important for
9337 TeXInfo are:
9339 :splice nil/t When set to t, return only table body lines, don't wrap
9340 them into a multitable environment. Default is nil.
9342 :fmt fmt A format to be used to wrap the field, should contain
9343 %s for the original field value. For example, to wrap
9344 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
9345 This may also be a property list with column numbers and
9346 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
9348 :cf \"f1 f2..\" The column fractions for the table. Bye default these
9349 are computed automatically from the width of the columns
9350 under org-mode.
9352 The general parameters :skip and :skipcols have already been applied when
9353 this function is called."
9354 (let* ((total (float (apply '+ org-table-last-column-widths)))
9355 (colfrac (or (plist-get params :cf)
9356 (mapconcat
9357 (lambda (x) (format "%.3f" (/ (float x) total)))
9358 org-table-last-column-widths " ")))
9359 (params2
9360 (list
9361 :tstart (concat "@multitable @columnfractions " colfrac)
9362 :tend "@end multitable"
9363 :lstart "@item " :lend "" :sep " @tab "
9364 :hlstart "@headitem ")))
9365 (orgtbl-to-generic table (org-combine-plists params2 params))))
9367 ;;;; Link Stuff
9369 ;;; Link abbreviations
9371 (defun org-link-expand-abbrev (link)
9372 "Apply replacements as defined in `org-link-abbrev-alist."
9373 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9374 (let* ((key (match-string 1 link))
9375 (as (or (assoc key org-link-abbrev-alist-local)
9376 (assoc key org-link-abbrev-alist)))
9377 (tag (and (match-end 2) (match-string 3 link)))
9378 rpl)
9379 (if (not as)
9380 link
9381 (setq rpl (cdr as))
9382 (cond
9383 ((symbolp rpl) (funcall rpl tag))
9384 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9385 (t (concat rpl tag)))))
9386 link))
9388 ;;; Storing and inserting links
9390 (defvar org-insert-link-history nil
9391 "Minibuffer history for links inserted with `org-insert-link'.")
9393 (defvar org-stored-links nil
9394 "Contains the links stored with `org-store-link'.")
9396 (defvar org-store-link-plist nil
9397 "Plist with info about the most recently link created with `org-store-link'.")
9399 ;;;###autoload
9400 (defun org-store-link (arg)
9401 "\\<org-mode-map>Store an org-link to the current location.
9402 This link can later be inserted into an org-buffer with
9403 \\[org-insert-link].
9404 For some link types, a prefix arg is interpreted:
9405 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9406 For file links, arg negates `org-context-in-file-links'."
9407 (interactive "P")
9408 (setq org-store-link-plist nil) ; reset
9409 (let (link cpltxt desc description search txt)
9410 (cond
9412 ((eq major-mode 'bbdb-mode)
9413 (let ((name (bbdb-record-name (bbdb-current-record)))
9414 (company (bbdb-record-company (bbdb-current-record))))
9415 (setq cpltxt (concat "bbdb:" (or name company))
9416 link (org-make-link cpltxt))
9417 (org-store-link-props :type "bbdb" :name name :company company)))
9419 ((eq major-mode 'Info-mode)
9420 (setq link (org-make-link "info:"
9421 (file-name-nondirectory Info-current-file)
9422 ":" Info-current-node))
9423 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9424 ":" Info-current-node))
9425 (org-store-link-props :type "info" :file Info-current-file
9426 :node Info-current-node))
9428 ((eq major-mode 'calendar-mode)
9429 (let ((cd (calendar-cursor-to-date)))
9430 (setq link
9431 (format-time-string
9432 (car org-time-stamp-formats)
9433 (apply 'encode-time
9434 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9435 nil nil nil))))
9436 (org-store-link-props :type "calendar" :date cd)))
9438 ((or (eq major-mode 'vm-summary-mode)
9439 (eq major-mode 'vm-presentation-mode))
9440 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9441 (vm-follow-summary-cursor)
9442 (save-excursion
9443 (vm-select-folder-buffer)
9444 (let* ((message (car vm-message-pointer))
9445 (folder buffer-file-name)
9446 (subject (vm-su-subject message))
9447 (to (vm-get-header-contents message "To"))
9448 (from (vm-get-header-contents message "From"))
9449 (message-id (vm-su-message-id message)))
9450 (org-store-link-props :type "vm" :from from :to to :subject subject
9451 :message-id message-id)
9452 (setq message-id (org-remove-angle-brackets message-id))
9453 (setq folder (abbreviate-file-name folder))
9454 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9455 folder)
9456 (setq folder (replace-match "" t t folder)))
9457 (setq cpltxt (org-email-link-description))
9458 (setq link (org-make-link "vm:" folder "#" message-id)))))
9460 ((eq major-mode 'wl-summary-mode)
9461 (let* ((msgnum (wl-summary-message-number))
9462 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9463 msgnum 'message-id))
9464 (wl-message-entity
9465 (if (fboundp 'elmo-message-entity)
9466 (elmo-message-entity
9467 wl-summary-buffer-elmo-folder msgnum)
9468 (elmo-msgdb-overview-get-entity
9469 msgnum (wl-summary-buffer-msgdb))))
9470 (from (wl-summary-line-from))
9471 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9472 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9473 (wl-summary-line-subject))))
9474 (org-store-link-props :type "wl" :from from :to to
9475 :subject subject :message-id message-id)
9476 (setq message-id (org-remove-angle-brackets message-id))
9477 (setq cpltxt (org-email-link-description))
9478 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9479 "#" message-id))))
9481 ((or (equal major-mode 'mh-folder-mode)
9482 (equal major-mode 'mh-show-mode))
9483 (let ((from (org-mhe-get-header "From:"))
9484 (to (org-mhe-get-header "To:"))
9485 (message-id (org-mhe-get-header "Message-Id:"))
9486 (subject (org-mhe-get-header "Subject:")))
9487 (org-store-link-props :type "mh" :from from :to to
9488 :subject subject :message-id message-id)
9489 (setq cpltxt (org-email-link-description))
9490 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9491 (org-remove-angle-brackets message-id)))))
9493 ((eq major-mode 'rmail-mode)
9494 (save-excursion
9495 (save-restriction
9496 (rmail-narrow-to-non-pruned-header)
9497 (let ((folder buffer-file-name)
9498 (message-id (mail-fetch-field "message-id"))
9499 (from (mail-fetch-field "from"))
9500 (to (mail-fetch-field "to"))
9501 (subject (mail-fetch-field "subject")))
9502 (org-store-link-props
9503 :type "rmail" :from from :to to
9504 :subject subject :message-id message-id)
9505 (setq message-id (org-remove-angle-brackets message-id))
9506 (setq cpltxt (org-email-link-description))
9507 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9509 ((eq major-mode 'gnus-group-mode)
9510 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9511 (gnus-group-group-name)) ; version
9512 ((fboundp 'gnus-group-name)
9513 (gnus-group-name))
9514 (t "???"))))
9515 (unless group (error "Not on a group"))
9516 (org-store-link-props :type "gnus" :group group)
9517 (setq cpltxt (concat
9518 (if (org-xor arg org-usenet-links-prefer-google)
9519 "http://groups.google.com/groups?group="
9520 "gnus:")
9521 group)
9522 link (org-make-link cpltxt))))
9524 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9525 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9526 (let* ((group gnus-newsgroup-name)
9527 (article (gnus-summary-article-number))
9528 (header (gnus-summary-article-header article))
9529 (from (mail-header-from header))
9530 (message-id (mail-header-id header))
9531 (date (mail-header-date header))
9532 (subject (gnus-summary-subject-string)))
9533 (org-store-link-props :type "gnus" :from from :subject subject
9534 :message-id message-id :group group)
9535 (setq cpltxt (org-email-link-description))
9536 (if (org-xor arg org-usenet-links-prefer-google)
9537 (setq link
9538 (concat
9539 cpltxt "\n "
9540 (format "http://groups.google.com/groups?as_umsgid=%s"
9541 (org-fixup-message-id-for-http message-id))))
9542 (setq link (org-make-link "gnus:" group
9543 "#" (number-to-string article))))))
9545 ((eq major-mode 'w3-mode)
9546 (setq cpltxt (url-view-url t)
9547 link (org-make-link cpltxt))
9548 (org-store-link-props :type "w3" :url (url-view-url t)))
9550 ((eq major-mode 'w3m-mode)
9551 (setq cpltxt (or w3m-current-title w3m-current-url)
9552 link (org-make-link w3m-current-url))
9553 (org-store-link-props :type "w3m" :url (url-view-url t)))
9555 ((setq search (run-hook-with-args-until-success
9556 'org-create-file-search-functions))
9557 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9558 "::" search))
9559 (setq cpltxt (or description link)))
9561 ((eq major-mode 'image-mode)
9562 (setq cpltxt (concat "file:"
9563 (abbreviate-file-name buffer-file-name))
9564 link (org-make-link cpltxt))
9565 (org-store-link-props :type "image" :file buffer-file-name))
9567 ((eq major-mode 'dired-mode)
9568 ;; link to the file in the current line
9569 (setq cpltxt (concat "file:"
9570 (abbreviate-file-name
9571 (expand-file-name
9572 (dired-get-filename nil t))))
9573 link (org-make-link cpltxt)))
9575 ((and buffer-file-name (org-mode-p))
9576 ;; Just link to current headline
9577 (setq cpltxt (concat "file:"
9578 (abbreviate-file-name buffer-file-name)))
9579 ;; Add a context search string
9580 (when (org-xor org-context-in-file-links arg)
9581 ;; Check if we are on a target
9582 (if (org-in-regexp "<<\\(.*?\\)>>")
9583 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9584 (setq txt (cond
9585 ((org-on-heading-p) nil)
9586 ((org-region-active-p)
9587 (buffer-substring (region-beginning) (region-end)))
9588 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9589 (when (or (null txt) (string-match "\\S-" txt))
9590 (setq cpltxt
9591 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9592 desc "NONE"))))
9593 (if (string-match "::\\'" cpltxt)
9594 (setq cpltxt (substring cpltxt 0 -2)))
9595 (setq link (org-make-link cpltxt)))
9597 (buffer-file-name
9598 ;; Just link to this file here.
9599 (setq cpltxt (concat "file:"
9600 (abbreviate-file-name buffer-file-name)))
9601 ;; Add a context string
9602 (when (org-xor org-context-in-file-links arg)
9603 (setq txt (if (org-region-active-p)
9604 (buffer-substring (region-beginning) (region-end))
9605 (buffer-substring (point-at-bol) (point-at-eol))))
9606 ;; Only use search option if there is some text.
9607 (when (string-match "\\S-" txt)
9608 (setq cpltxt
9609 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9610 desc "NONE")))
9611 (setq link (org-make-link cpltxt)))
9613 ((interactive-p)
9614 (error "Cannot link to a buffer which is not visiting a file"))
9616 (t (setq link nil)))
9618 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9619 (setq link (or link cpltxt)
9620 desc (or desc cpltxt))
9621 (if (equal desc "NONE") (setq desc nil))
9623 (if (and (interactive-p) link)
9624 (progn
9625 (setq org-stored-links
9626 (cons (list cpltxt link desc) org-stored-links))
9627 (message "Stored: %s" (or cpltxt link)))
9628 (org-make-link-string link desc))))
9630 (defun org-store-link-props (&rest plist)
9631 "Store link properties, extract names and addresses."
9632 (let (x adr)
9633 (when (setq x (plist-get plist :from))
9634 (setq adr (mail-extract-address-components x))
9635 (plist-put plist :fromname (car adr))
9636 (plist-put plist :fromaddress (nth 1 adr)))
9637 (when (setq x (plist-get plist :to))
9638 (setq adr (mail-extract-address-components x))
9639 (plist-put plist :toname (car adr))
9640 (plist-put plist :toaddress (nth 1 adr))))
9641 (let ((from (plist-get plist :from))
9642 (to (plist-get plist :to)))
9643 (when (and from to org-from-is-user-regexp)
9644 (plist-put plist :fromto
9645 (if (string-match org-from-is-user-regexp from)
9646 (concat "to %t")
9647 (concat "from %f")))))
9648 (setq org-store-link-plist plist))
9650 (defun org-email-link-description (&optional fmt)
9651 "Return the description part of an email link.
9652 This takes information from `org-store-link-plist' and formats it
9653 according to FMT (default from `org-email-link-description-format')."
9654 (setq fmt (or fmt org-email-link-description-format))
9655 (let* ((p org-store-link-plist)
9656 (to (plist-get p :toaddress))
9657 (from (plist-get p :fromaddress))
9658 (table
9659 (list
9660 (cons "%c" (plist-get p :fromto))
9661 (cons "%F" (plist-get p :from))
9662 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9663 (cons "%T" (plist-get p :to))
9664 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9665 (cons "%s" (plist-get p :subject))
9666 (cons "%m" (plist-get p :message-id)))))
9667 (when (string-match "%c" fmt)
9668 ;; Check if the user wrote this message
9669 (if (and org-from-is-user-regexp from to
9670 (save-match-data (string-match org-from-is-user-regexp from)))
9671 (setq fmt (replace-match "to %t" t t fmt))
9672 (setq fmt (replace-match "from %f" t t fmt))))
9673 (org-replace-escapes fmt table)))
9675 (defun org-make-org-heading-search-string (&optional string heading)
9676 "Make search string for STRING or current headline."
9677 (interactive)
9678 (let ((s (or string (org-get-heading))))
9679 (unless (and string (not heading))
9680 ;; We are using a headline, clean up garbage in there.
9681 (if (string-match org-todo-regexp s)
9682 (setq s (replace-match "" t t s)))
9683 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9684 (setq s (replace-match "" t t s)))
9685 (setq s (org-trim s))
9686 (if (string-match (concat "^\\(" org-quote-string "\\|"
9687 org-comment-string "\\)") s)
9688 (setq s (replace-match "" t t s)))
9689 (while (string-match org-ts-regexp s)
9690 (setq s (replace-match "" t t s))))
9691 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9692 (setq s (replace-match " " t t s)))
9693 (or string (setq s (concat "*" s))) ; Add * for headlines
9694 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9696 (defun org-make-link (&rest strings)
9697 "Concatenate STRINGS, format resulting string with `org-link-format'."
9698 (apply 'concat strings))
9700 (defun org-make-link-string (link &optional description)
9701 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9702 (when (stringp description)
9703 ;; Remove brackets from the description, they are fatal.
9704 (while (string-match "\\[\\|\\]" description)
9705 (setq description (replace-match "" t t description))))
9706 (when (equal (org-link-escape link) description)
9707 ;; No description needed, it is identical
9708 (setq description nil))
9709 (when (and (not description)
9710 (not (equal link (org-link-escape link))))
9711 (setq description link))
9712 (concat "[[" (org-link-escape link) "]"
9713 (if description (concat "[" description "]") "")
9714 "]"))
9716 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9717 "Association list of escapes for some characters problematic in links.")
9719 (defun org-link-escape (text)
9720 "Escape charaters in TEXT that are problematic for links."
9721 (when text
9722 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9723 org-link-escape-chars "\\|")))
9724 (while (string-match re text)
9725 (setq text
9726 (replace-match
9727 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9728 t t text)))
9729 text)))
9731 (defun org-link-unescape (text)
9732 "Reverse the action of `org-link-escape'."
9733 (when text
9734 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9735 org-link-escape-chars "\\|")))
9736 (while (string-match re text)
9737 (setq text
9738 (replace-match
9739 (car (rassoc (match-string 0 text) org-link-escape-chars))
9740 t t text)))
9741 text)))
9743 (defun org-xor (a b)
9744 "Exclusive or."
9745 (if a (not b) b))
9747 (defun org-get-header (header)
9748 "Find a header field in the current buffer."
9749 (save-excursion
9750 (goto-char (point-min))
9751 (let ((case-fold-search t) s)
9752 (cond
9753 ((eq header 'from)
9754 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9755 (setq s (match-string 1)))
9756 (while (string-match "\"" s)
9757 (setq s (replace-match "" t t s)))
9758 (if (string-match "[<(].*" s)
9759 (setq s (replace-match "" t t s))))
9760 ((eq header 'message-id)
9761 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9762 (setq s (match-string 1))))
9763 ((eq header 'subject)
9764 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9765 (setq s (match-string 1)))))
9766 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9767 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9768 s)))
9771 (defun org-fixup-message-id-for-http (s)
9772 "Replace special characters in a message id, so it can be used in an http query."
9773 (while (string-match "<" s)
9774 (setq s (replace-match "%3C" t t s)))
9775 (while (string-match ">" s)
9776 (setq s (replace-match "%3E" t t s)))
9777 (while (string-match "@" s)
9778 (setq s (replace-match "%40" t t s)))
9781 (defun org-insert-link (&optional complete-file)
9782 "Insert a link. At the prompt, enter the link.
9784 Completion can be used to select a link previously stored with
9785 `org-store-link'. When the empty string is entered (i.e. if you just
9786 press RET at the prompt), the link defaults to the most recently
9787 stored link. As SPC triggers completion in the minibuffer, you need to
9788 use M-SPC or C-q SPC to force the insertion of a space character.
9790 You will also be prompted for a description, and if one is given, it will
9791 be displayed in the buffer instead of the link.
9793 If there is already a link at point, this command will allow you to edit link
9794 and description parts.
9796 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9797 selected using completion. The path to the file will be relative to
9798 the current directory if the file is in the current directory or a
9799 subdirectory. Otherwise, the link will be the absolute path as
9800 completed in the minibuffer (i.e. normally ~/path/to/file).
9802 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9803 is in the current directory or below.
9804 With three \\[universal-argument] prefixes, negate the meaning of
9805 `org-keep-stored-link-after-insertion'."
9806 (interactive "P")
9807 (let ((region (if (org-region-active-p)
9808 (prog1 (buffer-substring (region-beginning) (region-end))
9809 (delete-region (region-beginning) (region-end)))))
9810 tmphist ; byte-compile incorrectly complains about this
9811 link desc entry remove file)
9812 (cond
9813 ((org-in-regexp org-bracket-link-regexp 1)
9814 ;; We do have a link at point, and we are going to edit it.
9815 (setq remove (list (match-beginning 0) (match-end 0)))
9816 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9817 (setq link (read-string "Link: "
9818 (org-link-unescape
9819 (org-match-string-no-properties 1)))))
9820 ((or (org-in-regexp org-angle-link-re)
9821 (org-in-regexp org-plain-link-re))
9822 ;; Convert to bracket link
9823 (setq remove (list (match-beginning 0) (match-end 0))
9824 link (read-string "Link: "
9825 (org-remove-angle-brackets (match-string 0)))))
9826 ((equal complete-file '(4))
9827 ;; Completing read for file names.
9828 (setq file (read-file-name "File: "))
9829 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9830 (pwd1 (file-name-as-directory (abbreviate-file-name
9831 (expand-file-name ".")))))
9832 (cond
9833 ((equal complete-file '(16))
9834 (setq link (org-make-link
9835 "file:"
9836 (abbreviate-file-name (expand-file-name file)))))
9837 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9838 (setq link (org-make-link "file:" (match-string 1 file))))
9839 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9840 (expand-file-name file))
9841 (setq link (org-make-link
9842 "file:" (match-string 1 (expand-file-name file)))))
9843 (t (setq link (org-make-link "file:" file))))))
9845 ;; Read link, with completion for stored links.
9846 ;; Fake a link history
9847 (setq tmphist (append (mapcar 'car org-stored-links)
9848 org-insert-link-history))
9849 (setq link (org-completing-read
9850 "Link: " org-stored-links nil nil nil
9851 'tmphist
9852 (or (car (car org-stored-links)))))
9853 (setq entry (assoc link org-stored-links))
9854 (or entry (push link org-insert-link-history))
9855 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9856 (not org-keep-stored-link-after-insertion))
9857 (setq org-stored-links (delq (assoc link org-stored-links)
9858 org-stored-links)))
9859 (setq link (if entry (nth 1 entry) link)
9860 desc (or region desc (nth 2 entry)))))
9862 (if (string-match org-plain-link-re link)
9863 ;; URL-like link, normalize the use of angular brackets.
9864 (setq link (org-make-link (org-remove-angle-brackets link))))
9866 ;; Check if we are linking to the current file with a search option
9867 ;; If yes, simplify the link by using only the search option.
9868 (when (and buffer-file-name
9869 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
9870 (let* ((path (match-string 1 link))
9871 (case-fold-search nil)
9872 (search (match-string 2 link)))
9873 (save-match-data
9874 (if (equal (file-truename buffer-file-name) (file-truename path))
9875 ;; We are linking to this same file, with a search option
9876 (setq link search)))))
9878 ;; Check if we can/should use a relative path. If yes, simplify the link
9879 (when (string-match "\\<file:\\(.*\\)" link)
9880 (let* ((path (match-string 1 link))
9881 (case-fold-search nil))
9882 (cond
9883 ((eq org-link-file-path-type 'absolute)
9884 (setq path (abbreviate-file-name (expand-file-name path))))
9885 ((eq org-link-file-path-type 'noabbrev)
9886 (setq path (expand-file-name path)))
9887 ((eq org-link-file-path-type 'relative)
9888 (setq path (file-relative-name path)))
9890 (save-match-data
9891 (if (string-match (concat "^" (regexp-quote
9892 (file-name-as-directory
9893 (expand-file-name "."))))
9894 (expand-file-name path))
9895 ;; We are linking a file with relative path name.
9896 (setq path (substring (expand-file-name path)
9897 (match-end 0)))))))
9898 (setq link (concat "file:" path))))
9900 (setq desc (read-string "Description: " desc))
9901 (unless (string-match "\\S-" desc) (setq desc nil))
9902 (if remove (apply 'delete-region remove))
9903 (insert (org-make-link-string link desc))))
9905 (defun org-completing-read (&rest args)
9906 (let ((minibuffer-local-completion-map
9907 (copy-keymap minibuffer-local-completion-map)))
9908 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9909 (apply 'completing-read args)))
9911 ;;; Opening/following a link
9912 (defvar org-link-search-failed nil)
9914 (defun org-next-link ()
9915 "Move forward to the next link.
9916 If the link is in hidden text, expose it."
9917 (interactive)
9918 (when (and org-link-search-failed (eq this-command last-command))
9919 (goto-char (point-min))
9920 (message "Link search wrapped back to beginning of buffer"))
9921 (setq org-link-search-failed nil)
9922 (let* ((pos (point))
9923 (ct (org-context))
9924 (a (assoc :link ct)))
9925 (if a (goto-char (nth 2 a)))
9926 (if (re-search-forward org-any-link-re nil t)
9927 (progn
9928 (goto-char (match-beginning 0))
9929 (if (org-invisible-p) (org-show-context)))
9930 (goto-char pos)
9931 (setq org-link-search-failed t)
9932 (error "No further link found"))))
9934 (defun org-previous-link ()
9935 "Move backward to the previous link.
9936 If the link is in hidden text, expose it."
9937 (interactive)
9938 (when (and org-link-search-failed (eq this-command last-command))
9939 (goto-char (point-max))
9940 (message "Link search wrapped back to end of buffer"))
9941 (setq org-link-search-failed nil)
9942 (let* ((pos (point))
9943 (ct (org-context))
9944 (a (assoc :link ct)))
9945 (if a (goto-char (nth 1 a)))
9946 (if (re-search-backward org-any-link-re nil t)
9947 (progn
9948 (goto-char (match-beginning 0))
9949 (if (org-invisible-p) (org-show-context)))
9950 (goto-char pos)
9951 (setq org-link-search-failed t)
9952 (error "No further link found"))))
9954 (defun org-find-file-at-mouse (ev)
9955 "Open file link or URL at mouse."
9956 (interactive "e")
9957 (mouse-set-point ev)
9958 (org-open-at-point 'in-emacs))
9960 (defun org-open-at-mouse (ev)
9961 "Open file link or URL at mouse."
9962 (interactive "e")
9963 (mouse-set-point ev)
9964 (org-open-at-point))
9966 (defvar org-window-config-before-follow-link nil
9967 "The window configuration before following a link.
9968 This is saved in case the need arises to restore it.")
9970 (defvar org-open-link-marker (make-marker)
9971 "Marker pointing to the location where `org-open-at-point; was called.")
9973 (defun org-open-at-point (&optional in-emacs)
9974 "Open link at or after point.
9975 If there is no link at point, this function will search forward up to
9976 the end of the current subtree.
9977 Normally, files will be opened by an appropriate application. If the
9978 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9979 (interactive "P")
9980 (move-marker org-open-link-marker (point))
9981 (setq org-window-config-before-follow-link (current-window-configuration))
9982 (org-remove-occur-highlights nil nil t)
9983 (if (org-at-timestamp-p t)
9984 (org-follow-timestamp-link)
9985 (let (type path link line search (pos (point)))
9986 (catch 'match
9987 (save-excursion
9988 (skip-chars-forward "^]\n\r")
9989 (when (org-in-regexp org-bracket-link-regexp)
9990 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9991 (while (string-match " *\n *" link)
9992 (setq link (replace-match " " t t link)))
9993 (setq link (org-link-expand-abbrev link))
9994 (if (string-match org-link-re-with-space2 link)
9995 (setq type (match-string 1 link) path (match-string 2 link))
9996 (setq type "thisfile" path link))
9997 (throw 'match t)))
9999 (when (get-text-property (point) 'org-linked-text)
10000 (setq type "thisfile"
10001 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10002 (1+ (point)) (point))
10003 path (buffer-substring
10004 (previous-single-property-change pos 'org-linked-text)
10005 (next-single-property-change pos 'org-linked-text)))
10006 (throw 'match t))
10008 (save-excursion
10009 (when (or (org-in-regexp org-angle-link-re)
10010 (org-in-regexp org-plain-link-re))
10011 (setq type (match-string 1) path (match-string 2))
10012 (throw 'match t)))
10013 (save-excursion
10014 (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
10015 (setq type "tags"
10016 path (match-string 1))
10017 (while (string-match ":" path)
10018 (setq path (replace-match "+" t t path)))
10019 (throw 'match t))))
10020 (unless path
10021 (error "No link found"))
10022 ;; Remove any trailing spaces in path
10023 (if (string-match " +\\'" path)
10024 (setq path (replace-match "" t t path)))
10026 (cond
10028 ((equal type "mailto")
10029 (let ((cmd (car org-link-mailto-program))
10030 (args (cdr org-link-mailto-program)) args1
10031 (address path) (subject "") a)
10032 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10033 (setq address (match-string 1 path)
10034 subject (org-link-escape (match-string 2 path))))
10035 (while args
10036 (cond
10037 ((not (stringp (car args))) (push (pop args) args1))
10038 (t (setq a (pop args))
10039 (if (string-match "%a" a)
10040 (setq a (replace-match address t t a)))
10041 (if (string-match "%s" a)
10042 (setq a (replace-match subject t t a)))
10043 (push a args1))))
10044 (apply cmd (nreverse args1))))
10046 ((member type '("http" "https" "ftp" "news"))
10047 (browse-url (concat type ":" path)))
10049 ((string= type "tags")
10050 (org-tags-view in-emacs path))
10051 ((string= type "thisfile")
10052 (if in-emacs
10053 (switch-to-buffer-other-window
10054 (org-get-buffer-for-internal-link (current-buffer)))
10055 (org-mark-ring-push))
10056 (org-link-search
10057 path
10058 (cond ((equal in-emacs '(4)) 'occur)
10059 ((equal in-emacs '(16)) 'org-occur)
10060 (t nil))
10061 pos))
10063 ((string= type "file")
10064 (if (string-match "::\\([0-9]+\\)\\'" path)
10065 (setq line (string-to-number (match-string 1 path))
10066 path (substring path 0 (match-beginning 0)))
10067 (if (string-match "::\\(.+\\)\\'" path)
10068 (setq search (match-string 1 path)
10069 path (substring path 0 (match-beginning 0)))))
10070 (org-open-file path in-emacs line search))
10072 ((string= type "news")
10073 (org-follow-gnus-link path))
10075 ((string= type "bbdb")
10076 (org-follow-bbdb-link path))
10078 ((string= type "info")
10079 (org-follow-info-link path))
10081 ((string= type "gnus")
10082 (let (group article)
10083 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10084 (error "Error in Gnus link"))
10085 (setq group (match-string 1 path)
10086 article (match-string 3 path))
10087 (org-follow-gnus-link group article)))
10089 ((string= type "vm")
10090 (let (folder article)
10091 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10092 (error "Error in VM link"))
10093 (setq folder (match-string 1 path)
10094 article (match-string 3 path))
10095 ;; in-emacs is the prefix arg, will be interpreted as read-only
10096 (org-follow-vm-link folder article in-emacs)))
10098 ((string= type "wl")
10099 (let (folder article)
10100 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10101 (error "Error in Wanderlust link"))
10102 (setq folder (match-string 1 path)
10103 article (match-string 3 path))
10104 (org-follow-wl-link folder article)))
10106 ((string= type "mhe")
10107 (let (folder article)
10108 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10109 (error "Error in MHE link"))
10110 (setq folder (match-string 1 path)
10111 article (match-string 3 path))
10112 (org-follow-mhe-link folder article)))
10114 ((string= type "rmail")
10115 (let (folder article)
10116 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10117 (error "Error in RMAIL link"))
10118 (setq folder (match-string 1 path)
10119 article (match-string 3 path))
10120 (org-follow-rmail-link folder article)))
10122 ((string= type "shell")
10123 (let ((cmd path))
10124 ;; FIXME: the following is only for backward compatibility
10125 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
10126 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
10127 (if (or (not org-confirm-shell-link-function)
10128 (funcall org-confirm-shell-link-function
10129 (format "Execute \"%s\" in shell? "
10130 (org-add-props cmd nil
10131 'face 'org-warning))))
10132 (progn
10133 (message "Executing %s" cmd)
10134 (shell-command cmd))
10135 (error "Abort"))))
10137 ((string= type "elisp")
10138 (let ((cmd path))
10139 (if (or (not org-confirm-elisp-link-function)
10140 (funcall org-confirm-elisp-link-function
10141 (format "Execute \"%s\" as elisp? "
10142 (org-add-props cmd nil
10143 'face 'org-warning))))
10144 (message "%s => %s" cmd (eval (read cmd)))
10145 (error "Abort"))))
10148 (browse-url-at-point)))))
10149 (move-marker org-open-link-marker nil))
10152 ;;; File search
10154 (defvar org-create-file-search-functions nil
10155 "List of functions to construct the right search string for a file link.
10156 These functions are called in turn with point at the location to
10157 which the link should point.
10159 A function in the hook should first test if it would like to
10160 handle this file type, for example by checking the major-mode or
10161 the file extension. If it decides not to handle this file, it
10162 should just return nil to give other functions a chance. If it
10163 does handle the file, it must return the search string to be used
10164 when following the link. The search string will be part of the
10165 file link, given after a double colon, and `org-open-at-point'
10166 will automatically search for it. If special measures must be
10167 taken to make the search successful, another function should be
10168 added to the companion hook `org-execute-file-search-functions',
10169 which see.
10171 A function in this hook may also use `setq' to set the variable
10172 `description' to provide a suggestion for the descriptive text to
10173 be used for this link when it gets inserted into an Org-mode
10174 buffer with \\[org-insert-link].")
10176 (defvar org-execute-file-search-functions nil
10177 "List of functions to execute a file search triggered by a link.
10179 Functions added to this hook must accept a single argument, the
10180 search string that was part of the file link, the part after the
10181 double colon. The function must first check if it would like to
10182 handle this search, for example by checking the major-mode or the
10183 file extension. If it decides not to handle this search, it
10184 should just return nil to give other functions a chance. If it
10185 does handle the search, it must return a non-nil value to keep
10186 other functions from trying.
10188 Each function can access the current prefix argument through the
10189 variable `current-prefix-argument'. Note that a single prefix is
10190 used to force opening a link in Emacs, so it may be good to only
10191 use a numeric or double prefix to guide the search function.
10193 In case this is needed, a function in this hook can also restore
10194 the window configuration before `org-open-at-point' was called using:
10196 (set-window-configuration org-window-config-before-follow-link)")
10198 (defun org-link-search (s &optional type avoid-pos)
10199 "Search for a link search option.
10200 If S is surrounded by forward slashes, it is interpreted as a
10201 regular expression. In org-mode files, this will create an `org-occur'
10202 sparse tree. In ordinary files, `occur' will be used to list matches.
10203 If the current buffer is in `dired-mode', grep will be used to search
10204 in all files. If AVOID-POS is given, ignore matches near that position."
10205 (let ((case-fold-search t)
10206 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10207 (pos (point))
10208 (pre "") (post "")
10209 words re0 re1 re2 re3 re4 re5 re2a reall)
10210 (cond
10211 ;; First check if there are any special
10212 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10213 ;; Now try the builtin stuff
10214 ((save-excursion
10215 (goto-char (point-min))
10216 (and
10217 (re-search-forward
10218 (concat "<<" (regexp-quote s0) ">>") nil t)
10219 (setq pos (match-beginning 0))))
10220 ;; There is an exact target for this
10221 (goto-char pos))
10222 ((string-match "^/\\(.*\\)/$" s)
10223 ;; A regular expression
10224 (cond
10225 ((org-mode-p)
10226 (org-occur (match-string 1 s)))
10227 ;;((eq major-mode 'dired-mode)
10228 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10229 (t (org-do-occur (match-string 1 s)))))
10231 ;; A normal search string
10232 (when (equal (string-to-char s) ?*)
10233 ;; Anchor on headlines, post may include tags.
10234 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10235 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10236 s (substring s 1)))
10237 (remove-text-properties
10238 0 (length s)
10239 '(face nil mouse-face nil keymap nil fontified nil) s)
10240 ;; Make a series of regular expressions to find a match
10241 (setq words (org-split-string s "[ \n\r\t]+")
10242 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10243 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10244 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10245 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10246 re1 (concat pre re2 post)
10247 re3 (concat pre re4 post)
10248 re5 (concat pre ".*" re4)
10249 re2 (concat pre re2)
10250 re2a (concat pre re2a)
10251 re4 (concat pre re4)
10252 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10253 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10254 re5 "\\)"
10256 (cond
10257 ((eq type 'org-occur) (org-occur reall))
10258 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10259 (t (goto-char (point-min))
10260 (if (or (org-search-not-self 1 re0 nil t)
10261 (org-search-not-self 1 re1 nil t)
10262 (org-search-not-self 1 re2 nil t)
10263 (org-search-not-self 1 re2a nil t)
10264 (org-search-not-self 1 re3 nil t)
10265 (org-search-not-self 1 re4 nil t)
10266 (org-search-not-self 1 re5 nil t)
10268 (goto-char (match-beginning 1))
10269 (goto-char pos)
10270 (error "No match")))))
10272 ;; Normal string-search
10273 (goto-char (point-min))
10274 (if (search-forward s nil t)
10275 (goto-char (match-beginning 0))
10276 (error "No match"))))
10277 (and (org-mode-p) (org-show-context 'link-search))))
10279 (defun org-search-not-self (group &rest args)
10280 "Execute `re-search-forward', but only accept matches that do not
10281 enclose the position of `org-open-link-marker'."
10282 (let ((m org-open-link-marker))
10283 (catch 'exit
10284 (while (apply 're-search-forward args)
10285 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10286 (goto-char (match-end group))
10287 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10288 (> (match-beginning 0) (marker-position m))
10289 (< (match-end 0) (marker-position m)))
10290 (save-match-data
10291 (or (not (org-in-regexp
10292 org-bracket-link-analytic-regexp 1))
10293 (not (match-end 4)) ; no description
10294 (and (<= (match-beginning 4) (point))
10295 (>= (match-end 4) (point))))))
10296 (throw 'exit (point))))))))
10298 (defun org-get-buffer-for-internal-link (buffer)
10299 "Return a buffer to be used for displaying the link target of internal links."
10300 (cond
10301 ((not org-display-internal-link-with-indirect-buffer)
10302 buffer)
10303 ((string-match "(Clone)$" (buffer-name buffer))
10304 (message "Buffer is already a clone, not making another one")
10305 ;; we also do not modify visibility in this case
10306 buffer)
10307 (t ; make a new indirect buffer for displaying the link
10308 (let* ((bn (buffer-name buffer))
10309 (ibn (concat bn "(Clone)"))
10310 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10311 (with-current-buffer ib (org-overview))
10312 ib))))
10314 (defun org-do-occur (regexp &optional cleanup)
10315 "Call the Emacs command `occur'.
10316 If CLEANUP is non-nil, remove the printout of the regular expression
10317 in the *Occur* buffer. This is useful if the regex is long and not useful
10318 to read."
10319 (occur regexp)
10320 (when cleanup
10321 (let ((cwin (selected-window)) win beg end)
10322 (when (setq win (get-buffer-window "*Occur*"))
10323 (select-window win))
10324 (goto-char (point-min))
10325 (when (re-search-forward "match[a-z]+" nil t)
10326 (setq beg (match-end 0))
10327 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10328 (setq end (1- (match-beginning 0)))))
10329 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10330 (goto-char (point-min))
10331 (select-window cwin))))
10333 ;;; The mark ring for links jumps
10335 (defvar org-mark-ring nil
10336 "Mark ring for positions before jumps in Org-mode.")
10337 (defvar org-mark-ring-last-goto nil
10338 "Last position in the mark ring used to go back.")
10339 ;; Fill and close the ring
10340 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10341 (loop for i from 1 to org-mark-ring-length do
10342 (push (make-marker) org-mark-ring))
10343 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10344 org-mark-ring)
10346 (defun org-mark-ring-push (&optional pos buffer)
10347 "Put the current position or POS into the mark ring and rotate it."
10348 (interactive)
10349 (setq pos (or pos (point)))
10350 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10351 (move-marker (car org-mark-ring)
10352 (or pos (point))
10353 (or buffer (current-buffer)))
10354 (message
10355 (substitute-command-keys
10356 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10358 (defun org-mark-ring-goto (&optional n)
10359 "Jump to the previous position in the mark ring.
10360 With prefix arg N, jump back that many stored positions. When
10361 called several times in succession, walk through the entire ring.
10362 Org-mode commands jumping to a different position in the current file,
10363 or to another Org-mode file, automatically push the old position
10364 onto the ring."
10365 (interactive "p")
10366 (let (p m)
10367 (if (eq last-command this-command)
10368 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10369 (setq p org-mark-ring))
10370 (setq org-mark-ring-last-goto p)
10371 (setq m (car p))
10372 (switch-to-buffer (marker-buffer m))
10373 (goto-char m)
10374 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10376 (defun org-remove-angle-brackets (s)
10377 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10378 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10380 (defun org-add-angle-brackets (s)
10381 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10382 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10385 ;;; Following specific links
10387 (defun org-follow-timestamp-link ()
10388 (cond
10389 ((org-at-date-range-p t)
10390 (let ((org-agenda-start-on-weekday)
10391 (t1 (match-string 1))
10392 (t2 (match-string 2)))
10393 (setq t1 (time-to-days (org-time-string-to-time t1))
10394 t2 (time-to-days (org-time-string-to-time t2)))
10395 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10396 ((org-at-timestamp-p t)
10397 (org-agenda-list nil (time-to-days (org-time-string-to-time
10398 (substring (match-string 1) 0 10)))
10400 (t (error "This should not happen"))))
10403 (defun org-follow-bbdb-link (name)
10404 "Follow a BBDB link to NAME."
10405 (require 'bbdb)
10406 (let ((inhibit-redisplay (not debug-on-error))
10407 (bbdb-electric-p nil))
10408 (catch 'exit
10409 ;; Exact match on name
10410 (bbdb-name (concat "\\`" name "\\'") nil)
10411 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10412 ;; Exact match on name
10413 (bbdb-company (concat "\\`" name "\\'") nil)
10414 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10415 ;; Partial match on name
10416 (bbdb-name name nil)
10417 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10418 ;; Partial match on company
10419 (bbdb-company name nil)
10420 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10421 ;; General match including network address and notes
10422 (bbdb name nil)
10423 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10424 (delete-window (get-buffer-window "*BBDB*"))
10425 (error "No matching BBDB record")))))
10427 (defun org-follow-info-link (name)
10428 "Follow an info file & node link to NAME."
10429 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10430 (string-match "\\(.*\\)" name))
10431 (progn
10432 (require 'info)
10433 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10434 (Info-find-node (match-string 1 name) (match-string 2 name))
10435 (Info-find-node (match-string 1 name) "Top")))
10436 (message (concat "Could not open: " name))))
10438 (defun org-follow-gnus-link (&optional group article)
10439 "Follow a Gnus link to GROUP and ARTICLE."
10440 (require 'gnus)
10441 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10442 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10443 (cond ((and group article)
10444 (gnus-group-read-group 0 nil group)
10445 (gnus-summary-goto-article (string-to-number article) nil t))
10446 (group (gnus-group-jump-to-group group))))
10448 (defun org-follow-vm-link (&optional folder article readonly)
10449 "Follow a VM link to FOLDER and ARTICLE."
10450 (require 'vm)
10451 (setq article (org-add-angle-brackets article))
10452 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10453 ;; ange-ftp or efs or tramp access
10454 (let ((user (or (match-string 1 folder) (user-login-name)))
10455 (host (match-string 2 folder))
10456 (file (match-string 3 folder)))
10457 (cond
10458 ((featurep 'tramp)
10459 ;; use tramp to access the file
10460 (if (featurep 'xemacs)
10461 (setq folder (format "[%s@%s]%s" user host file))
10462 (setq folder (format "/%s@%s:%s" user host file))))
10464 ;; use ange-ftp or efs
10465 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10466 (setq folder (format "/%s@%s:%s" user host file))))))
10467 (when folder
10468 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10469 (sit-for 0.1)
10470 (when article
10471 (vm-select-folder-buffer)
10472 (widen)
10473 (let ((case-fold-search t))
10474 (goto-char (point-min))
10475 (if (not (re-search-forward
10476 (concat "^" "message-id: *" (regexp-quote article))))
10477 (error "Could not find the specified message in this folder"))
10478 (vm-isearch-update)
10479 (vm-isearch-narrow)
10480 (vm-beginning-of-message)
10481 (vm-summarize)))))
10483 (defun org-follow-wl-link (folder article)
10484 "Follow a Wanderlust link to FOLDER and ARTICLE."
10485 (if (and (string= folder "%")
10486 article
10487 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10488 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10489 ;; Thus, we recompose folder and article ids.
10490 (setq folder (format "%s#%s" folder (match-string 1 article))
10491 article (match-string 3 article)))
10492 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10493 (error "No such folder: %s" folder))
10494 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10495 (and article
10496 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10497 (wl-summary-redisplay)))
10499 (defun org-follow-rmail-link (folder article)
10500 "Follow an RMAIL link to FOLDER and ARTICLE."
10501 (setq article (org-add-angle-brackets article))
10502 (let (message-number)
10503 (save-excursion
10504 (save-window-excursion
10505 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10506 (setq message-number
10507 (save-restriction
10508 (widen)
10509 (goto-char (point-max))
10510 (if (re-search-backward
10511 (concat "^Message-ID:\\s-+" (regexp-quote
10512 (or article "")))
10513 nil t)
10514 (rmail-what-message))))))
10515 (if message-number
10516 (progn
10517 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10518 (rmail-show-message message-number)
10519 message-number)
10520 (error "Message not found"))))
10522 ;;; mh-e integration based on planner-mode
10523 (defun org-mhe-get-message-real-folder ()
10524 "Return the name of the current message real folder, so if you use
10525 sequences, it will now work."
10526 (save-excursion
10527 (let* ((folder
10528 (if (equal major-mode 'mh-folder-mode)
10529 mh-current-folder
10530 ;; Refer to the show buffer
10531 mh-show-folder-buffer))
10532 (end-index
10533 (if (boundp 'mh-index-folder)
10534 (min (length mh-index-folder) (length folder))))
10536 ;; a simple test on mh-index-data does not work, because
10537 ;; mh-index-data is always nil in a show buffer.
10538 (if (and (boundp 'mh-index-folder)
10539 (string= mh-index-folder (substring folder 0 end-index)))
10540 (if (equal major-mode 'mh-show-mode)
10541 (save-window-excursion
10542 (when (buffer-live-p (get-buffer folder))
10543 (progn
10544 (pop-to-buffer folder)
10545 (org-mhe-get-message-folder-from-index)
10548 (org-mhe-get-message-folder-from-index)
10550 folder
10554 (defun org-mhe-get-message-folder-from-index ()
10555 "Returns the name of the message folder in a index folder buffer."
10556 (save-excursion
10557 (mh-index-previous-folder)
10558 (re-search-forward "^\\(+.*\\)$" nil t)
10559 (message (match-string 1))))
10561 (defun org-mhe-get-message-folder ()
10562 "Return the name of the current message folder. Be careful if you
10563 use sequences."
10564 (save-excursion
10565 (if (equal major-mode 'mh-folder-mode)
10566 mh-current-folder
10567 ;; Refer to the show buffer
10568 mh-show-folder-buffer)))
10570 (defun org-mhe-get-message-num ()
10571 "Return the number of the current message. Be careful if you
10572 use sequences."
10573 (save-excursion
10574 (if (equal major-mode 'mh-folder-mode)
10575 (mh-get-msg-num nil)
10576 ;; Refer to the show buffer
10577 (mh-show-buffer-message-number))))
10579 (defun org-mhe-get-header (header)
10580 "Return a header of the message in folder mode. This will create a
10581 show buffer for the corresponding message. If you have a more clever
10582 idea..."
10583 (let* ((folder (org-mhe-get-message-folder))
10584 (num (org-mhe-get-message-num))
10585 (buffer (get-buffer-create (concat "show-" folder)))
10586 (header-field))
10587 (with-current-buffer buffer
10588 (mh-display-msg num folder)
10589 (if (equal major-mode 'mh-folder-mode)
10590 (mh-header-display)
10591 (mh-show-header-display))
10592 (set-buffer buffer)
10593 (setq header-field (mh-get-header-field header))
10594 (if (equal major-mode 'mh-folder-mode)
10595 (mh-show)
10596 (mh-show-show))
10597 header-field)))
10599 (defun org-follow-mhe-link (folder article)
10600 "Follow an MHE link to FOLDER and ARTICLE.
10601 If ARTICLE is nil FOLDER is shown. If the configuration variable
10602 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10603 ARTICLE is searched in all folders. Indexed searches (swish++,
10604 namazu, and others supported by MH-E) will always search in all
10605 folders."
10606 (require 'mh-e)
10607 (require 'mh-search)
10608 (require 'mh-utils)
10609 (mh-find-path)
10610 (if (not article)
10611 (mh-visit-folder (mh-normalize-folder-name folder))
10612 (setq article (org-add-angle-brackets article))
10613 (mh-search-choose)
10614 (if (equal mh-searcher 'pick)
10615 (progn
10616 (mh-search folder (list "--message-id" article))
10617 (when (and org-mhe-search-all-folders
10618 (not (org-mhe-get-message-real-folder)))
10619 (kill-this-buffer)
10620 (mh-search "+" (list "--message-id" article))))
10621 (mh-search "+" article))
10622 (if (org-mhe-get-message-real-folder)
10623 (mh-show-msg 1)
10624 (kill-this-buffer)
10625 (error "Message not found"))))
10627 ;;; BibTeX links
10629 ;; Use the custom search meachnism to construct and use search strings for
10630 ;; file links to BibTeX database entries.
10632 (defun org-create-file-search-in-bibtex ()
10633 "Create the search string and description for a BibTeX database entry."
10634 (when (eq major-mode 'bibtex-mode)
10635 ;; yes, we want to construct this search string.
10636 ;; Make a good description for this entry, using names, year and the title
10637 ;; Put it into the `description' variable which is dynamically scoped.
10638 (let ((bibtex-autokey-names 1)
10639 (bibtex-autokey-names-stretch 1)
10640 (bibtex-autokey-name-case-convert-function 'identity)
10641 (bibtex-autokey-name-separator " & ")
10642 (bibtex-autokey-additional-names " et al.")
10643 (bibtex-autokey-year-length 4)
10644 (bibtex-autokey-name-year-separator " ")
10645 (bibtex-autokey-titlewords 3)
10646 (bibtex-autokey-titleword-separator " ")
10647 (bibtex-autokey-titleword-case-convert-function 'identity)
10648 (bibtex-autokey-titleword-length 'infty)
10649 (bibtex-autokey-year-title-separator ": "))
10650 (setq description (bibtex-generate-autokey)))
10651 ;; Now parse the entry, get the key and return it.
10652 (save-excursion
10653 (bibtex-beginning-of-entry)
10654 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10656 (defun org-execute-file-search-in-bibtex (s)
10657 "Find the link search string S as a key for a database entry."
10658 (when (eq major-mode 'bibtex-mode)
10659 ;; Yes, we want to do the search in this file.
10660 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10661 (goto-char (point-min))
10662 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10663 (regexp-quote s) "[ \t\n]*,") nil t)
10664 (goto-char (match-beginning 0)))
10665 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10666 ;; Use double prefix to indicate that any web link should be browsed
10667 (let ((b (current-buffer)) (p (point)))
10668 ;; Restore the window configuration because we just use the web link
10669 (set-window-configuration org-window-config-before-follow-link)
10670 (save-excursion (set-buffer b) (goto-char p)
10671 (bibtex-url)))
10672 (recenter 0)) ; Move entry start to beginning of window
10673 ;; return t to indicate that the search is done.
10676 ;; Finally add the functions to the right hooks.
10677 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10678 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10680 ;; end of Bibtex link setup
10682 ;;; Following file links
10684 (defun org-open-file (path &optional in-emacs line search)
10685 "Open the file at PATH.
10686 First, this expands any special file name abbreviations. Then the
10687 configuration variable `org-file-apps' is checked if it contains an
10688 entry for this file type, and if yes, the corresponding command is launched.
10689 If no application is found, Emacs simply visits the file.
10690 With optional argument IN-EMACS, Emacs will visit the file.
10691 Optional LINE specifies a line to go to, optional SEARCH a string to
10692 search for. If LINE or SEARCH is given, the file will always be
10693 opened in Emacs.
10694 If the file does not exist, an error is thrown."
10695 (setq in-emacs (or in-emacs line search))
10696 (let* ((file (if (equal path "")
10697 buffer-file-name
10698 (substitute-in-file-name (expand-file-name path))))
10699 (apps (append org-file-apps (org-default-apps)))
10700 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10701 (dirp (if remp nil (file-directory-p file)))
10702 (dfile (downcase file))
10703 (old-buffer (current-buffer))
10704 (old-pos (point))
10705 (old-mode major-mode)
10706 ext cmd)
10707 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10708 (setq ext (match-string 1 dfile))
10709 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10710 (setq ext (match-string 1 dfile))))
10711 (if in-emacs
10712 (setq cmd 'emacs)
10713 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10714 (and dirp (cdr (assoc 'directory apps)))
10715 (cdr (assoc ext apps))
10716 (cdr (assoc t apps)))))
10717 (when (eq cmd 'mailcap)
10718 (require 'mailcap)
10719 (mailcap-parse-mailcaps)
10720 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10721 (command (mailcap-mime-info mime-type)))
10722 (if (stringp command)
10723 (setq cmd command)
10724 (setq cmd 'emacs))))
10725 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10726 (not (file-exists-p file))
10727 (not org-open-non-existing-files))
10728 (error "No such file: %s" file))
10729 (cond
10730 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10731 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10732 (if (string-match "['\"]%s['\"]" cmd)
10733 (setq cmd (replace-match "%s" t t cmd)))
10734 (setq cmd (format cmd (shell-quote-argument file)))
10735 (save-window-excursion
10736 (shell-command (concat cmd " &"))))
10737 ((or (stringp cmd)
10738 (eq cmd 'emacs))
10739 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10740 (if line (goto-line line)
10741 (if search (org-link-search search))))
10742 ((consp cmd)
10743 (eval cmd))
10744 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10745 (and (org-mode-p) (eq old-mode 'org-mode)
10746 (or (not (equal old-buffer (current-buffer)))
10747 (not (equal old-pos (point))))
10748 (org-mark-ring-push old-pos old-buffer))))
10750 (defun org-default-apps ()
10751 "Return the default applications for this operating system."
10752 (cond
10753 ((eq system-type 'darwin)
10754 org-file-apps-defaults-macosx)
10755 ((eq system-type 'windows-nt)
10756 org-file-apps-defaults-windowsnt)
10757 (t org-file-apps-defaults-gnu)))
10759 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10760 (defun org-file-remote-p (file)
10761 "Test whether FILE specifies a location on a remote system.
10762 Return non-nil if the location is indeed remote.
10764 For example, the filename \"/user@host:/foo\" specifies a location
10765 on the system \"/user@host:\"."
10766 (cond ((fboundp 'file-remote-p)
10767 (file-remote-p file))
10768 ((fboundp 'tramp-handle-file-remote-p)
10769 (tramp-handle-file-remote-p file))
10770 ((and (boundp 'ange-ftp-name-format)
10771 (string-match (car ange-ftp-name-format) file))
10773 (t nil)))
10776 ;;;; Hooks for remember.el
10778 ;;;###autoload
10779 (defun org-remember-annotation ()
10780 "Return a link to the current location as an annotation for remember.el.
10781 If you are using Org-mode files as target for data storage with
10782 remember.el, then the annotations should include a link compatible with the
10783 conventions in Org-mode. This function returns such a link."
10784 (org-store-link nil))
10786 (defconst org-remember-help
10787 "Select a destination location for the note.
10788 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10789 RET at beg-of-buf -> Append to file as level 2 headline
10790 RET on headline -> Store as sublevel entry to current headline
10791 <left>/<right> -> before/after current headline, same headings level")
10793 ;;;###autoload
10794 (defun org-remember-apply-template (&optional use-char skip-interactive)
10795 "Initialize *remember* buffer with template, invoke `org-mode'.
10796 This function should be placed into `remember-mode-hook' and in fact requires
10797 to be run from that hook to fucntion properly."
10798 (if org-remember-templates
10800 (let* ((char (or use-char
10801 (if (= (length org-remember-templates) 1)
10802 (caar org-remember-templates)
10803 (message "Select template: %s"
10804 (mapconcat
10805 (lambda (x) (char-to-string (car x)))
10806 org-remember-templates " "))
10807 (read-char-exclusive))))
10808 (entry (cdr (assoc char org-remember-templates)))
10809 (tpl (car entry))
10810 (plist-p (if org-store-link-plist t nil))
10811 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10812 (string-match "\\S-" (nth 1 entry)))
10813 (nth 1 entry)
10814 org-default-notes-file))
10815 (headline (nth 2 entry))
10816 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10817 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10818 (v-u (concat "[" (substring v-t 1 -1) "]"))
10819 (v-U (concat "[" (substring v-T 1 -1) "]"))
10820 (v-i initial) ; defined in `remember-mode'
10821 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10822 (v-n user-full-name)
10823 (org-startup-folded nil)
10824 org-time-was-given x prompt char time)
10825 (setq org-store-link-plist
10826 (append (list :annotation v-a :initial v-i)))
10827 (unless tpl (setq tpl "") (message "No template") (ding))
10828 (erase-buffer)
10829 (insert (substitute-command-keys
10830 (format
10831 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10832 ## Target file \"%s\", headline \"%s\"
10833 ## To switch templates, use `\\[org-remember]'.\n\n"
10834 (abbreviate-file-name (or file org-default-notes-file))
10835 (or headline ""))))
10836 (insert tpl) (goto-char (point-min))
10837 ;; Simple %-escapes
10838 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
10839 (when (and initial (equal (match-string 0) "%i"))
10840 (save-match-data
10841 (let* ((lead (buffer-substring
10842 (point-at-bol) (match-beginning 0))))
10843 (setq v-i (mapconcat 'identity
10844 (org-split-string initial "\n")
10845 (concat "\n" lead))))))
10846 (replace-match
10847 (or (eval (intern (concat "v-" (match-string 1)))) "")
10848 t t))
10849 ;; From the property list
10850 (when plist-p
10851 (goto-char (point-min))
10852 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10853 (and (setq x (plist-get org-store-link-plist
10854 (intern (match-string 1))))
10855 (replace-match x t t))))
10856 ;; Turn on org-mode in the remember buffer, set local variables
10857 (org-mode)
10858 (org-set-local 'org-finish-function 'remember-buffer)
10859 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10860 (org-set-local 'org-default-notes-file file))
10861 (if (and headline (stringp headline) (string-match "\\S-" headline))
10862 (org-set-local 'org-remember-default-headline headline))
10863 ;; Interactive template entries
10864 (goto-char (point-min))
10865 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
10866 (setq char (if (match-end 3) (match-string 3))
10867 prompt (if (match-end 2) (match-string 2)))
10868 (goto-char (match-beginning 0))
10869 (replace-match "")
10870 (if char
10871 (progn
10872 (setq org-time-was-given (equal (upcase char) char))
10873 (setq time (org-read-date (equal (upcase char) "U") t nil
10874 prompt))
10875 (org-insert-time-stamp time org-time-was-given
10876 (member char '("u" "U"))))
10877 (insert (read-string
10878 (if prompt (concat prompt ": ") "Enter string")))))
10879 (goto-char (point-min))
10880 (if (re-search-forward "%\\?" nil t)
10881 (replace-match "")
10882 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
10883 (org-mode)
10884 (org-set-local 'org-finish-function 'remember-buffer)))
10886 ;;;###autoload
10887 (defun org-remember ()
10888 "Call `remember'. If this is already a remember buffer, re-apply template.
10889 If there is an active region, make sure remember uses it as initial content
10890 of the remember buffer."
10891 (interactive)
10892 (if (eq org-finish-function 'remember-buffer)
10893 (progn
10894 (when (< (length org-remember-templates) 2)
10895 (error "No other template available"))
10896 (erase-buffer)
10897 (let ((annotation (plist-get org-store-link-plist :annotation))
10898 (initial (plist-get org-store-link-plist :initial)))
10899 (org-remember-apply-template))
10900 (message "Press C-c C-c to remember data"))
10901 (if (org-region-active-p)
10902 (remember (buffer-substring (point) (mark)))
10903 (call-interactively 'remember))))
10905 ;;;###autoload
10906 (defun org-remember-handler ()
10907 "Store stuff from remember.el into an org file.
10908 First prompts for an org file. If the user just presses return, the value
10909 of `org-default-notes-file' is used.
10910 Then the command offers the headings tree of the selected file in order to
10911 file the text at a specific location.
10912 You can either immediately press RET to get the note appended to the
10913 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10914 find a better place. Then press RET or <left> or <right> in insert the note.
10916 Key Cursor position Note gets inserted
10917 -----------------------------------------------------------------------------
10918 RET buffer-start as level 2 heading at end of file
10919 RET on headline as sublevel of the heading at cursor
10920 RET no heading at cursor position, level taken from context.
10921 Or use prefix arg to specify level manually.
10922 <left> on headline as same level, before current heading
10923 <right> on headline as same level, after current heading
10925 So the fastest way to store the note is to press RET RET to append it to
10926 the default file. This way your current train of thought is not
10927 interrupted, in accordance with the principles of remember.el. But with
10928 little extra effort, you can push it directly to the correct location.
10930 Before being stored away, the function ensures that the text has a
10931 headline, i.e. a first line that starts with a \"*\". If not, a headline
10932 is constructed from the current date and some additional data.
10934 If the variable `org-adapt-indentation' is non-nil, the entire text is
10935 also indented so that it starts in the same column as the headline
10936 \(i.e. after the stars).
10938 See also the variable `org-reverse-note-order'."
10939 (goto-char (point-min))
10940 (while (looking-at "^[ \t]*\n\\|^##.*\n")
10941 (replace-match ""))
10942 (catch 'quit
10943 (let* ((txt (buffer-substring (point-min) (point-max)))
10944 (fastp current-prefix-arg)
10945 (file (if fastp org-default-notes-file (org-get-org-file)))
10946 (heading org-remember-default-headline)
10947 (visiting (org-find-base-buffer-visiting file))
10948 (org-startup-folded nil)
10949 (org-startup-align-all-tables nil)
10950 (org-goto-start-pos 1)
10951 spos level indent reversed)
10952 ;; Modify text so that it becomes a nice subtree which can be inserted
10953 ;; into an org tree.
10954 (let* ((lines (split-string txt "\n"))
10955 first)
10956 (setq first (car lines) lines (cdr lines))
10957 (if (string-match "^\\*+" first)
10958 ;; Is already a headline
10959 (setq indent nil)
10960 ;; We need to add a headline: Use time and first buffer line
10961 (setq lines (cons first lines)
10962 first (concat "* " (current-time-string)
10963 " (" (remember-buffer-desc) ")")
10964 indent " "))
10965 (if (and org-adapt-indentation indent)
10966 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10967 (setq txt (concat first "\n"
10968 (mapconcat 'identity lines "\n"))))
10969 ;; Find the file
10970 (if (not visiting) (find-file-noselect file))
10971 (with-current-buffer (or visiting (get-file-buffer file))
10972 (save-excursion (and (goto-char (point-min))
10973 (not (re-search-forward "^\\* " nil t))
10974 (insert "\n* Notes\n")))
10975 (setq reversed (org-notes-order-reversed-p))
10976 (save-excursion
10977 (save-restriction
10978 (widen)
10980 ;; Find the default location
10981 (when (and heading (stringp heading) (string-match "\\S-" heading))
10982 (goto-char (point-min))
10983 (if (re-search-forward
10984 (concat "^\\*+[ \t]+" (regexp-quote heading)
10985 "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
10986 nil t)
10987 (setq org-goto-start-pos (match-beginning 0))))
10989 ;; Ask the User for a location
10990 (setq spos (if fastp
10991 org-goto-start-pos
10992 (org-get-location (current-buffer) org-remember-help)))
10993 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10994 ; not handle this note
10995 (goto-char spos)
10996 (cond ((and (bobp) (not reversed))
10997 ;; Put it at the end, one level below level 1
10998 (save-restriction
10999 (widen)
11000 (goto-char (point-max))
11001 (if (not (bolp)) (newline))
11002 (org-paste-subtree (org-get-legal-level 1 1) txt)))
11003 ((and (bobp) reversed)
11004 ;; Put it at the start, as level 1
11005 (save-restriction
11006 (widen)
11007 (goto-char (point-min))
11008 (re-search-forward "^\\*" nil t)
11009 (beginning-of-line 1)
11010 (org-paste-subtree 1 txt)))
11011 ((and (org-on-heading-p nil) (not current-prefix-arg))
11012 ;; Put it below this entry, at the beg/end of the subtree
11013 (org-back-to-heading t)
11014 (setq level (funcall outline-level))
11015 (if reversed
11016 (outline-end-of-heading)
11017 (org-end-of-subtree t))
11018 (if (not (bolp)) (newline))
11019 (beginning-of-line 1)
11020 (org-paste-subtree (org-get-legal-level level 1) txt))
11022 ;; Put it right there, with automatic level determined by
11023 ;; org-paste-subtree or from prefix arg
11024 (org-paste-subtree current-prefix-arg txt)))
11025 (when remember-save-after-remembering
11026 (save-buffer)
11027 (if (not visiting) (kill-buffer (current-buffer)))))))))
11028 t) ;; return t to indicate that we took care of this note.
11030 (defun org-get-org-file ()
11031 "Read a filename, with default directory `org-directory'."
11032 (let ((default (or org-default-notes-file remember-data-file)))
11033 (read-file-name (format "File name [%s]: " default)
11034 (file-name-as-directory org-directory)
11035 default)))
11037 (defun org-notes-order-reversed-p ()
11038 "Check if the current file should receive notes in reversed order."
11039 (cond
11040 ((not org-reverse-note-order) nil)
11041 ((eq t org-reverse-note-order) t)
11042 ((not (listp org-reverse-note-order)) nil)
11043 (t (catch 'exit
11044 (let ((all org-reverse-note-order)
11045 entry)
11046 (while (setq entry (pop all))
11047 (if (string-match (car entry) buffer-file-name)
11048 (throw 'exit (cdr entry))))
11049 nil)))))
11051 ;;;; Dynamic blocks
11053 (defun org-find-dblock (name)
11054 "Find the first dynamic block with name NAME in the buffer.
11055 If not found, stay at current position and return nil."
11056 (let (pos)
11057 (save-excursion
11058 (goto-char (point-min))
11059 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
11060 nil t)
11061 (match-beginning 0))))
11062 (if pos (goto-char pos))
11063 pos))
11065 (defconst org-dblock-start-re
11066 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11067 "Matches the startline of a dynamic block, with parameters.")
11069 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
11070 "Matches the end of a dyhamic block.")
11072 (defun org-create-dblock (plist)
11073 "Create a dynamic block section, with parameters taken from PLIST.
11074 PLIST must containe a :name entry which is used as name of the block."
11075 (unless (bolp) (newline))
11076 (let ((name (plist-get plist :name)))
11077 (insert "#+BEGIN: " name)
11078 (while plist
11079 (if (eq (car plist) :name)
11080 (setq plist (cddr plist))
11081 (insert " " (prin1-to-string (pop plist)))))
11082 (insert "\n\n#+END:\n")
11083 (beginning-of-line -2)))
11085 (defun org-prepare-dblock ()
11086 "Prepare dynamic block for refresh.
11087 This empties the block, puts the cursor at the insert position and returns
11088 the property list including an extra property :name with the block name."
11089 (unless (looking-at org-dblock-start-re)
11090 (error "Not at a dynamic block"))
11091 (let* ((begdel (1+ (match-end 0)))
11092 (name (match-string 1))
11093 (params (append (list :name name)
11094 (read (concat "(" (match-string 3) ")")))))
11095 (unless (re-search-forward org-dblock-end-re nil t)
11096 (error "Dynamic block not terminated"))
11097 (delete-region begdel (match-beginning 0))
11098 (goto-char begdel)
11099 (open-line 1)
11100 params))
11102 (defun org-map-dblocks (&optional command)
11103 "Apply COMMAND to all dynamic blocks in the current buffer.
11104 If COMMAND is not given, use `org-update-dblock'."
11105 (let ((cmd (or command 'org-update-dblock))
11106 pos)
11107 (save-excursion
11108 (goto-char (point-min))
11109 (while (re-search-forward org-dblock-start-re nil t)
11110 (goto-char (setq pos (match-beginning 0)))
11111 (condition-case nil
11112 (funcall cmd)
11113 (error (message "Error during update of dynamic block")))
11114 (goto-char pos)
11115 (unless (re-search-forward org-dblock-end-re nil t)
11116 (error "Dynamic block not terminated"))))))
11118 (defun org-dblock-update (&optional arg)
11119 "User command for updating dynamic blocks.
11120 Update the dynamic block at point. With prefix ARG, update all dynamic
11121 blocks in the buffer."
11122 (interactive "P")
11123 (if arg
11124 (org-update-all-dblocks)
11125 (or (looking-at org-dblock-start-re)
11126 (org-beginning-of-dblock))
11127 (org-update-dblock)))
11129 (defun org-update-dblock ()
11130 "Update the dynamic block at point
11131 This means to empty the block, parse for parameters and then call
11132 the correct writing function."
11133 (let* ((pos (point))
11134 (params (org-prepare-dblock))
11135 (name (plist-get params :name))
11136 (cmd (intern (concat "org-dblock-write:" name))))
11137 (funcall cmd params)
11138 (goto-char pos)))
11140 (defun org-beginning-of-dblock ()
11141 "Find the beginning of the dynamic block at point.
11142 Error if there is no scuh block at point."
11143 (let ((pos (point))
11144 beg)
11145 (end-of-line 1)
11146 (if (and (re-search-backward org-dblock-start-re nil t)
11147 (setq beg (match-beginning 0))
11148 (re-search-forward org-dblock-end-re nil t)
11149 (> (match-end 0) pos))
11150 (goto-char beg)
11151 (goto-char pos)
11152 (error "Not in a dynamic block"))))
11154 (defun org-update-all-dblocks ()
11155 "Update all dynamic blocks in the buffer.
11156 This function can be used in a hook."
11157 (when (org-mode-p)
11158 (org-map-dblocks 'org-update-dblock)))
11161 ;;;; Completion
11163 (defun org-complete (&optional arg)
11164 "Perform completion on word at point.
11165 At the beginning of a headline, this completes TODO keywords as given in
11166 `org-todo-keywords'.
11167 If the current word is preceded by a backslash, completes the TeX symbols
11168 that are supported for HTML support.
11169 If the current word is preceded by \"#+\", completes special words for
11170 setting file options.
11171 In the line after \"#+STARTUP:, complete valid keywords.\"
11172 At all other locations, this simply calls `ispell-complete-word'."
11173 (interactive "P")
11174 (catch 'exit
11175 (let* ((end (point))
11176 (beg1 (save-excursion
11177 (skip-chars-backward "a-zA-Z_@0-9")
11178 (point)))
11179 (beg (save-excursion
11180 (skip-chars-backward "a-zA-Z0-9_:$")
11181 (point)))
11182 (confirm (lambda (x) (stringp (car x))))
11183 (searchhead (equal (char-before beg) ?*))
11184 (tag (equal (char-before beg1) ?:))
11185 (texp (equal (char-before beg) ?\\))
11186 (link (equal (char-before beg) ?\[))
11187 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
11188 beg)
11189 "#+"))
11190 (startup (string-match "^#\\+STARTUP:.*"
11191 (buffer-substring (point-at-bol) (point))))
11192 (completion-ignore-case opt)
11193 (type nil)
11194 (tbl nil)
11195 (table (cond
11196 (opt
11197 (setq type :opt)
11198 (mapcar (lambda (x)
11199 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
11200 (cons (match-string 2 x) (match-string 1 x)))
11201 (org-split-string (org-get-current-options) "\n")))
11202 (startup
11203 (setq type :startup)
11204 org-startup-options)
11205 (link (append org-link-abbrev-alist-local
11206 org-link-abbrev-alist))
11207 (texp
11208 (setq type :tex)
11209 org-html-entities)
11210 ((string-match "\\`\\*+[ \t]*\\'"
11211 (buffer-substring (point-at-bol) beg))
11212 (setq type :todo)
11213 (mapcar 'list org-todo-keywords))
11214 (searchhead
11215 (setq type :searchhead)
11216 (save-excursion
11217 (goto-char (point-min))
11218 (while (re-search-forward org-todo-line-regexp nil t)
11219 (push (list
11220 (org-make-org-heading-search-string
11221 (match-string 3) t))
11222 tbl)))
11223 tbl)
11224 (tag (setq type :tag beg beg1)
11225 (or org-tag-alist (org-get-buffer-tags)))
11226 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
11227 (pattern (buffer-substring-no-properties beg end))
11228 (completion (try-completion pattern table confirm)))
11229 (cond ((eq completion t)
11230 (if (equal type :opt)
11231 (insert (substring (cdr (assoc (upcase pattern) table))
11232 (length pattern)))
11233 (if (equal type :tag) (insert ":"))))
11234 ((null completion)
11235 (message "Can't find completion for \"%s\"" pattern)
11236 (ding))
11237 ((not (string= pattern completion))
11238 (delete-region beg end)
11239 (if (string-match " +$" completion)
11240 (setq completion (replace-match "" t t completion)))
11241 (insert completion)
11242 (if (get-buffer-window "*Completions*")
11243 (delete-window (get-buffer-window "*Completions*")))
11244 (if (assoc completion table)
11245 (if (eq type :todo) (insert " ")
11246 (if (eq type :tag) (insert ":"))))
11247 (if (and (equal type :opt) (assoc completion table))
11248 (message "%s" (substitute-command-keys
11249 "Press \\[org-complete] again to insert example settings"))))
11251 (message "Making completion list...")
11252 (let ((list (sort (all-completions pattern table confirm)
11253 'string<)))
11254 (with-output-to-temp-buffer "*Completions*"
11255 (condition-case nil
11256 ;; Protection needed for XEmacs and emacs 21
11257 (display-completion-list list pattern)
11258 (error (display-completion-list list)))))
11259 (message "Making completion list...%s" "done"))))))
11261 ;;;; TODO, DEADLINE, Comments
11263 (defun org-toggle-comment ()
11264 "Change the COMMENT state of an entry."
11265 (interactive)
11266 (save-excursion
11267 (org-back-to-heading)
11268 (if (looking-at (concat outline-regexp
11269 "\\( +\\<" org-comment-string "\\>\\)"))
11270 (replace-match "" t t nil 1)
11271 (if (looking-at outline-regexp)
11272 (progn
11273 (goto-char (match-end 0))
11274 (insert " " org-comment-string))))))
11276 (defvar org-last-todo-state-is-todo nil
11277 "This is non-nil when the last TODO state change led to a TODO state.
11278 If the last change removed the TODO tag or switched to DONE, then
11279 this is nil.")
11281 (defun org-todo (&optional arg)
11282 "Change the TODO state of an item.
11283 The state of an item is given by a keyword at the start of the heading,
11284 like
11285 *** TODO Write paper
11286 *** DONE Call mom
11288 The different keywords are specified in the variable `org-todo-keywords'.
11289 By default the available states are \"TODO\" and \"DONE\".
11290 So for this example: when the item starts with TODO, it is changed to DONE.
11291 When it starts with DONE, the DONE is removed. And when neither TODO nor
11292 DONE are present, add TODO at the beginning of the heading.
11294 With C-u prefix arg, use completion to determine the new state.
11295 With numeric prefix arg, switch to that state.
11297 For calling through lisp, arg is also interpreted in the following way:
11298 'none -> empty state
11299 \"\"(empty string) -> switch to empty state
11300 'done -> switch to DONE
11301 'nextset -> switch to the next set of keywords
11302 'previousset -> switch to the previous set of keywords
11303 \"WAITING\" -> switch to the specified keyword, but only if it
11304 really is a member of `org-todo-keywords'."
11305 (interactive "P")
11306 (save-excursion
11307 (org-back-to-heading)
11308 (if (looking-at outline-regexp) (goto-char (match-end 0)))
11309 (or (looking-at (concat " +" org-todo-regexp " *"))
11310 (looking-at " *"))
11311 (let* ((this (match-string 1))
11312 (head (org-get-todo-sequence-head this))
11313 (interpret (nth 1 (assoc head org-todo-kwd-alist)))
11314 (done-word (nth 3 (assoc head org-todo-kwd-alist)))
11315 (last-state (or this ""))
11316 (completion-ignore-case t)
11317 (member (member this org-todo-keywords))
11318 (tail (cdr member))
11319 (state (cond
11320 ((equal arg '(4))
11321 ;; Read a state with completion
11322 (completing-read "State: " (mapcar (lambda(x) (list x))
11323 org-todo-keywords)
11324 nil t))
11325 ((eq arg 'right)
11326 (if this
11327 (if tail (car tail) nil)
11328 (car org-todo-keywords)))
11329 ((eq arg 'left)
11330 (if (equal member org-todo-keywords)
11332 (if this
11333 (nth (- (length org-todo-keywords) (length tail) 2)
11334 org-todo-keywords)
11335 (org-last org-todo-keywords))))
11336 (arg
11337 ;; user or caller requests a specific state
11338 (cond
11339 ((equal arg "") nil)
11340 ((eq arg 'none) nil)
11341 ((eq arg 'done) (or done-word (car org-done-keywords)))
11342 ((eq arg 'nextset)
11343 (or (car (cdr (member head org-todo-heads)))
11344 (car org-todo-heads)))
11345 ((eq arg 'previousset)
11346 (let ((org-todo-heads (reverse org-todo-heads)))
11347 (or (car (cdr (member head org-todo-heads)))
11348 (car org-todo-heads))))
11349 ((car (member arg org-todo-keywords)))
11350 ((nth (1- (prefix-numeric-value arg))
11351 org-todo-keywords))))
11352 ((null member) (or head (car org-todo-keywords)))
11353 ((member this org-done-keywords) nil) ;; -> make empty
11354 ((null tail) nil) ;; -> first entry
11355 ((eq interpret 'sequence)
11356 (car tail))
11357 ((memq interpret '(type priority))
11358 (if (eq this-command last-command)
11359 (car tail)
11360 (if (> (length tail) 0)
11361 (or done-word (car org-done-keywords))
11362 nil)))
11363 (t nil)))
11364 (next (if state (concat " " state " ") " "))
11365 dostates)
11366 (replace-match next t t)
11367 (when (memq arg '(nextset previousset))
11368 (message "Keyword set: %s"
11369 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11370 (setq org-last-todo-state-is-todo
11371 (not (member state org-done-keywords)))
11372 (when org-log-done
11373 (setq dostates (and (eq interpret 'sequence)
11374 (listp org-log-done) (memq 'state org-log-done)))
11375 (cond
11376 ((and state (not this))
11377 (org-add-planning-info nil nil 'closed)
11378 (and dostates (org-add-log-maybe 'state state 'findpos)))
11379 ((and state dostates)
11380 (org-add-log-maybe 'state state 'findpos))
11381 ((member state org-done-keywords)
11382 ;; Planning info calls the note-setting command.
11383 (org-add-planning-info 'closed (org-current-time)
11384 (if (org-get-repeat) nil 'scheduled))
11385 (org-add-log-maybe 'done state 'findpos))))
11386 ;; Fixup tag positioning
11387 (and org-auto-align-tags (org-set-tags nil t))
11388 (run-hooks 'org-after-todo-state-change-hook)
11389 (and (member state org-done-keywords) (org-auto-repeat-maybe))
11390 (if (and arg (not (member state org-done-keywords)))
11391 (setq head (org-get-todo-sequence-head state)))
11392 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
11393 ;; Fixup cursor location if close to the keyword
11394 (if (and (outline-on-heading-p)
11395 (not (bolp))
11396 (save-excursion (beginning-of-line 1)
11397 (looking-at org-todo-line-regexp))
11398 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11399 (progn
11400 (goto-char (or (match-end 2) (match-end 1)))
11401 (just-one-space))))
11403 (defun org-get-todo-sequence-head (kwd)
11404 "Return the head of the TODO sequence to which KWD belongs.
11405 If KWD is not set, check if there is a text property remembering the
11406 right sequence."
11407 (let (p)
11408 (cond
11409 ((not kwd)
11410 (or (get-text-property (point-at-bol) 'org-todo-head)
11411 (progn
11412 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11413 nil (point-at-eol)))
11414 (get-text-property p 'org-todo-head))))
11415 ((not (member kwd org-todo-keywords))
11416 (car org-todo-keywords))
11417 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11419 (defun org-get-repeat ()
11420 "Return the REPEAT statement of this entry."
11421 (save-match-data
11422 (save-excursion
11423 (org-back-to-heading t)
11424 (if (re-search-forward
11425 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11426 (match-string 1)))))
11428 (defvar org-last-changed-timestamp)
11429 (defvar org-log-post-message)
11430 (defun org-auto-repeat-maybe ()
11431 "Check if the current headline contains a REPEAT key.
11432 If yes, set TODO state back to what it was and change any SCHEDULED
11433 or DEADLINE times the new date.
11434 This function should be run in the `org-after-todo-state-change-hook'."
11435 ;; last-state is dynamically scoped into this function
11436 (let* ((repeat (org-get-repeat))
11437 (aa (assoc last-state org-todo-kwd-alist))
11438 (interpret (nth 1 aa))
11439 (head (nth 2 aa))
11440 (done-word (nth 3 aa))
11441 (whata '(("d" . day) ("m" . month) ("y" . year)))
11442 (msg "Entry repeats: ")
11443 (org-log-done)
11444 re type n what start)
11445 (when repeat
11446 (org-todo (if (eq interpret 'type) last-state head))
11447 (when (and org-log-repeat
11448 (not (memq 'org-add-log-note
11449 (default-value 'post-command-hook))))
11450 ;; Make sure a note is taken
11451 (let ((org-log-done '(done)))
11452 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
11453 'findpos)))
11454 (org-back-to-heading t)
11455 (org-add-planning-info nil nil 'closed)
11456 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11457 org-deadline-time-regexp "\\)"))
11458 (while (re-search-forward
11459 re (save-excursion (outline-next-heading) (point)) t)
11460 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11461 start 0)
11462 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11463 (setq start (match-end 0)
11464 n (string-to-number (match-string 1 repeat))
11465 what (match-string 2 repeat))
11466 (if (equal what "w") (setq n (* n 7) what "d"))
11467 (org-timestamp-change n (cdr (assoc what whata))))
11468 (setq msg (concat msg type org-last-changed-timestamp " ")))
11469 (setq org-log-post-message msg)
11470 (message msg))))
11472 (defun org-show-todo-tree (arg)
11473 "Make a compact tree which shows all headlines marked with TODO.
11474 The tree will show the lines where the regexp matches, and all higher
11475 headlines above the match.
11476 With \\[universal-argument] prefix, also show the DONE entries.
11477 With a numeric prefix N, construct a sparse tree for the Nth element
11478 of `org-todo-keywords'."
11479 (interactive "P")
11480 (let ((case-fold-search nil)
11481 (kwd-re
11482 (cond ((null arg) org-not-done-regexp)
11483 ((equal arg '(4)) org-todo-regexp)
11484 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
11485 (regexp-quote (nth (1- (prefix-numeric-value arg))
11486 org-todo-keywords)))
11487 (t (error "Invalid prefix argument: %s" arg)))))
11488 (message "%d TODO entries found"
11489 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11491 (defun org-deadline ()
11492 "Insert the DEADLINE: string to make a deadline.
11493 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11494 to modify it to the correct date."
11495 (interactive)
11496 (org-add-planning-info 'deadline nil 'closed))
11498 (defun org-schedule ()
11499 "Insert the SCHEDULED: string to schedule a TODO item.
11500 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11501 to modify it to the correct date."
11502 (interactive)
11503 (org-add-planning-info 'scheduled nil 'closed))
11505 (defun org-add-planning-info (what &optional time &rest remove)
11506 "Insert new timestamp with keyword in the line directly after the headline.
11507 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11508 If non is given, the user is prompted for a date.
11509 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11510 be removed."
11511 (interactive)
11512 (let (org-time-was-given)
11513 (when what (setq time (or time (org-read-date nil 'to-time))))
11514 (when (and org-insert-labeled-timestamps-at-point
11515 (member what '(scheduled deadline)))
11516 (insert
11517 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11518 (org-insert-time-stamp time org-time-was-given)
11519 (setq what nil))
11520 (save-excursion
11521 (save-restriction
11522 (let (col list elt ts buffer-invisibility-spec)
11523 (org-back-to-heading t)
11524 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11525 (goto-char (match-end 1))
11526 (setq col (current-column))
11527 (goto-char (1+ (match-end 0)))
11528 (if (and (not (looking-at outline-regexp))
11529 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11530 "[^\r\n]*"))
11531 (not (equal (match-string 1) org-clock-string)))
11532 (narrow-to-region (match-beginning 0) (match-end 0))
11533 (insert "\n")
11534 (backward-char 1)
11535 (narrow-to-region (point) (point))
11536 (indent-to-column col))
11537 ;; Check if we have to remove something.
11538 (setq list (cons what remove))
11539 (while list
11540 (setq elt (pop list))
11541 (goto-char (point-min))
11542 (when (or (and (eq elt 'scheduled)
11543 (re-search-forward org-scheduled-time-regexp nil t))
11544 (and (eq elt 'deadline)
11545 (re-search-forward org-deadline-time-regexp nil t))
11546 (and (eq elt 'closed)
11547 (re-search-forward org-closed-time-regexp nil t)))
11548 (replace-match "")
11549 (if (looking-at "--+<[^>]+>") (replace-match ""))
11550 (if (looking-at " +") (replace-match ""))))
11551 (goto-char (point-max))
11552 (when what
11553 (insert
11554 (if (not (equal (char-before) ?\ )) " " "")
11555 (cond ((eq what 'scheduled) org-scheduled-string)
11556 ((eq what 'deadline) org-deadline-string)
11557 ((eq what 'closed) org-closed-string))
11558 " ")
11559 (org-insert-time-stamp time
11560 (or org-time-was-given (eq what 'closed))
11561 (eq what 'closed))
11562 (end-of-line 1))
11563 (goto-char (point-min))
11564 (widen)
11565 (if (looking-at "[ \t]+\r?\n")
11566 (replace-match ""))
11567 ts)))))
11569 (defvar org-log-note-marker (make-marker))
11570 (defvar org-log-note-purpose nil)
11571 (defvar org-log-note-state nil)
11572 (defvar org-log-note-window-configuration nil)
11573 (defvar org-log-note-return-to (make-marker))
11574 (defvar org-log-post-message nil
11575 "Message to be displayed after a log note has been stored.
11576 The auto-repeater uses this.")
11578 (defun org-add-log-maybe (&optional purpose state findpos)
11579 (save-excursion
11580 (when (and (listp org-log-done)
11581 (memq purpose org-log-done))
11582 (when findpos
11583 (org-back-to-heading t)
11584 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11585 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11586 "[^\r\n]*\\)?"))
11587 (goto-char (match-end 0)))
11588 (move-marker org-log-note-marker (point))
11589 (setq org-log-note-purpose purpose)
11590 (setq org-log-note-state state)
11591 (add-hook 'post-command-hook 'org-add-log-note 'append))))
11593 (defun org-add-log-note (&optional purpose)
11594 "Pop up a window for taking a note, and add this note later at point."
11595 (remove-hook 'post-command-hook 'org-add-log-note)
11596 (setq org-log-note-window-configuration (current-window-configuration))
11597 (delete-other-windows)
11598 (move-marker org-log-note-return-to (point))
11599 (switch-to-buffer (marker-buffer org-log-note-marker))
11600 (goto-char org-log-note-marker)
11601 (switch-to-buffer-other-window "*Org Note*")
11602 (erase-buffer)
11603 (let ((org-inhibit-startup t)) (org-mode))
11604 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11605 (cond
11606 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11607 ((eq org-log-note-purpose 'done) "closed todo item")
11608 ((eq org-log-note-purpose 'state) "state change")
11609 (t (error "This should not happen")))))
11610 (org-set-local 'org-finish-function 'org-store-log-note))
11612 (defun org-store-log-note ()
11613 "Finish taking a log note, and insert it to where it belongs."
11614 (let ((txt (buffer-string))
11615 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11616 lines ind)
11617 (kill-buffer (current-buffer))
11618 (if (string-match "^#.*\n[ \t\n]*" txt)
11619 (setq txt (replace-match "" t t txt)))
11620 (if (string-match "\\s-+\\'" txt)
11621 (setq txt (replace-match "" t t txt)))
11622 (setq lines (org-split-string txt "\n"))
11623 (when (and note (string-match "\\S-" note))
11624 (setq note
11625 (org-replace-escapes
11626 note
11627 (list (cons "%u" (user-login-name))
11628 (cons "%U" user-full-name)
11629 (cons "%t" (format-time-string
11630 (org-time-stamp-format 'long 'inactive)
11631 (current-time)))
11632 (cons "%s" (if org-log-note-state
11633 (concat "\"" org-log-note-state "\"")
11634 "")))))
11635 (if lines (setq note (concat note " \\\\")))
11636 (push note lines))
11637 (save-excursion
11638 (set-buffer (marker-buffer org-log-note-marker))
11639 (save-excursion
11640 (goto-char org-log-note-marker)
11641 (move-marker org-log-note-marker nil)
11642 (end-of-line 1)
11643 (if (not (bolp)) (insert "\n")) (indent-relative nil)
11644 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
11645 (insert " - " (pop lines))
11646 (while lines
11647 (insert "\n" ind (pop lines))))))
11648 (set-window-configuration org-log-note-window-configuration)
11649 (with-current-buffer (marker-buffer org-log-note-return-to)
11650 (goto-char org-log-note-return-to))
11651 (move-marker org-log-note-return-to nil)
11652 (and org-log-post-message (message org-log-post-message)))
11654 (defvar org-occur-highlights nil)
11655 (make-variable-buffer-local 'org-occur-highlights)
11657 (defun org-occur (regexp &optional keep-previous callback)
11658 "Make a compact tree which shows all matches of REGEXP.
11659 The tree will show the lines where the regexp matches, and all higher
11660 headlines above the match. It will also show the heading after the match,
11661 to make sure editing the matching entry is easy.
11662 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11663 call to `org-occur' will be kept, to allow stacking of calls to this
11664 command.
11665 If CALLBACK is non-nil, it is a function which is called to confirm
11666 that the match should indeed be shown."
11667 (interactive "sRegexp: \nP")
11668 (or keep-previous (org-remove-occur-highlights nil nil t))
11669 (let ((cnt 0))
11670 (save-excursion
11671 (goto-char (point-min))
11672 (if (or (not keep-previous) ; do not want to keep
11673 (not org-occur-highlights)) ; no previous matches
11674 ;; hide everything
11675 (org-overview))
11676 (while (re-search-forward regexp nil t)
11677 (when (or (not callback)
11678 (save-match-data (funcall callback)))
11679 (setq cnt (1+ cnt))
11680 (org-highlight-new-match (match-beginning 0) (match-end 0))
11681 (org-show-context 'occur-tree))))
11682 (when org-remove-highlights-with-change
11683 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11684 nil 'local))
11685 (unless org-sparse-tree-open-archived-trees
11686 (org-hide-archived-subtrees (point-min) (point-max)))
11687 (run-hooks 'org-occur-hook)
11688 (if (interactive-p)
11689 (message "%d match(es) for regexp %s" cnt regexp))
11690 cnt))
11692 (defun org-show-context (&optional key)
11693 "Make sure point and context and visible.
11694 How much context is shown depends upon the variables
11695 `org-show-hierarchy-above', `org-show-following-heading'. and
11696 `org-show-siblings'."
11697 (let ((heading-p (org-on-heading-p t))
11698 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11699 (following-p (org-get-alist-option org-show-following-heading key))
11700 (siblings-p (org-get-alist-option org-show-siblings key)))
11701 (catch 'exit
11702 ;; Show heading or entry text
11703 (if heading-p
11704 (org-flag-heading nil) ; only show the heading
11705 (and (or (org-invisible-p) (org-invisible-p2))
11706 (org-show-hidden-entry))) ; show entire entry
11707 (when following-p
11708 ;; Show next sibling, or heading below text
11709 (save-excursion
11710 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11711 (org-flag-heading nil))))
11712 (when siblings-p (org-show-siblings))
11713 (when hierarchy-p
11714 ;; show all higher headings, possibly with siblings
11715 (save-excursion
11716 (while (and (condition-case nil
11717 (progn (org-up-heading-all 1) t)
11718 (error nil))
11719 (not (bobp)))
11720 (org-flag-heading nil)
11721 (when siblings-p (org-show-siblings))))))))
11723 (defun org-reveal (&optional siblings)
11724 "Show current entry, hierarchy above it, and the following headline.
11725 This can be used to show a consistent set of context around locations
11726 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11727 not t for the search context.
11729 With optional argument SIBLINGS, on each level of the hierarchy all
11730 siblings are shown. This repairs the tree structure to what it would
11731 look like when opened with hierarchical calls to `org-cycle'."
11732 (interactive "P")
11733 (let ((org-show-hierarchy-above t)
11734 (org-show-following-heading t)
11735 (org-show-siblings (if siblings t org-show-siblings)))
11736 (org-show-context nil)))
11738 (defun org-highlight-new-match (beg end)
11739 "Highlight from BEG to END and mark the highlight is an occur headline."
11740 (let ((ov (org-make-overlay beg end)))
11741 (org-overlay-put ov 'face 'secondary-selection)
11742 (push ov org-occur-highlights)))
11744 (defun org-remove-occur-highlights (&optional beg end noremove)
11745 "Remove the occur highlights from the buffer.
11746 BEG and END are ignored. If NOREMOVE is nil, remove this function
11747 from the `before-change-functions' in the current buffer."
11748 (interactive)
11749 (unless org-inhibit-highlight-removal
11750 (mapc 'org-delete-overlay org-occur-highlights)
11751 (setq org-occur-highlights nil)
11752 (unless noremove
11753 (remove-hook 'before-change-functions
11754 'org-remove-occur-highlights 'local))))
11756 ;;;; Priorities
11758 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11759 "Regular expression matching the priority indicator.")
11761 (defvar org-remove-priority-next-time nil)
11763 (defun org-priority-up ()
11764 "Increase the priority of the current item."
11765 (interactive)
11766 (org-priority 'up))
11768 (defun org-priority-down ()
11769 "Decrease the priority of the current item."
11770 (interactive)
11771 (org-priority 'down))
11773 (defun org-priority (&optional action)
11774 "Change the priority of an item by ARG.
11775 ACTION can be set, up, or down."
11776 (interactive)
11777 (setq action (or action 'set))
11778 (let (current new news have remove)
11779 (save-excursion
11780 (org-back-to-heading)
11781 (if (looking-at org-priority-regexp)
11782 (setq current (string-to-char (match-string 2))
11783 have t)
11784 (setq current org-default-priority))
11785 (cond
11786 ((eq action 'set)
11787 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
11788 (setq new (read-char-exclusive))
11789 (cond ((equal new ?\ ) (setq remove t))
11790 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11791 (error "Priority must be between `%c' and `%c'"
11792 ?A org-lowest-priority))))
11793 ((eq action 'up)
11794 (setq new (1- current)))
11795 ((eq action 'down)
11796 (setq new (1+ current)))
11797 (t (error "Invalid action")))
11798 (setq new (min (max ?A (upcase new)) org-lowest-priority))
11799 (setq news (format "%c" new))
11800 (if have
11801 (if remove
11802 (replace-match "" t t nil 1)
11803 (replace-match news t t nil 2))
11804 (if remove
11805 (error "No priority cookie found in line")
11806 (looking-at org-todo-line-regexp)
11807 (if (match-end 2)
11808 (progn
11809 (goto-char (match-end 2))
11810 (insert " [#" news "]"))
11811 (goto-char (match-beginning 3))
11812 (insert "[#" news "] ")))))
11813 (if remove
11814 (message "Priority removed")
11815 (message "Priority of current item set to %s" news))))
11818 (defun org-get-priority (s)
11819 "Find priority cookie and return priority."
11820 (save-match-data
11821 (if (not (string-match org-priority-regexp s))
11822 (* 1000 (- org-lowest-priority org-default-priority))
11823 (* 1000 (- org-lowest-priority
11824 (string-to-char (match-string 2 s)))))))
11826 ;;;; Tags
11828 (defun org-scan-tags (action matcher &optional todo-only)
11829 "Scan headline tags with inheritance and produce output ACTION.
11830 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
11831 evaluated, testing if a given set of tags qualifies a headline for
11832 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
11833 are included in the output."
11834 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11835 (mapconcat 'regexp-quote
11836 (nreverse (cdr (reverse org-todo-keywords)))
11837 "\\|")
11838 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11839 (props (list 'face nil
11840 'done-face 'org-done
11841 'undone-face nil
11842 'mouse-face 'highlight
11843 'org-not-done-regexp org-not-done-regexp
11844 'keymap org-agenda-keymap
11845 'help-echo
11846 (format "mouse-2 or RET jump to org file %s"
11847 (abbreviate-file-name buffer-file-name))))
11848 (case-fold-search nil)
11849 lspos
11850 tags tags-list tags-alist (llast 0) rtn level category i txt
11851 todo marker entry priority)
11852 (save-excursion
11853 (goto-char (point-min))
11854 (when (eq action 'sparse-tree) (org-overview))
11855 (while (re-search-forward re nil t)
11856 (catch :skip
11857 (setq todo (if (match-end 1) (match-string 2))
11858 tags (if (match-end 4) (match-string 4)))
11859 (goto-char (setq lspos (1+ (match-beginning 0))))
11860 (setq level (funcall outline-level)
11861 category (org-get-category))
11862 (setq i llast llast level)
11863 ;; remove tag lists from same and sublevels
11864 (while (>= i level)
11865 (when (setq entry (assoc i tags-alist))
11866 (setq tags-alist (delete entry tags-alist)))
11867 (setq i (1- i)))
11868 ;; add the nex tags
11869 (when tags
11870 (setq tags (mapcar 'downcase (org-split-string tags ":"))
11871 tags-alist
11872 (cons (cons level tags) tags-alist)))
11873 ;; compile tags for current headline
11874 (setq tags-list
11875 (if org-use-tag-inheritance
11876 (apply 'append (mapcar 'cdr tags-alist))
11877 tags))
11878 (when (and (or (not todo-only) todo)
11879 (eval matcher)
11880 (or (not org-agenda-skip-archived-trees)
11881 (not (member org-archive-tag tags-list))))
11882 (and (eq action 'agenda) (org-agenda-skip))
11883 ;; list this headline
11884 (if (eq action 'sparse-tree)
11885 (progn
11886 (org-show-context 'tags-tree))
11887 (setq txt (org-format-agenda-item
11889 (concat
11890 (if org-tags-match-list-sublevels
11891 (make-string (1- level) ?.) "")
11892 (org-get-heading))
11893 category tags-list)
11894 priority (org-get-priority txt))
11895 (goto-char lspos)
11896 (setq marker (org-agenda-new-marker))
11897 (org-add-props txt props
11898 'org-marker marker 'org-hd-marker marker 'org-category category
11899 'priority priority)
11900 (push txt rtn))
11901 ;; if we are to skip sublevels, jump to end of subtree
11902 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
11903 (when (and (eq action 'sparse-tree)
11904 (not org-sparse-tree-open-archived-trees))
11905 (org-hide-archived-subtrees (point-min) (point-max)))
11906 (nreverse rtn)))
11908 (defvar todo-only) ;; dynamically scoped
11910 (defun org-tags-sparse-tree (&optional todo-only match)
11911 "Create a sparse tree according to tags string MATCH.
11912 MATCH can contain positive and negative selection of tags, like
11913 \"+WORK+URGENT-WITHBOSS\".
11914 If optional argument TODO_ONLY is non-nil, only select lines that are
11915 also TODO lines."
11916 (interactive "P")
11917 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11919 (defun org-make-tags-matcher (match)
11920 "Create the TAGS//TODO matcher form for the selection string MATCH."
11921 ;; todo-only is scoped dynamically into this function, and the function
11922 ;; may change it it the matcher asksk for it.
11923 (unless match
11924 ;; Get a new match request, with completion
11925 (setq org-last-tags-completion-table
11926 (or org-tag-alist
11927 org-last-tags-completion-table))
11928 (setq match (completing-read
11929 "Match: " 'org-tags-completion-function nil nil nil
11930 'org-tags-history)))
11932 ;; Parse the string and create a lisp form
11933 (let ((match0 match)
11934 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
11935 minus tag mm
11936 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11937 orterms term orlist re-p level-p)
11938 (if (string-match "/+" match)
11939 ;; match contains also a todo-matching request
11940 (progn
11941 (setq tagsmatch (substring match 0 (match-beginning 0))
11942 todomatch (substring match (match-end 0)))
11943 (if (string-match "^!" todomatch)
11944 (setq todo-only t todomatch (substring todomatch 1)))
11945 (if (string-match "^\\s-*$" todomatch)
11946 (setq todomatch nil)))
11947 ;; only matching tags
11948 (setq tagsmatch match todomatch nil))
11950 ;; Make the tags matcher
11951 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11952 (setq tagsmatcher t)
11953 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11954 (while (setq term (pop orterms))
11955 (while (and (equal (substring term -1) "\\") orterms)
11956 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11957 (while (string-match re term)
11958 (setq minus (and (match-end 1)
11959 (equal (match-string 1 term) "-"))
11960 tag (match-string 2 term)
11961 re-p (equal (string-to-char tag) ?{)
11962 level-p (match-end 3)
11963 mm (cond
11964 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11965 (level-p `(= level ,(string-to-number
11966 (match-string 3 term))))
11967 (t `(member ,(downcase tag) tags-list)))
11968 mm (if minus (list 'not mm) mm)
11969 term (substring term (match-end 0)))
11970 (push mm tagsmatcher))
11971 (push (if (> (length tagsmatcher) 1)
11972 (cons 'and tagsmatcher)
11973 (car tagsmatcher))
11974 orlist)
11975 (setq tagsmatcher nil))
11976 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
11978 ;; Make the todo matcher
11979 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11980 (setq todomatcher t)
11981 (setq orterms (org-split-string todomatch "|") orlist nil)
11982 (while (setq term (pop orterms))
11983 (while (string-match re term)
11984 (setq minus (and (match-end 1)
11985 (equal (match-string 1 term) "-"))
11986 kwd (match-string 2 term)
11987 re-p (equal (string-to-char kwd) ?{)
11988 term (substring term (match-end 0))
11989 mm (if re-p
11990 `(string-match ,(substring kwd 1 -1) todo)
11991 (list 'equal 'todo kwd))
11992 mm (if minus (list 'not mm) mm))
11993 (push mm todomatcher))
11994 (push (if (> (length todomatcher) 1)
11995 (cons 'and todomatcher)
11996 (car todomatcher))
11997 orlist)
11998 (setq todomatcher nil))
11999 (setq todomatcher (if (> (length orlist) 1)
12000 (cons 'or orlist) (car orlist))))
12002 ;; Return the string and lisp forms of the matcher
12003 (setq matcher (if todomatcher
12004 (list 'and tagsmatcher todomatcher)
12005 tagsmatcher))
12006 (cons match0 matcher)))
12008 (defun org-match-any-p (re list)
12009 "Does re match any element of list?"
12010 (setq list (mapcar (lambda (x) (string-match re x)) list))
12011 (delq nil list))
12013 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
12014 (defvar org-tags-overlay (org-make-overlay 1 1))
12015 (org-detach-overlay org-tags-overlay)
12017 (defun org-set-tags (&optional arg just-align)
12018 "Set the tags for the current headline.
12019 With prefix ARG, realign all tags in headings in the current buffer."
12020 (interactive "P")
12021 (let* ((re (concat "^" outline-regexp))
12022 (current (org-get-tags))
12023 table current-tags inherited-tags ; computed below when needed
12024 tags p0 c0 c1 rpl)
12025 (if arg
12026 (save-excursion
12027 (goto-char (point-min))
12028 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12029 (while (re-search-forward re nil t)
12030 (org-set-tags nil t)
12031 (end-of-line 1)))
12032 (message "All tags realigned to column %d" org-tags-column))
12033 (if just-align
12034 (setq tags current)
12035 ;; Get a new set of tags from the user
12036 (save-excursion
12037 (setq table (or org-tag-alist (org-get-buffer-tags))
12038 org-last-tags-completion-table table
12039 current-tags (org-split-string current ":")
12040 inherited-tags (nreverse
12041 (nthcdr (length current-tags)
12042 (nreverse (org-get-tags-at))))
12043 tags
12044 (if (or (eq t org-use-fast-tag-selection)
12045 (and org-use-fast-tag-selection
12046 (delq nil (mapcar 'cdr table))))
12047 (org-fast-tag-selection current-tags inherited-tags table)
12048 (let ((org-add-colon-after-tag-completion t))
12049 (org-trim
12050 (completing-read "Tags: " 'org-tags-completion-function
12051 nil nil current 'org-tags-history))))))
12052 (while (string-match "[-+&]+" tags)
12053 ;; No boolean logic, just a list
12054 (setq tags (replace-match ":" t t tags))))
12056 (if (string-match "\\`[\t ]*\\'" tags)
12057 (setq tags "")
12058 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12059 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12061 ;; Insert new tags at the correct column
12062 (beginning-of-line 1)
12063 (if (re-search-forward
12064 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12065 (point-at-eol) t)
12066 (progn
12067 (if (equal tags "")
12068 (setq rpl "")
12069 (goto-char (match-beginning 0))
12070 (setq c0 (current-column) p0 (point)
12071 c1 (max (1+ c0) (if (> org-tags-column 0)
12072 org-tags-column
12073 (- (- org-tags-column) (length tags))))
12074 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12075 (replace-match rpl t t)
12076 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
12077 tags)
12078 (error "Tags alignment failed")))))
12080 (defun org-tags-completion-function (string predicate &optional flag)
12081 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12082 (confirm (lambda (x) (stringp (car x)))))
12083 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12084 (setq s1 (match-string 1 string)
12085 s2 (match-string 2 string))
12086 (setq s1 "" s2 string))
12087 (cond
12088 ((eq flag nil)
12089 ;; try completion
12090 (setq rtn (try-completion s2 ctable confirm))
12091 (if (stringp rtn)
12092 (concat s1 s2 (substring rtn (length s2))
12093 (if (and org-add-colon-after-tag-completion
12094 (assoc rtn ctable))
12095 ":" "")))
12097 ((eq flag t)
12098 ;; all-completions
12099 (all-completions s2 ctable confirm)
12101 ((eq flag 'lambda)
12102 ;; exact match?
12103 (assoc s2 ctable)))
12106 (defun org-fast-tag-insert (kwd tags face &optional end)
12107 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
12108 (insert (format "%-12s" (concat kwd ":"))
12109 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12110 (or end "")))
12112 (defun org-fast-tag-show-exit (flag)
12113 (save-excursion
12114 (goto-line 3)
12115 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12116 (replace-match ""))
12117 (when flag
12118 (end-of-line 1)
12119 (move-to-column (- (window-width) 19) t)
12120 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12122 (defun org-set-current-tags-overlay (current prefix)
12123 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12124 (if (featurep 'xemacs)
12125 (org-overlay-display org-tags-overlay (concat prefix s)
12126 'secondary-selection)
12127 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12128 (org-overlay-display org-tags-overlay (concat prefix s)))))
12130 (defun org-fast-tag-selection (current inherited table)
12131 "Fast tag selection with single keys.
12132 CURRENT is the current list of tags in the headline, INHERITED is the
12133 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12134 possibly with grouping information.
12135 If the keys are nil, a-z are automatically assigned.
12136 Returns the new tags string, or nil to not change the current settings."
12137 (let* ((maxlen (apply 'max (mapcar
12138 (lambda (x)
12139 (if (stringp (car x)) (string-width (car x)) 0))
12140 table)))
12141 (buf (current-buffer))
12142 (expert (eq org-fast-tag-selection-single-key 'expert))
12143 (buffer-tags nil)
12144 (fwidth (+ maxlen 3 1 3))
12145 (ncol (/ (- (window-width) 4) fwidth))
12146 (i-face 'org-done)
12147 (c-face 'org-tag)
12148 tg cnt e c char c1 c2 ntable tbl rtn
12149 ov-start ov-end ov-prefix
12150 (exit-after-next org-fast-tag-selection-single-key)
12151 groups ingroup)
12152 (save-excursion
12153 (beginning-of-line 1)
12154 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12155 (setq ov-start (match-beginning 1)
12156 ov-end (match-end 1)
12157 ov-prefix "")
12158 (setq ov-start (1- (point-at-eol))
12159 ov-end (1+ ov-start))
12160 (skip-chars-forward "^\n\r")
12161 (setq ov-prefix
12162 (concat
12163 (buffer-substring (1- (point)) (point))
12164 (if (> (current-column) org-tags-column)
12166 (make-string (- org-tags-column (current-column)) ?\ ))))))
12167 (org-move-overlay org-tags-overlay ov-start ov-end)
12168 (save-window-excursion
12169 (if expert
12170 (set-buffer (get-buffer-create " *Org tags*"))
12171 (delete-other-windows)
12172 (split-window-vertically)
12173 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12174 (erase-buffer)
12175 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12176 (org-fast-tag-insert "Current" current c-face "\n\n")
12177 (org-fast-tag-show-exit exit-after-next)
12178 (org-set-current-tags-overlay current ov-prefix)
12179 (setq tbl table char ?a cnt 0)
12180 (while (setq e (pop tbl))
12181 (cond
12182 ((equal e '(:startgroup))
12183 (push '() groups) (setq ingroup t)
12184 (when (not (= cnt 0))
12185 (setq cnt 0)
12186 (insert "\n"))
12187 (insert "{ "))
12188 ((equal e '(:endgroup))
12189 (setq ingroup nil cnt 0)
12190 (insert "}\n"))
12192 (setq tg (car e) c2 nil)
12193 (if (cdr e)
12194 (setq c (cdr e))
12195 ;; automatically assign a character.
12196 (setq c1 (string-to-char
12197 (downcase (substring
12198 tg (if (= (string-to-char tg) ?@) 1 0)))))
12199 (if (or (rassoc c1 ntable) (rassoc c1 table))
12200 (while (or (rassoc char ntable) (rassoc char table))
12201 (setq char (1+ char)))
12202 (setq c2 c1))
12203 (setq c (or c2 char)))
12204 (if ingroup (push tg (car groups)))
12205 (setq tg (org-add-props tg nil 'face
12206 (cond
12207 ((member tg current) c-face)
12208 ((member tg inherited) i-face)
12209 (t nil))))
12210 (if (and (= cnt 0) (not ingroup)) (insert " "))
12211 (insert "[" c "] " tg (make-string
12212 (- fwidth 4 (length tg)) ?\ ))
12213 (push (cons tg c) ntable)
12214 (when (= (setq cnt (1+ cnt)) ncol)
12215 (insert "\n")
12216 (if ingroup (insert " "))
12217 (setq cnt 0)))))
12218 (setq ntable (nreverse ntable))
12219 (insert "\n")
12220 (goto-char (point-min))
12221 (if (and (not expert) (fboundp 'fit-window-to-buffer))
12222 (fit-window-to-buffer))
12223 (setq rtn
12224 (catch 'exit
12225 (while t
12226 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
12227 (if groups " [!] no groups" " [!]groups")
12228 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12229 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12230 (cond
12231 ((= c ?\r) (throw 'exit t))
12232 ((= c ?!)
12233 (setq groups (not groups))
12234 (goto-char (point-min))
12235 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12236 ((= c ?\C-c)
12237 (if (not expert)
12238 (org-fast-tag-show-exit
12239 (setq exit-after-next (not exit-after-next)))
12240 (setq expert nil)
12241 (delete-other-windows)
12242 (split-window-vertically)
12243 (switch-to-buffer-other-window " *Org tags*")
12244 (and (fboundp 'fit-window-to-buffer)
12245 (fit-window-to-buffer))))
12246 ((or (= c ?\C-g)
12247 (and (= c ?q) (not (rassoc c ntable))))
12248 (org-detach-overlay org-tags-overlay)
12249 (setq quit-flag t))
12250 ((= c ?\ )
12251 (setq current nil)
12252 (if exit-after-next (setq exit-after-next 'now)))
12253 ((= c ?\t)
12254 (condition-case nil
12255 (setq tg (completing-read
12256 "Tag: "
12257 (or buffer-tags
12258 (with-current-buffer buf
12259 (org-get-buffer-tags)))))
12260 (quit (setq tg "")))
12261 (when (string-match "\\S-" tg)
12262 (add-to-list 'buffer-tags (list tg))
12263 (if (member tg current)
12264 (setq current (delete tg current))
12265 (push tg current)))
12266 (if exit-after-next (setq exit-after-next 'now)))
12267 ((setq e (rassoc c ntable) tg (car e))
12268 (if (member tg current)
12269 (setq current (delete tg current))
12270 (loop for g in groups do
12271 (if (member tg g)
12272 (mapcar (lambda (x)
12273 (setq current (delete x current)))
12274 g)))
12275 (push tg current))
12276 (if exit-after-next (setq exit-after-next 'now))))
12278 ;; Create a sorted list
12279 (setq current
12280 (sort current
12281 (lambda (a b)
12282 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12283 (if (eq exit-after-next 'now) (throw 'exit t))
12284 (goto-char (point-min))
12285 (beginning-of-line 2)
12286 (delete-region (point) (point-at-eol))
12287 (org-fast-tag-insert "Current" current c-face)
12288 (org-set-current-tags-overlay current ov-prefix)
12289 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
12290 (setq tg (match-string 1))
12291 (add-text-properties (match-beginning 1) (match-end 1)
12292 (list 'face
12293 (cond
12294 ((member tg current) c-face)
12295 ((member tg inherited) i-face)
12296 (t nil)))))
12297 (goto-char (point-min)))))
12298 (org-detach-overlay org-tags-overlay)
12299 (if rtn
12300 (mapconcat 'identity current ":")
12301 nil))))
12303 (defun org-get-tags ()
12304 "Get the TAGS string in the current headline."
12305 (unless (org-on-heading-p t)
12306 (error "Not on a heading"))
12307 (save-excursion
12308 (beginning-of-line 1)
12309 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12310 (org-match-string-no-properties 1)
12311 "")))
12313 (defun org-get-buffer-tags ()
12314 "Get a table of all tags used in the buffer, for completion."
12315 (let (tags)
12316 (save-excursion
12317 (goto-char (point-min))
12318 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
12319 (mapc (lambda (x) (add-to-list 'tags x))
12320 (org-split-string (org-match-string-no-properties 1) ":"))))
12321 (mapcar 'list tags)))
12323 ;;;; Timestamps
12325 (defvar org-last-changed-timestamp nil)
12326 (defvar org-time-was-given) ; dynamically scoped parameter
12327 (defvar org-ts-what) ; dynamically scoped parameter
12329 (defun org-time-stamp (arg)
12330 "Prompt for a date/time and insert a time stamp.
12331 If the user specifies a time like HH:MM, or if this command is called
12332 with a prefix argument, the time stamp will contain date and time.
12333 Otherwise, only the date will be included. All parts of a date not
12334 specified by the user will be filled in from the current date/time.
12335 So if you press just return without typing anything, the time stamp
12336 will represent the current date/time. If there is already a timestamp
12337 at the cursor, it will be modified."
12338 (interactive "P")
12339 (let (org-time-was-given time)
12340 (cond
12341 ((and (org-at-timestamp-p)
12342 (eq last-command 'org-time-stamp)
12343 (eq this-command 'org-time-stamp))
12344 (insert "--")
12345 (setq time (let ((this-command this-command))
12346 (org-read-date arg 'totime)))
12347 (org-insert-time-stamp time (or org-time-was-given arg)))
12348 ((org-at-timestamp-p)
12349 (setq time (let ((this-command this-command))
12350 (org-read-date arg 'totime)))
12351 (when (org-at-timestamp-p) ; just to get the match data
12352 (replace-match "")
12353 (setq org-last-changed-timestamp
12354 (org-insert-time-stamp time (or org-time-was-given arg))))
12355 (message "Timestamp updated"))
12357 (setq time (let ((this-command this-command))
12358 (org-read-date arg 'totime)))
12359 (org-insert-time-stamp time (or org-time-was-given arg))))))
12361 (defun org-time-stamp-inactive (&optional arg)
12362 "Insert an inactive time stamp.
12363 An inactive time stamp is enclosed in square brackets instead of angle
12364 brackets. It is inactive in the sense that it does not trigger agenda entries,
12365 does not link to the calendar and cannot be changed with the S-cursor keys.
12366 So these are more for recording a certain time/date."
12367 (interactive "P")
12368 (let (org-time-was-given time)
12369 (setq time (org-read-date arg 'totime))
12370 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
12372 (defvar org-date-ovl (org-make-overlay 1 1))
12373 (org-overlay-put org-date-ovl 'face 'org-warning)
12374 (org-detach-overlay org-date-ovl)
12376 (defvar org-ans1) ; dynamically scoped parameter
12377 (defvar org-ans2) ; dynamically scoped parameter
12379 (defun org-read-date (&optional with-time to-time from-string prompt)
12380 "Read a date and make things smooth for the user.
12381 The prompt will suggest to enter an ISO date, but you can also enter anything
12382 which will at least partially be understood by `parse-time-string'.
12383 Unrecognized parts of the date will default to the current day, month, year,
12384 hour and minute. For example,
12385 3-2-5 --> 2003-02-05
12386 feb 15 --> currentyear-02-15
12387 sep 12 9 --> 2009-09-12
12388 12:45 --> today 12:45
12389 22 sept 0:34 --> currentyear-09-22 0:34
12390 12 --> currentyear-currentmonth-12
12391 Fri --> nearest Friday (today or later)
12392 +4 --> four days from today (only if +N is the only thing given)
12393 etc.
12394 The function understands only English month and weekday abbreviations,
12395 but this can be configured with the variables `parse-time-months' and
12396 `parse-time-weekdays'.
12398 While prompting, a calendar is popped up - you can also select the
12399 date with the mouse (button 1). The calendar shows a period of three
12400 months. To scroll it to other months, use the keys `>' and `<'.
12401 If you don't like the calendar, turn it off with
12402 \(setq org-popup-calendar-for-date-prompt nil)
12404 With optional argument TO-TIME, the date will immediately be converted
12405 to an internal time.
12406 With an optional argument WITH-TIME, the prompt will suggest to also
12407 insert a time. Note that when WITH-TIME is not set, you can still
12408 enter a time, and this function will inform the calling routine about
12409 this change. The calling routine may then choose to change the format
12410 used to insert the time stamp into the buffer to include the time."
12411 (require 'parse-time)
12412 (let* ((org-time-stamp-rounding-minutes
12413 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
12414 (ct (org-current-time))
12415 (default-time
12416 ;; Default time is either today, or, when entering a range,
12417 ;; the range start.
12418 (if (save-excursion
12419 (re-search-backward
12420 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12421 (- (point) 20) t))
12422 (apply
12423 'encode-time
12424 (mapcar (lambda(x) (or x 0))
12425 (parse-time-string (match-string 1))))
12426 ct))
12427 (calendar-move-hook nil)
12428 (view-diary-entries-initially nil)
12429 (view-calendar-holidays-initially nil)
12430 (timestr (format-time-string
12431 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12432 (prompt (concat (if prompt (concat prompt " ") "")
12433 (format "Date and/or time (default [%s]): " timestr)))
12434 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12435 second minute hour day month year tl wday wday1 pm)
12437 (cond
12438 (from-string (setq ans from-string))
12439 (org-popup-calendar-for-date-prompt
12440 (save-excursion
12441 (save-window-excursion
12442 (calendar)
12443 (calendar-forward-day (- (time-to-days default-time)
12444 (calendar-absolute-from-gregorian
12445 (calendar-current-date))))
12446 (org-eval-in-calendar nil)
12447 (let* ((old-map (current-local-map))
12448 (map (copy-keymap calendar-mode-map))
12449 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12450 (define-key map (kbd "RET") 'org-calendar-select)
12451 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
12452 'org-calendar-select-mouse)
12453 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
12454 'org-calendar-select-mouse)
12455 (define-key minibuffer-local-map [(meta shift left)]
12456 (lambda () (interactive)
12457 (org-eval-in-calendar '(calendar-backward-month 1))))
12458 (define-key minibuffer-local-map [(meta shift right)]
12459 (lambda () (interactive)
12460 (org-eval-in-calendar '(calendar-forward-month 1))))
12461 (define-key minibuffer-local-map [(shift up)]
12462 (lambda () (interactive)
12463 (org-eval-in-calendar '(calendar-backward-week 1))))
12464 (define-key minibuffer-local-map [(shift down)]
12465 (lambda () (interactive)
12466 (org-eval-in-calendar '(calendar-forward-week 1))))
12467 (define-key minibuffer-local-map [(shift left)]
12468 (lambda () (interactive)
12469 (org-eval-in-calendar '(calendar-backward-day 1))))
12470 (define-key minibuffer-local-map [(shift right)]
12471 (lambda () (interactive)
12472 (org-eval-in-calendar '(calendar-forward-day 1))))
12473 (define-key minibuffer-local-map ">"
12474 (lambda () (interactive)
12475 (org-eval-in-calendar '(scroll-calendar-left 1))))
12476 (define-key minibuffer-local-map "<"
12477 (lambda () (interactive)
12478 (org-eval-in-calendar '(scroll-calendar-right 1))))
12479 (unwind-protect
12480 (progn
12481 (use-local-map map)
12482 (setq org-ans0 (read-string prompt "" nil nil))
12483 ;; org-ans0: from prompt
12484 ;; org-ans1: from mouse click
12485 ;; org-ans2: from calendar motion
12486 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12487 (use-local-map old-map))))))
12488 (t ; Naked prompt only
12489 (setq ans (read-string prompt "" nil timestr))))
12490 (org-detach-overlay org-date-ovl)
12492 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12493 (setq deltadays (string-to-number ans) ans ""))
12495 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12496 (when (string-match
12497 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12498 (setq year (if (match-end 2)
12499 (string-to-number (match-string 2 ans))
12500 (string-to-number (format-time-string "%Y")))
12501 month (string-to-number (match-string 3 ans))
12502 day (string-to-number (match-string 4 ans)))
12503 (if (< year 100) (setq year (+ 2000 year)))
12504 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12505 t nil ans)))
12506 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12507 ;; If there is a time with am/pm, and *no* time without it, we convert
12508 ;; convert so that matching will be successful.
12509 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12510 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12511 (setq hour (string-to-number (match-string 1 ans))
12512 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
12513 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
12514 (if (and (= hour 12) (not pm))
12515 (setq hour 0)
12516 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12517 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
12519 (setq tl (parse-time-string ans)
12520 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12521 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12522 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12523 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12524 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12525 second (or (nth 0 tl) 0)
12526 wday (nth 6 tl))
12527 (setq day (+ day deltadays))
12528 (when (and wday (not (nth 3 tl)))
12529 ;; Weekday was given, but no day, so pick that day in the week
12530 ;; on or after the derived date.
12531 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12532 (unless (equal wday wday1)
12533 (setq day (+ day (% (- wday wday1 -7) 7)))))
12534 (if (and (boundp 'org-time-was-given)
12535 (nth 2 tl))
12536 (setq org-time-was-given t))
12537 (if (< year 100) (setq year (+ 2000 year)))
12538 (if to-time
12539 (encode-time second minute hour day month year)
12540 (if (or (nth 1 tl) (nth 2 tl))
12541 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12542 (format "%04d-%02d-%02d" year month day)))))
12544 (defun org-eval-in-calendar (form)
12545 "Eval FORM in the calendar window and return to current window.
12546 Also, store the cursor date in variable org-ans2."
12547 (let ((sw (selected-window)))
12548 (select-window (get-buffer-window "*Calendar*"))
12549 (eval form)
12550 (when (calendar-cursor-to-date)
12551 (let* ((date (calendar-cursor-to-date))
12552 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12553 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12554 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12555 (select-window sw)
12556 ;; Update the prompt to show new default date
12557 (save-excursion
12558 (goto-char (point-min))
12559 (when (and (re-search-forward "\\[[-0-9]+\\]" nil t)
12560 (get-text-property (match-end 0) 'field))
12561 (let ((inhibit-read-only t))
12562 (replace-match (concat "[" org-ans2 "]") t t)
12563 (add-text-properties (point-min) (1+ (match-end 0))
12564 (text-properties-at (1+ (point-min)))))))))
12566 (defun org-calendar-select ()
12567 "Return to `org-read-date' with the date currently selected.
12568 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12569 (interactive)
12570 (when (calendar-cursor-to-date)
12571 (let* ((date (calendar-cursor-to-date))
12572 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12573 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12574 (if (active-minibuffer-window) (exit-minibuffer))))
12576 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12577 "Insert a date stamp for the date given by the internal TIME.
12578 WITH-HM means, use the stamp format that includes the time of the day.
12579 INACTIVE means use square brackets instead of angular ones, so that the
12580 stamp will not contribute to the agenda.
12581 PRE and POST are optional strings to be inserted before and after the
12582 stamp.
12583 The command returns the inserted time stamp."
12584 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12585 stamp)
12586 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12587 (insert (or pre ""))
12588 (insert (setq stamp (format-time-string fmt time)))
12589 (insert (or post ""))
12590 stamp))
12592 (defun org-toggle-time-stamp-overlays ()
12593 "Toggle the use of custom time stamp formats."
12594 (interactive)
12595 (setq org-display-custom-times (not org-display-custom-times))
12596 (unless org-display-custom-times
12597 (let ((p (point-min)) (bmp (buffer-modified-p)))
12598 (while (setq p (next-single-property-change p 'display))
12599 (if (and (get-text-property p 'display)
12600 (eq (get-text-property p 'face) 'org-date))
12601 (remove-text-properties
12602 p (setq p (next-single-property-change p 'display))
12603 '(display t))))
12604 (set-buffer-modified-p bmp)))
12605 (if (featurep 'xemacs)
12606 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12607 (org-restart-font-lock)
12608 (setq org-table-may-need-update t)
12609 (if org-display-custom-times
12610 (message "Time stamps are overlayed with custom format")
12611 (message "Time stamp overlays removed")))
12613 (defun org-display-custom-time (beg end)
12614 "Overlay modified time stamp format over timestamp between BED and END."
12615 (let* ((t1 (save-match-data
12616 (org-parse-time-string (buffer-substring beg end) t)))
12617 (w1 (- end beg))
12618 (with-hm (and (nth 1 t1) (nth 2 t1)))
12619 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12620 (time (org-fix-decoded-time t1))
12621 (str (org-add-props
12622 (format-time-string
12623 (substring tf 1 -1) (apply 'encode-time time))
12624 nil 'mouse-face 'highlight))
12625 (w2 (length str)))
12626 (if (not (= w2 w1))
12627 (add-text-properties (1+ beg) (+ 2 beg)
12628 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12629 (if (featurep 'xemacs)
12630 (progn
12631 (put-text-property beg end 'invisible t)
12632 (put-text-property beg end 'end-glyph (make-glyph str)))
12633 (put-text-property beg end 'display str))))
12635 (defun org-translate-time (string)
12636 "Translate all timestamps in STRING to custom format.
12637 But do this only if the variable `org-display-custom-times' is set."
12638 (when org-display-custom-times
12639 (save-match-data
12640 (let* ((start 0)
12641 (re org-ts-regexp-both)
12642 t1 with-hm inactive tf time str beg end)
12643 (while (setq start (string-match re string start))
12644 (setq beg (match-beginning 0)
12645 end (match-end 0)
12646 t1 (save-match-data
12647 (org-parse-time-string (substring string beg end) t))
12648 with-hm (and (nth 1 t1) (nth 2 t1))
12649 inactive (equal (substring string beg (1+ beg)) "[")
12650 tf (funcall (if with-hm 'cdr 'car)
12651 org-time-stamp-custom-formats)
12652 time (org-fix-decoded-time t1)
12653 str (format-time-string
12654 (concat
12655 (if inactive "[" "<") (substring tf 1 -1)
12656 (if inactive "]" ">"))
12657 (apply 'encode-time time))
12658 string (replace-match str t t string)
12659 start (+ start (length str)))))))
12660 string)
12662 (defun org-fix-decoded-time (time)
12663 "Set 0 instead of nil for the first 6 elements of time.
12664 Don't touch the rest."
12665 (let ((n 0))
12666 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12668 (defun org-days-to-time (timestamp-string)
12669 "Difference between TIMESTAMP-STRING and now in days."
12670 (- (time-to-days (org-time-string-to-time timestamp-string))
12671 (time-to-days (current-time))))
12673 (defun org-deadline-close (timestamp-string &optional ndays)
12674 "Is the time in TIMESTAMP-STRING close to the current date?"
12675 (and (< (org-days-to-time timestamp-string)
12676 (or ndays org-deadline-warning-days))
12677 (not (org-entry-is-done-p))))
12679 (defun org-calendar-select-mouse (ev)
12680 "Return to `org-read-date' with the date currently selected.
12681 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12682 (interactive "e")
12683 (mouse-set-point ev)
12684 (when (calendar-cursor-to-date)
12685 (let* ((date (calendar-cursor-to-date))
12686 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12687 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12688 (if (active-minibuffer-window) (exit-minibuffer))))
12690 (defun org-check-deadlines (ndays)
12691 "Check if there are any deadlines due or past due.
12692 A deadline is considered due if it happens within `org-deadline-warning-days'
12693 days from today's date. If the deadline appears in an entry marked DONE,
12694 it is not shown. The prefix arg NDAYS can be used to test that many
12695 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12696 (interactive "P")
12697 (let* ((org-warn-days
12698 (cond
12699 ((equal ndays '(4)) 100000)
12700 (ndays (prefix-numeric-value ndays))
12701 (t org-deadline-warning-days)))
12702 (case-fold-search nil)
12703 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12704 (callback
12705 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12707 (message "%d deadlines past-due or due within %d days"
12708 (org-occur regexp nil callback)
12709 org-warn-days)))
12711 (defun org-evaluate-time-range (&optional to-buffer)
12712 "Evaluate a time range by computing the difference between start and end.
12713 Normally the result is just printed in the echo area, but with prefix arg
12714 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12715 If the time range is actually in a table, the result is inserted into the
12716 next column.
12717 For time difference computation, a year is assumed to be exactly 365
12718 days in order to avoid rounding problems."
12719 (interactive "P")
12721 (org-clock-update-time-maybe)
12722 (save-excursion
12723 (unless (org-at-date-range-p)
12724 (goto-char (point-at-bol))
12725 (re-search-forward org-tr-regexp (point-at-eol) t))
12726 (if (not (org-at-date-range-p))
12727 (error "Not at a time-stamp range, and none found in current line")))
12728 (let* ((ts1 (match-string 1))
12729 (ts2 (match-string 2))
12730 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12731 (match-end (match-end 0))
12732 (time1 (org-time-string-to-time ts1))
12733 (time2 (org-time-string-to-time ts2))
12734 (t1 (time-to-seconds time1))
12735 (t2 (time-to-seconds time2))
12736 (diff (abs (- t2 t1)))
12737 (negative (< (- t2 t1) 0))
12738 ;; (ys (floor (* 365 24 60 60)))
12739 (ds (* 24 60 60))
12740 (hs (* 60 60))
12741 (fy "%dy %dd %02d:%02d")
12742 (fy1 "%dy %dd")
12743 (fd "%dd %02d:%02d")
12744 (fd1 "%dd")
12745 (fh "%02d:%02d")
12746 y d h m align)
12747 (if havetime
12748 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12750 d (floor (/ diff ds)) diff (mod diff ds)
12751 h (floor (/ diff hs)) diff (mod diff hs)
12752 m (floor (/ diff 60)))
12753 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12755 d (floor (+ (/ diff ds) 0.5))
12756 h 0 m 0))
12757 (if (not to-buffer)
12758 (message (org-make-tdiff-string y d h m))
12759 (when (org-at-table-p)
12760 (goto-char match-end)
12761 (setq align t)
12762 (and (looking-at " *|") (goto-char (match-end 0))))
12763 (if (looking-at
12764 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12765 (replace-match ""))
12766 (if negative (insert " -"))
12767 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12768 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12769 (insert " " (format fh h m))))
12770 (if align (org-table-align))
12771 (message "Time difference inserted")))))
12773 (defun org-make-tdiff-string (y d h m)
12774 (let ((fmt "")
12775 (l nil))
12776 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12777 l (push y l)))
12778 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12779 l (push d l)))
12780 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12781 l (push h l)))
12782 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12783 l (push m l)))
12784 (apply 'format fmt (nreverse l))))
12786 (defun org-time-string-to-time (s)
12787 (apply 'encode-time (org-parse-time-string s)))
12789 (defun org-parse-time-string (s &optional nodefault)
12790 "Parse the standard Org-mode time string.
12791 This should be a lot faster than the normal `parse-time-string'.
12792 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12793 hour and minute fields will be nil if not given."
12794 (if (string-match org-ts-regexp1 s)
12795 (list 0
12796 (if (or (match-beginning 8) (not nodefault))
12797 (string-to-number (or (match-string 8 s) "0")))
12798 (if (or (match-beginning 7) (not nodefault))
12799 (string-to-number (or (match-string 7 s) "0")))
12800 (string-to-number (match-string 4 s))
12801 (string-to-number (match-string 3 s))
12802 (string-to-number (match-string 2 s))
12803 nil nil nil)
12804 (make-list 9 0)))
12806 (defun org-timestamp-up (&optional arg)
12807 "Increase the date item at the cursor by one.
12808 If the cursor is on the year, change the year. If it is on the month or
12809 the day, change that.
12810 With prefix ARG, change by that many units."
12811 (interactive "p")
12812 (org-timestamp-change (prefix-numeric-value arg)))
12814 (defun org-timestamp-down (&optional arg)
12815 "Decrease the date item at the cursor by one.
12816 If the cursor is on the year, change the year. If it is on the month or
12817 the day, change that.
12818 With prefix ARG, change by that many units."
12819 (interactive "p")
12820 (org-timestamp-change (- (prefix-numeric-value arg))))
12822 (defun org-timestamp-up-day (&optional arg)
12823 "Increase the date in the time stamp by one day.
12824 With prefix ARG, change that many days."
12825 (interactive "p")
12826 (if (and (not (org-at-timestamp-p t))
12827 (org-on-heading-p))
12828 (org-todo 'up)
12829 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12831 (defun org-timestamp-down-day (&optional arg)
12832 "Decrease the date in the time stamp by one day.
12833 With prefix ARG, change that many days."
12834 (interactive "p")
12835 (if (and (not (org-at-timestamp-p t))
12836 (org-on-heading-p))
12837 (org-todo 'down)
12838 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12840 (defsubst org-pos-in-match-range (pos n)
12841 (and (match-beginning n)
12842 (<= (match-beginning n) pos)
12843 (>= (match-end n) pos)))
12845 (defun org-at-timestamp-p (&optional inactive-ok)
12846 "Determine if the cursor is in or at a timestamp."
12847 (interactive)
12848 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12849 (pos (point))
12850 (ans (or (looking-at tsr)
12851 (save-excursion
12852 (skip-chars-backward "^[<\n\r\t")
12853 (if (> (point) 1) (backward-char 1))
12854 (and (looking-at tsr)
12855 (> (- (match-end 0) pos) -1))))))
12856 (and (boundp 'org-ts-what)
12857 (setq org-ts-what
12858 (cond
12859 ((org-pos-in-match-range pos 2) 'year)
12860 ((org-pos-in-match-range pos 3) 'month)
12861 ((org-pos-in-match-range pos 7) 'hour)
12862 ((org-pos-in-match-range pos 8) 'minute)
12863 ((or (org-pos-in-match-range pos 4)
12864 (org-pos-in-match-range pos 5)) 'day)
12865 (t 'day))))
12866 ans))
12868 (defun org-timestamp-change (n &optional what)
12869 "Change the date in the time stamp at point.
12870 The date will be changed by N times WHAT. WHAT can be `day', `month',
12871 `year', `minute', `second'. If WHAT is not given, the cursor position
12872 in the timestamp determines what will be changed."
12873 (let ((pos (point))
12874 with-hm inactive
12875 org-ts-what
12876 ts time time0)
12877 (if (not (org-at-timestamp-p t))
12878 (error "Not at a timestamp"))
12879 (if (and (not what) (not (eq org-ts-what 'day))
12880 org-display-custom-times
12881 (get-text-property (point) 'display)
12882 (not (get-text-property (1- (point)) 'display)))
12883 (setq org-ts-what 'day))
12884 (setq org-ts-what (or what org-ts-what)
12885 with-hm (<= (abs (- (cdr org-ts-lengths)
12886 (- (match-end 0) (match-beginning 0))))
12888 inactive (= (char-after (match-beginning 0)) ?\[)
12889 ts (match-string 0))
12890 (replace-match "")
12891 (setq time0 (org-parse-time-string ts))
12892 (setq time
12893 (apply 'encode-time
12894 (append
12895 (list (or (car time0) 0))
12896 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
12897 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
12898 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
12899 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
12900 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
12901 (nthcdr 6 time0))))
12902 (if (eq what 'calendar)
12903 (let ((cal-date
12904 (save-excursion
12905 (save-match-data
12906 (set-buffer "*Calendar*")
12907 (calendar-cursor-to-date)))))
12908 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12909 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12910 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12911 (setcar time0 (or (car time0) 0))
12912 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12913 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
12914 (setq time (apply 'encode-time time0))))
12915 (setq org-last-changed-timestamp
12916 (org-insert-time-stamp time with-hm inactive))
12917 (org-clock-update-time-maybe)
12918 (goto-char pos)
12919 ;; Try to recenter the calendar window, if any
12920 (if (and org-calendar-follow-timestamp-change
12921 (get-buffer-window "*Calendar*" t)
12922 (memq org-ts-what '(day month year)))
12923 (org-recenter-calendar (time-to-days time)))))
12925 (defun org-recenter-calendar (date)
12926 "If the calendar is visible, recenter it to DATE."
12927 (let* ((win (selected-window))
12928 (cwin (get-buffer-window "*Calendar*" t))
12929 (calendar-move-hook nil))
12930 (when cwin
12931 (select-window cwin)
12932 (calendar-goto-date (if (listp date) date
12933 (calendar-gregorian-from-absolute date)))
12934 (select-window win))))
12936 (defun org-goto-calendar (&optional arg)
12937 "Go to the Emacs calendar at the current date.
12938 If there is a time stamp in the current line, go to that date.
12939 A prefix ARG can be used to force the current date."
12940 (interactive "P")
12941 (let ((tsr org-ts-regexp) diff
12942 (calendar-move-hook nil)
12943 (view-calendar-holidays-initially nil)
12944 (view-diary-entries-initially nil))
12945 (if (or (org-at-timestamp-p)
12946 (save-excursion
12947 (beginning-of-line 1)
12948 (looking-at (concat ".*" tsr))))
12949 (let ((d1 (time-to-days (current-time)))
12950 (d2 (time-to-days
12951 (org-time-string-to-time (match-string 1)))))
12952 (setq diff (- d2 d1))))
12953 (calendar)
12954 (calendar-goto-today)
12955 (if (and diff (not arg)) (calendar-forward-day diff))))
12957 (defun org-date-from-calendar ()
12958 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12959 If there is already a time stamp at the cursor position, update it."
12960 (interactive)
12961 (org-timestamp-change 0 'calendar))
12963 ;;; The clock for measuring work time.
12965 (defvar org-clock-marker (make-marker)
12966 "Marker recording the last clock-in.")
12968 (defun org-clock-in ()
12969 "Start the clock on the current item.
12970 If necessary, clock-out of the currently active clock."
12971 (interactive)
12972 (org-clock-out t)
12973 (let (ts)
12974 (save-excursion
12975 (org-back-to-heading t)
12976 (beginning-of-line 2)
12977 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12978 (not (equal (match-string 1) org-clock-string)))
12979 ;; First line hast scheduling info, move one further
12980 (beginning-of-line 2)
12981 (or (bolp) (newline)))
12982 (insert "\n") (backward-char 1)
12983 (indent-relative)
12984 (insert org-clock-string " ")
12985 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12986 (move-marker org-clock-marker (point) (buffer-base-buffer))
12987 (message "Clock started at %s" ts))))
12989 (defun org-clock-out (&optional fail-quietly)
12990 "Stop the currently running clock.
12991 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12992 (interactive)
12993 (catch 'exit
12994 (if (not (marker-buffer org-clock-marker))
12995 (if fail-quietly (throw 'exit t) (error "No active clock")))
12996 (let (ts te s h m)
12997 (save-excursion
12998 (set-buffer (marker-buffer org-clock-marker))
12999 (goto-char org-clock-marker)
13000 (beginning-of-line 1)
13001 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13002 (equal (match-string 1) org-clock-string))
13003 (setq ts (match-string 2))
13004 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
13005 (goto-char org-clock-marker)
13006 (insert "--")
13007 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13008 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
13009 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
13010 h (floor (/ s 3600))
13011 s (- s (* 3600 h))
13012 m (floor (/ s 60))
13013 s (- s (* 60 s)))
13014 (insert " => " (format "%2d:%02d" h m))
13015 (move-marker org-clock-marker nil)
13016 (org-add-log-maybe 'clock-out)
13017 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
13019 (defun org-clock-cancel ()
13020 "Cancel the running clock be removing the start timestamp."
13021 (interactive)
13022 (if (not (marker-buffer org-clock-marker))
13023 (error "No active clock"))
13024 (save-excursion
13025 (set-buffer (marker-buffer org-clock-marker))
13026 (goto-char org-clock-marker)
13027 (delete-region (1- (point-at-bol)) (point-at-eol)))
13028 (message "Clock canceled"))
13030 (defvar org-clock-file-total-minutes nil
13031 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
13032 (make-variable-buffer-local 'org-clock-file-total-minutes)
13034 (defun org-clock-sum (&optional tstart tend)
13035 "Sum the times for each subtree.
13036 Puts the resulting times in minutes as a text property on each headline."
13037 (interactive)
13038 (let* ((bmp (buffer-modified-p))
13039 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
13040 org-clock-string
13041 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
13042 (lmax 30)
13043 (ltimes (make-vector lmax 0))
13044 (t1 0)
13045 (level 0)
13046 ts te dt
13047 time)
13048 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
13049 (save-excursion
13050 (goto-char (point-max))
13051 (while (re-search-backward re nil t)
13052 (if (match-end 2)
13053 ;; A time
13054 (setq ts (match-string 2)
13055 te (match-string 3)
13056 ts (time-to-seconds
13057 (apply 'encode-time (org-parse-time-string ts)))
13058 te (time-to-seconds
13059 (apply 'encode-time (org-parse-time-string te)))
13060 ts (if tstart (max ts tstart) ts)
13061 te (if tend (min te tend) te)
13062 dt (- te ts)
13063 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
13064 ;; A headline
13065 (setq level (- (match-end 1) (match-beginning 1)))
13066 (when (or (> t1 0) (> (aref ltimes level) 0))
13067 (loop for l from 0 to level do
13068 (aset ltimes l (+ (aref ltimes l) t1)))
13069 (setq t1 0 time (aref ltimes level))
13070 (loop for l from level to (1- lmax) do
13071 (aset ltimes l 0))
13072 (goto-char (match-beginning 0))
13073 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
13074 (setq org-clock-file-total-minutes (aref ltimes 0)))
13075 (set-buffer-modified-p bmp)))
13077 (defun org-clock-display (&optional total-only)
13078 "Show subtree times in the entire buffer.
13079 If TOTAL-ONLY is non-nil, only show the total time for the entire file
13080 in the echo area."
13081 (interactive)
13082 (org-remove-clock-overlays)
13083 (let (time h m p)
13084 (org-clock-sum)
13085 (unless total-only
13086 (save-excursion
13087 (goto-char (point-min))
13088 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13089 (goto-char p)
13090 (when (setq time (get-text-property p :org-clock-minutes))
13091 (org-put-clock-overlay time (funcall outline-level))))
13092 (setq h (/ org-clock-file-total-minutes 60)
13093 m (- org-clock-file-total-minutes (* 60 h)))
13094 ;; Arrange to remove the overlays upon next change.
13095 (when org-remove-highlights-with-change
13096 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
13097 nil 'local))))
13098 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
13100 (defvar org-clock-overlays nil)
13101 (make-variable-buffer-local 'org-clock-overlays)
13103 (defun org-put-clock-overlay (time &optional level)
13104 "Put an overlays on the current line, displaying TIME.
13105 If LEVEL is given, prefix time with a corresponding number of stars.
13106 This creates a new overlay and stores it in `org-clock-overlays', so that it
13107 will be easy to remove."
13108 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
13109 (l (if level (org-get-legal-level level 0) 0))
13110 (off 0)
13111 ov tx)
13112 (move-to-column c)
13113 (unless (eolp) (skip-chars-backward "^ \t"))
13114 (skip-chars-backward " \t")
13115 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
13116 tx (concat (buffer-substring (1- (point)) (point))
13117 (make-string (+ off (max 0 (- c (current-column)))) ?.)
13118 (org-add-props (format "%s %2d:%02d%s"
13119 (make-string l ?*) h m
13120 (make-string (- 10 l) ?\ ))
13121 '(face secondary-selection))
13122 ""))
13123 (if (not (featurep 'xemacs))
13124 (org-overlay-put ov 'display tx)
13125 (org-overlay-put ov 'invisible t)
13126 (org-overlay-put ov 'end-glyph (make-glyph tx)))
13127 (push ov org-clock-overlays)))
13129 (defun org-remove-clock-overlays (&optional beg end noremove)
13130 "Remove the occur highlights from the buffer.
13131 BEG and END are ignored. If NOREMOVE is nil, remove this function
13132 from the `before-change-functions' in the current buffer."
13133 (interactive)
13134 (unless org-inhibit-highlight-removal
13135 (mapc 'org-delete-overlay org-clock-overlays)
13136 (setq org-clock-overlays nil)
13137 (unless noremove
13138 (remove-hook 'before-change-functions
13139 'org-remove-clock-overlays 'local))))
13141 (defun org-clock-out-if-current ()
13142 "Clock out if the current entry contains the running clock.
13143 This is used to stop the clock after a TODO entry is marked DONE."
13144 (when (and (member state org-done-keywords)
13145 (equal (marker-buffer org-clock-marker) (current-buffer))
13146 (< (point) org-clock-marker)
13147 (> (save-excursion (outline-next-heading) (point))
13148 org-clock-marker))
13149 ;; Clock out, but don't accept a logging message for this.
13150 (let ((org-log-done (if (and (listp org-log-done)
13151 (member 'clock-out org-log-done))
13152 '(done)
13153 org-log-done)))
13154 (org-clock-out))))
13156 (add-hook 'org-after-todo-state-change-hook
13157 'org-clock-out-if-current)
13159 (defun org-check-running-clock ()
13160 "Check if the current buffer contains the running clock.
13161 If yes, offer to stop it and to save the buffer with the changes."
13162 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
13163 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
13164 (buffer-name))))
13165 (org-clock-out)
13166 (when (y-or-n-p "Save changed buffer?")
13167 (save-buffer))))
13169 (defun org-clock-report ()
13170 "Create a table containing a report about clocked time.
13171 If the buffer contains lines
13172 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
13174 #+END: clocktable
13175 then the table will be inserted between these lines, replacing whatever
13176 is was there before. If these lines are not in the buffer, the table
13177 is inserted at point, surrounded by the special lines.
13178 The BEGIN line can contain parameters. Allowed are:
13179 :maxlevel The maximum level to be included in the table. Default is 3.
13180 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
13181 (interactive)
13182 (org-remove-clock-overlays)
13183 (unless (org-find-dblock "clocktable")
13184 (org-create-dblock (list :name "clocktable"
13185 :maxlevel 2 :emphasize nil)))
13186 (org-update-dblock))
13188 (defun org-clock-update-time-maybe ()
13189 "If this is a CLOCK line, update it and return t.
13190 Otherwise, return nil."
13191 (interactive)
13192 (save-excursion
13193 (beginning-of-line 1)
13194 (skip-chars-forward " \t")
13195 (when (looking-at org-clock-string)
13196 (let ((re (concat "[ \t]*" org-clock-string
13197 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
13198 "\\([ \t]*=>.*\\)?"))
13199 ts te h m s)
13200 (if (not (looking-at re))
13202 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
13203 (end-of-line 1)
13204 (setq ts (match-string 1)
13205 te (match-string 2))
13206 (setq s (- (time-to-seconds
13207 (apply 'encode-time (org-parse-time-string te)))
13208 (time-to-seconds
13209 (apply 'encode-time (org-parse-time-string ts))))
13210 h (floor (/ s 3600))
13211 s (- s (* 3600 h))
13212 m (floor (/ s 60))
13213 s (- s (* 60 s)))
13214 (insert " => " (format "%2d:%02d" h m))
13215 t)))))
13217 (defun org-clock-special-range (key &optional time as-strings)
13218 "Return two times bordering a special time range.
13219 Key is a symbol specifying the range and can be one of `today', `yesterday',
13220 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
13221 A week starts Monday 0:00 and ends Sunday 24:00.
13222 The range is determined relative to TIME. TIME defaults to the current time.
13223 The return value is a cons cell with two internal times like the ones
13224 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
13225 the returned times will be formatted strings."
13226 (let* ((tm (decode-time (or time (current-time))))
13227 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
13228 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
13229 (dow (nth 6 tm))
13230 s1 m1 h1 d1 month1 y1 diff ts te fm)
13231 (cond
13232 ((eq key 'today)
13233 (setq h 0 m 0 h1 24 m1 0))
13234 ((eq key 'yesterday)
13235 (setq d (1- d) h 0 m 0 h1 24 m1 0))
13236 ((eq key 'thisweek)
13237 (setq diff (if (= dow 0) 6 (1- dow))
13238 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13239 ((eq key 'lastweek)
13240 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
13241 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13242 ((eq key 'thismonth)
13243 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
13244 ((eq key 'lastmonth)
13245 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
13246 ((eq key 'thisyear)
13247 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
13248 ((eq key 'lastyear)
13249 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
13250 (t (error "No such time block %s" key)))
13251 (setq ts (encode-time s m h d month y)
13252 te (encode-time (or s1 s) (or m1 m) (or h1 h)
13253 (or d1 d) (or month1 month) (or y1 y)))
13254 (setq fm (cdr org-time-stamp-formats))
13255 (if as-strings
13256 (cons (format-time-string fm ts) (format-time-string fm te))
13257 (cons ts te))))
13259 (defun org-dblock-write:clocktable (params)
13260 "Write the standard clocktable."
13261 (let ((hlchars '((1 . "*") (2 . ?/)))
13262 (emph nil)
13263 (ins (make-marker))
13264 ipos time h m p level hlc hdl maxlevel
13265 ts te cc block)
13266 (setq maxlevel (or (plist-get params :maxlevel) 3)
13267 emph (plist-get params :emphasize)
13268 ts (plist-get params :tstart)
13269 te (plist-get params :tend)
13270 block (plist-get params :block))
13271 (when block
13272 (setq cc (org-clock-special-range block nil t)
13273 ts (car cc) te (cdr cc)))
13274 (if ts (setq ts (time-to-seconds
13275 (apply 'encode-time (org-parse-time-string ts)))))
13276 (if te (setq te (time-to-seconds
13277 (apply 'encode-time (org-parse-time-string te)))))
13278 (move-marker ins (point))
13279 (setq ipos (point))
13280 (insert-before-markers "Clock summary at ["
13281 (substring
13282 (format-time-string (cdr org-time-stamp-formats))
13283 1 -1)
13284 "]."
13285 (if block
13286 (format " Considered range is /%s/." block)
13288 "\n\n|L|Headline|Time|\n")
13289 (org-clock-sum ts te)
13290 (setq h (/ org-clock-file-total-minutes 60)
13291 m (- org-clock-file-total-minutes (* 60 h)))
13292 (insert-before-markers "|-\n|0|" "*Total file time*| "
13293 (format "*%d:%02d*" h m)
13294 "|\n")
13295 (goto-char (point-min))
13296 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13297 (goto-char p)
13298 (when (setq time (get-text-property p :org-clock-minutes))
13299 (save-excursion
13300 (beginning-of-line 1)
13301 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
13302 (setq level (- (match-end 1) (match-beginning 1)))
13303 (<= level maxlevel))
13304 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13305 hdl (match-string 2)
13306 h (/ time 60)
13307 m (- time (* 60 h)))
13308 (goto-char ins)
13309 (if (= level 1) (insert-before-markers "|-\n"))
13310 (insert-before-markers
13311 "| " (int-to-string level) "|" hlc hdl hlc " |"
13312 (make-string (1- level) ?|)
13314 (format "%d:%02d" h m)
13316 " |\n")))))
13317 (goto-char ins)
13318 (backward-delete-char 1)
13319 (goto-char ipos)
13320 (skip-chars-forward "^|")
13321 (org-table-align)))
13323 ;; FIXME: I don't think anybody uses this, ask David
13324 (defun org-collect-clock-time-entries ()
13325 "Return an internal list with clocking information.
13326 This list has one entry for each CLOCK interval.
13327 FIXME: describe the elements."
13328 (interactive)
13329 (let ((re (concat "^[ \t]*" org-clock-string
13330 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13331 rtn beg end next cont level title total closedp leafp
13332 clockpos titlepos h m donep)
13333 (save-excursion
13334 (org-clock-sum)
13335 (goto-char (point-min))
13336 (while (re-search-forward re nil t)
13337 (setq clockpos (match-beginning 0)
13338 beg (match-string 1) end (match-string 2)
13339 cont (match-end 0))
13340 (setq beg (apply 'encode-time (org-parse-time-string beg))
13341 end (apply 'encode-time (org-parse-time-string end)))
13342 (org-back-to-heading t)
13343 (setq donep (org-entry-is-done-p))
13344 (setq titlepos (point)
13345 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13346 h (/ total 60) m (- total (* 60 h))
13347 total (cons h m))
13348 (looking-at "\\(\\*+\\) +\\(.*\\)")
13349 (setq level (- (match-end 1) (match-beginning 1))
13350 title (org-match-string-no-properties 2))
13351 (save-excursion (outline-next-heading) (setq next (point)))
13352 (setq closedp (re-search-forward org-closed-time-regexp next t))
13353 (goto-char next)
13354 (setq leafp (and (looking-at "^\\*+ ")
13355 (<= (- (match-end 0) (point)) level)))
13356 (push (list beg end clockpos closedp donep
13357 total title titlepos level leafp)
13358 rtn)
13359 (goto-char cont)))
13360 (nreverse rtn)))
13362 ;;;; Agenda, and Diary Integration
13364 ;;; Define the Org-agenda-mode
13366 (defvar org-agenda-mode-map (make-sparse-keymap)
13367 "Keymap for `org-agenda-mode'.")
13369 (defvar org-agenda-menu) ; defined later in this file.
13370 (defvar org-agenda-follow-mode nil)
13371 (defvar org-agenda-show-log nil)
13372 (defvar org-agenda-redo-command nil)
13373 (defvar org-agenda-mode-hook nil)
13374 (defvar org-agenda-type nil)
13375 (defvar org-agenda-force-single-file nil)
13377 (defun org-agenda-mode ()
13378 "Mode for time-sorted view on action items in Org-mode files.
13380 The following commands are available:
13382 \\{org-agenda-mode-map}"
13383 (interactive)
13384 (kill-all-local-variables)
13385 (setq org-agenda-undo-list nil
13386 org-agenda-pending-undo-list nil)
13387 (setq major-mode 'org-agenda-mode)
13388 (setq mode-name "Org-Agenda")
13389 (use-local-map org-agenda-mode-map)
13390 (easy-menu-add org-agenda-menu)
13391 (if org-startup-truncated (setq truncate-lines t))
13392 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
13393 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
13394 ;; Make sure properties are removed when copying text
13395 (when (boundp 'buffer-substring-filters)
13396 (org-set-local 'buffer-substring-filters
13397 (cons (lambda (x)
13398 (set-text-properties 0 (length x) nil x) x)
13399 buffer-substring-filters)))
13400 (unless org-agenda-keep-modes
13401 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
13402 org-agenda-show-log nil))
13403 (easy-menu-change
13404 '("Agenda") "Agenda Files"
13405 (append
13406 (list
13407 (vector
13408 (if (get 'org-agenda-files 'org-restrict)
13409 "Restricted to single file"
13410 "Edit File List")
13411 '(org-edit-agenda-file-list)
13412 (not (get 'org-agenda-files 'org-restrict)))
13413 "--")
13414 (mapcar 'org-file-menu-entry (org-agenda-files))))
13415 (org-agenda-set-mode-name)
13416 (apply
13417 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
13418 (list 'org-agenda-mode-hook)))
13420 (substitute-key-definition 'undo 'org-agenda-undo
13421 org-agenda-mode-map global-map)
13422 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
13423 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
13424 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
13425 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
13426 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
13427 (define-key org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
13428 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
13429 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
13430 (define-key org-agenda-mode-map " " 'org-agenda-show)
13431 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
13432 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
13433 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
13434 (define-key org-agenda-mode-map "o" 'delete-other-windows)
13435 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
13436 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
13437 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
13438 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
13439 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
13440 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
13441 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
13442 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
13443 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
13444 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13445 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13447 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
13448 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13449 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13450 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
13451 (while l (define-key org-agenda-mode-map
13452 (int-to-string (pop l)) 'digit-argument)))
13454 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
13455 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
13456 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13457 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13458 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
13459 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
13460 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
13461 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
13462 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
13463 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
13464 (define-key org-agenda-mode-map "n" 'next-line)
13465 (define-key org-agenda-mode-map "p" 'previous-line)
13466 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13467 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13468 (define-key org-agenda-mode-map "," 'org-agenda-priority)
13469 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
13470 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
13471 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13472 (eval-after-load "calendar"
13473 '(define-key calendar-mode-map org-calendar-to-agenda-key
13474 'org-calendar-goto-agenda))
13475 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
13476 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13477 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13478 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13479 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
13480 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
13481 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
13482 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
13483 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
13484 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13485 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
13486 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
13487 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
13488 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13489 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13490 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
13491 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
13492 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13493 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13494 "Local keymap for agenda entries from Org-mode.")
13496 (define-key org-agenda-keymap
13497 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13498 (define-key org-agenda-keymap
13499 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13500 (when org-agenda-mouse-1-follows-link
13501 (define-key org-agenda-keymap [follow-link] 'mouse-face))
13502 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13503 '("Agenda"
13504 ("Agenda Files")
13505 "--"
13506 ["Show" org-agenda-show t]
13507 ["Go To (other window)" org-agenda-goto t]
13508 ["Go To (this window)" org-agenda-switch-to t]
13509 ["Follow Mode" org-agenda-follow-mode
13510 :style toggle :selected org-agenda-follow-mode :active t]
13511 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13512 "--"
13513 ["Cycle TODO" org-agenda-todo t]
13514 ["Archive subtree" org-agenda-archive t]
13515 ["Delete subtree" org-agenda-kill t]
13516 "--"
13517 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13518 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13519 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13520 "--"
13521 ("Tags"
13522 ["Show all Tags" org-agenda-show-tags t]
13523 ["Set Tags" org-agenda-set-tags t])
13524 ("Date/Schedule"
13525 ["Schedule" org-agenda-schedule t]
13526 ["Set Deadline" org-agenda-deadline t]
13527 "--"
13528 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13529 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13530 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13531 ("Priority"
13532 ["Set Priority" org-agenda-priority t]
13533 ["Increase Priority" org-agenda-priority-up t]
13534 ["Decrease Priority" org-agenda-priority-down t]
13535 ["Show Priority" org-agenda-show-priority t])
13536 ("Calendar/Diary"
13537 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13538 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13539 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13540 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13541 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13542 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13543 "--"
13544 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13545 "--"
13546 ("View"
13547 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13548 :style radio :selected (equal org-agenda-ndays 1)]
13549 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13550 :style radio :selected (equal org-agenda-ndays 7)]
13551 "--"
13552 ["Show Logbook entries" org-agenda-log-mode
13553 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13554 ["Include Diary" org-agenda-toggle-diary
13555 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13556 ["Use Time Grid" org-agenda-toggle-time-grid
13557 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13558 ["Rebuild buffer" org-agenda-redo t]
13559 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13560 "--"
13561 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13562 "--"
13563 ["Quit" org-agenda-quit t]
13564 ["Exit and Release Buffers" org-agenda-exit t]
13567 ;;; Agenda undo
13569 (defvar org-agenda-allow-remote-undo t
13570 "Non-nil means, allow remote undo from the agenda buffer.")
13571 (defvar org-agenda-undo-list nil
13572 "List of undoable operations in the agenda since last refresh.")
13573 (defvar org-agenda-undo-has-started-in nil
13574 "Buffers that have already seen `undo-start' in the current undo sequence.")
13575 (defvar org-agenda-pending-undo-list nil
13576 "In a series of undo commands, this is the list of remaning undo items.")
13578 (defmacro org-if-unprotected (&rest body)
13579 "Execute BODY if ther is no `org-protected' text property at point."
13580 (declare (debug t))
13581 `(unless (get-text-property (point) 'org-protected)
13582 ,@body))
13584 (defmacro org-with-remote-undo (_buffer &rest _body)
13585 "Execute BODY while recording undo information in two buffers."
13586 (declare (indent 1) (debug t))
13587 `(let ((_cline (org-current-line))
13588 (_cmd this-command)
13589 (_buf1 (current-buffer))
13590 (_buf2 ,_buffer)
13591 (_undo1 buffer-undo-list)
13592 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13593 _c1 _c2)
13594 ,@_body
13595 (when org-agenda-allow-remote-undo
13596 (setq _c1 (org-verify-change-for-undo
13597 _undo1 (with-current-buffer _buf1 buffer-undo-list))
13598 _c2 (org-verify-change-for-undo
13599 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13600 (when (or _c1 _c2)
13601 ;; make sure there are undo boundaries
13602 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13603 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13604 ;; remember which buffer to undo
13605 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13606 org-agenda-undo-list)))))
13608 (defun org-agenda-undo ()
13609 "Undo a remote editing step in the agenda.
13610 This undoes changes both in the agenda buffer and in the remote buffer
13611 that have been changed along."
13612 (interactive)
13613 (or org-agenda-allow-remote-undo
13614 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13615 (if (not (eq this-command last-command))
13616 (setq org-agenda-undo-has-started-in nil
13617 org-agenda-pending-undo-list org-agenda-undo-list))
13618 (if (not org-agenda-pending-undo-list)
13619 (error "No further undo information"))
13620 (let* ((entry (pop org-agenda-pending-undo-list))
13621 buf line cmd rembuf)
13622 (setq cmd (pop entry) line (pop entry))
13623 (setq rembuf (nth 2 entry))
13624 (org-with-remote-undo rembuf
13625 (while (bufferp (setq buf (pop entry)))
13626 (if (pop entry)
13627 (with-current-buffer buf
13628 (let ((last-undo-buffer buf)
13629 buffer-read-only)
13630 (unless (memq buf org-agenda-undo-has-started-in)
13631 (push buf org-agenda-undo-has-started-in)
13632 (make-local-variable 'pending-undo-list)
13633 (undo-start))
13634 (while (and pending-undo-list
13635 (listp pending-undo-list)
13636 (not (car pending-undo-list)))
13637 (pop pending-undo-list))
13638 (undo-more 1))))))
13639 (goto-line line)
13640 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13642 (defun org-verify-change-for-undo (l1 l2)
13643 "Verify that a real change occurred between the undo lists L1 and L2."
13644 (while (and l1 (listp l1) (null (car l1))) (pop l1))
13645 (while (and l2 (listp l2) (null (car l2))) (pop l2))
13646 (not (eq l1 l2)))
13648 ;;; Agenda dispatch
13650 (defvar org-agenda-restrict nil)
13651 (defvar org-agenda-restrict-begin (make-marker))
13652 (defvar org-agenda-restrict-end (make-marker))
13653 (defvar org-agenda-last-dispatch-buffer nil)
13655 ;;;###autoload
13656 (defun org-agenda (arg)
13657 "Dispatch agenda commands to collect entries to the agenda buffer.
13658 Prompts for a character to select a command. Any prefix arg will be passed
13659 on to the selected command. The default selections are:
13661 a Call `org-agenda-list' to display the agenda for current day or week.
13662 t Call `org-todo-list' to display the global todo list.
13663 T Call `org-todo-list' to display the global todo list, select only
13664 entries with a specific TODO keyword (the user gets a prompt).
13665 m Call `org-tags-view' to display headlines with tags matching
13666 a condition (the user is prompted for the condition).
13667 M Like `m', but select only TODO entries, no ordinary headlines.
13668 l Create a timeeline for the current buffer.
13670 More commands can be added by configuring the variable
13671 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
13672 searches can be pre-defined in this way.
13674 If the current buffer is in Org-mode and visiting a file, you can also
13675 first press `1' to indicate that the agenda should be temporarily (until the
13676 next use of \\[org-agenda]) restricted to the current file."
13677 (interactive "P")
13678 (catch 'exit
13679 (let* ((buf (current-buffer))
13680 (bfn (buffer-file-name (buffer-base-buffer)))
13681 (restrict-ok (and bfn (org-mode-p)))
13682 (custom org-agenda-custom-commands)
13683 c entry key type match lprops)
13684 ;; Turn off restriction
13685 (put 'org-agenda-files 'org-restrict nil)
13686 (setq org-agenda-restrict nil)
13687 (move-marker org-agenda-restrict-begin nil)
13688 (move-marker org-agenda-restrict-end nil)
13689 ;; Remember where this call originated
13690 (setq org-agenda-last-dispatch-buffer (current-buffer))
13691 (save-window-excursion
13692 (delete-other-windows)
13693 (switch-to-buffer-other-window " *Agenda Commands*")
13694 (erase-buffer)
13695 (insert (eval-when-compile
13696 (let ((header
13697 "Press key for an agenda command:
13698 -------------------------------- C Configure custom agenda commands
13699 a Agenda for current week or day
13700 t List of all TODO entries T Entries with special TODO kwd
13701 m Match a TAGS query M Like m, but only TODO entries
13702 L Timeline for current buffer # List stuck projects (!=configure)
13704 (start 0))
13705 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13706 (setq start (match-end 0))
13707 (add-text-properties (match-beginning 2) (match-end 2)
13708 '(face bold) header))
13709 header)))
13710 (while (setq entry (pop custom))
13711 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13712 (insert (format "\n%-4s%-14s: %s"
13713 (org-add-props (copy-sequence key)
13714 '(face bold))
13715 (cond
13716 ((stringp type) type)
13717 ((eq type 'todo) "TODO keyword")
13718 ((eq type 'tags) "Tags query")
13719 ((eq type 'tags-todo) "Tags (TODO)")
13720 ((eq type 'tags-tree) "Tags tree")
13721 ((eq type 'todo-tree) "TODO kwd tree")
13722 ((eq type 'occur-tree) "Occur tree")
13723 ((functionp type) (symbol-name type))
13724 (t "???"))
13725 (if (stringp match)
13726 (org-add-props match nil 'face 'org-warning)
13727 (format "set of %d commands" (length match))))))
13728 (if restrict-ok
13729 (insert "\n"
13730 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
13731 (goto-char (point-min))
13732 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13733 (message "Press key for agenda command%s"
13734 (if restrict-ok ", or [1] or [0] to restrict" ""))
13735 (setq c (read-char-exclusive))
13736 (message "")
13737 (when (memq c '(?L ?1 ?0))
13738 (if restrict-ok
13739 (put 'org-agenda-files 'org-restrict (list bfn))
13740 (error "Cannot restrict agenda to current buffer"))
13741 (with-current-buffer " *Agenda Commands*"
13742 (goto-char (point-max))
13743 (delete-region (point-at-bol) (point))
13744 (goto-char (point-min)))
13745 (when (eq c ?0)
13746 (setq org-agenda-restrict t)
13747 (with-current-buffer buf
13748 (if (org-region-active-p)
13749 (progn
13750 (move-marker org-agenda-restrict-begin (region-beginning))
13751 (move-marker org-agenda-restrict-end (region-end)))
13752 (save-excursion
13753 (org-back-to-heading t)
13754 (move-marker org-agenda-restrict-begin (point))
13755 (move-marker org-agenda-restrict-end
13756 (progn (org-end-of-subtree t)))))))
13757 (unless (eq c ?L)
13758 (message "Press key for agenda command%s"
13759 (if restrict-ok " (restricted to current file)" ""))
13760 (setq c (read-char-exclusive)))
13761 (message "")))
13762 (require 'calendar) ; FIXME: can we avoid this for some commands?
13763 ;; For example the todo list should not need it (but does...)
13764 (cond
13765 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13766 (if (symbolp (nth 1 entry))
13767 (progn
13768 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13769 lprops (nth 3 entry))
13770 (cond
13771 ((eq type 'tags)
13772 (org-let lprops '(org-tags-view current-prefix-arg match)))
13773 ((eq type 'tags-todo)
13774 (org-let lprops '(org-tags-view '(4) match)))
13775 ((eq type 'todo)
13776 (org-let lprops '(org-todo-list match)))
13777 ((eq type 'tags-tree)
13778 (org-check-for-org-mode)
13779 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13780 ((eq type 'todo-tree)
13781 (org-check-for-org-mode)
13782 (org-let lprops
13783 '(org-occur (concat "^" outline-regexp "[ \t]*"
13784 (regexp-quote match) "\\>"))))
13785 ((eq type 'occur-tree)
13786 (org-check-for-org-mode)
13787 (org-let lprops '(org-occur match)))
13788 ((fboundp type)
13789 (org-let lprops '(funcall type match)))
13790 (t (error "Invalid custom agenda command type %s" type))))
13791 (org-run-agenda-series (cddr entry))))
13792 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13793 ((equal c ?a) (call-interactively 'org-agenda-list))
13794 ((equal c ?t) (call-interactively 'org-todo-list))
13795 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13796 ((equal c ?m) (call-interactively 'org-tags-view))
13797 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13798 ((equal c ?L)
13799 (unless restrict-ok
13800 (error "This is not an Org-mode file"))
13801 (org-call-with-arg 'org-timeline arg))
13802 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13803 ((equal c ?!) (customize-variable 'org-stuck-projects))
13804 (t (error "Invalid key"))))))
13806 (defun org-run-agenda-series (series)
13807 (org-prepare-agenda)
13808 (let* ((org-agenda-multi t)
13809 (redo (list 'org-run-agenda-series (list 'quote series)))
13810 (cmds (car series))
13811 (gprops (nth 1 series))
13812 match ;; The byte compiler incorrectly complains about this. Keep it!
13813 cmd type lprops)
13814 (while (setq cmd (pop cmds))
13815 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
13816 (cond
13817 ((eq type 'agenda)
13818 (call-interactively 'org-agenda-list))
13819 ((eq type 'alltodo)
13820 (call-interactively 'org-todo-list))
13821 ((eq type 'stuck)
13822 (call-interactively 'org-agenda-list-stuck-projects))
13823 ((eq type 'tags)
13824 (org-let2 gprops lprops
13825 '(org-tags-view current-prefix-arg match)))
13826 ((eq type 'tags-todo)
13827 (org-let2 gprops lprops
13828 '(org-tags-view '(4) match)))
13829 ((eq type 'todo)
13830 (org-let2 gprops lprops
13831 '(org-todo-list match)))
13832 ((fboundp type)
13833 (org-let2 gprops lprops
13834 '(funcall type match)))
13835 (t (error "Invalid type in command series"))))
13836 (widen)
13837 (setq org-agenda-redo-command redo)
13838 (goto-char (point-min)))
13839 (org-finalize-agenda))
13841 ;;;###autoload
13842 (defmacro org-batch-agenda (cmd-key &rest parameters)
13843 "Run an agenda command in batch mode, send result to STDOUT.
13844 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
13845 Paramters are alternating variable names and values that will be bound
13846 before running the agenda command."
13847 (let (pars)
13848 (while parameters
13849 (push (list (pop parameters) (if parameters (pop parameters))) pars))
13850 (flet ((read-char-exclusive () (string-to-char cmd-key)))
13851 (eval (list 'let (nreverse pars) '(org-agenda nil))))
13852 (set-buffer "*Org Agenda*")
13853 (princ (buffer-string))))
13855 (defmacro org-no-read-only (&rest body)
13856 "Inhibit read-only for BODY."
13857 `(let ((inhibit-read-only t)) ,@body))
13859 (defun org-check-for-org-mode ()
13860 "Make sure current buffer is in org-mode. Error if not."
13861 (or (org-mode-p)
13862 (error "Cannot execute org-mode agenda command on buffer in %s."
13863 major-mode)))
13865 (defun org-fit-agenda-window ()
13866 "Fit the window to the buffer size."
13867 (and (memq org-agenda-window-setup '(reorganize-frame))
13868 (fboundp 'fit-window-to-buffer)
13869 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
13870 (/ (frame-height) 2))))
13872 ;;; Agenda file list
13874 (defun org-agenda-files (&optional unrestricted)
13875 "Get the list of agenda files.
13876 Optional UNRESTRICTED means return the full list even if a restriction
13877 is currently in place."
13878 (cond
13879 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13880 ((stringp org-agenda-files) (org-read-agenda-file-list))
13881 ((listp org-agenda-files) org-agenda-files)
13882 (t (error "Invalid value of `org-agenda-files'"))))
13884 (defun org-edit-agenda-file-list ()
13885 "Edit the list of agenda files.
13886 Depending on setup, this either uses customize to edit the variable
13887 `org-agenda-files', or it visits the file that is holding the list. In the
13888 latter case, the buffer is set up in a way that saving it automatically kills
13889 the buffer and restores the previous window configuration."
13890 (interactive)
13891 (if (stringp org-agenda-files)
13892 (let ((cw (current-window-configuration)))
13893 (find-file org-agenda-files)
13894 (org-set-local 'org-window-configuration cw)
13895 (org-add-hook 'after-save-hook
13896 (lambda ()
13897 (set-window-configuration
13898 (prog1 org-window-configuration
13899 (kill-buffer (current-buffer))))
13900 (org-install-agenda-files-menu)
13901 (message "New agenda file list installed"))
13902 nil 'local)
13903 (message (substitute-command-keys
13904 "Edit list and finish with \\[save-buffer]")))
13905 (customize-variable 'org-agenda-files)))
13907 (defun org-store-new-agenda-file-list (list)
13908 "Set new value for the agenda file list and save it correcly."
13909 (if (stringp org-agenda-files)
13910 (let ((f org-agenda-files) b)
13911 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13912 (with-temp-file f
13913 (insert (mapconcat 'identity list "\n") "\n")))
13914 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13915 (setq org-agenda-files list)
13916 (customize-save-variable 'org-agenda-files org-agenda-files))))
13918 (defun org-read-agenda-file-list ()
13919 "Read the list of agenda files from a file."
13920 (when (stringp org-agenda-files)
13921 (with-temp-buffer
13922 (insert-file-contents org-agenda-files)
13923 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13926 ;;;###autoload
13927 (defun org-cycle-agenda-files ()
13928 "Cycle through the files in `org-agenda-files'.
13929 If the current buffer visits an agenda file, find the next one in the list.
13930 If the current buffer does not, find the first agenda file."
13931 (interactive)
13932 (let* ((fs (org-agenda-files t))
13933 (files (append fs (list (car fs))))
13934 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13935 file)
13936 (unless files (error "No agenda files"))
13937 (catch 'exit
13938 (while (setq file (pop files))
13939 (if (equal (file-truename file) tcf)
13940 (when (car files)
13941 (find-file (car files))
13942 (throw 'exit t))))
13943 (find-file (car fs)))
13944 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13946 (defun org-agenda-file-to-front (&optional to-end)
13947 "Move/add the current file to the top of the agenda file list.
13948 If the file is not present in the list, it is added to the front. If it is
13949 present, it is moved there. With optional argument TO-END, add/move to the
13950 end of the list."
13951 (interactive "P")
13952 (let ((file-alist (mapcar (lambda (x)
13953 (cons (file-truename x) x))
13954 (org-agenda-files t)))
13955 (ctf (file-truename buffer-file-name))
13956 x had)
13957 (setq x (assoc ctf file-alist) had x)
13959 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13960 (if to-end
13961 (setq file-alist (append (delq x file-alist) (list x)))
13962 (setq file-alist (cons x (delq x file-alist))))
13963 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13964 (org-install-agenda-files-menu)
13965 (message "File %s to %s of agenda file list"
13966 (if had "moved" "added") (if to-end "end" "front"))))
13968 (defun org-remove-file (&optional file)
13969 "Remove current file from the list of files in variable `org-agenda-files'.
13970 These are the files which are being checked for agenda entries.
13971 Optional argument FILE means, use this file instead of the current."
13972 (interactive)
13973 (let* ((file (or file buffer-file-name))
13974 (true-file (file-truename file))
13975 (afile (abbreviate-file-name file))
13976 (files (delq nil (mapcar
13977 (lambda (x)
13978 (if (equal true-file
13979 (file-truename x))
13980 nil x))
13981 (org-agenda-files t)))))
13982 (if (not (= (length files) (length (org-agenda-files t))))
13983 (progn
13984 (org-store-new-agenda-file-list files)
13985 (org-install-agenda-files-menu)
13986 (message "Removed file: %s" afile))
13987 (message "File was not in list: %s" afile))))
13989 (defun org-file-menu-entry (file)
13990 (vector file (list 'find-file file) t))
13992 (defun org-check-agenda-file (file)
13993 "Make sure FILE exists. If not, ask user what to do."
13994 (when (not (file-exists-p file))
13995 (message "non-existent file %s. [R]emove from list or [A]bort?"
13996 (abbreviate-file-name file))
13997 (let ((r (downcase (read-char-exclusive))))
13998 (cond
13999 ((equal r ?r)
14000 (org-remove-file file)
14001 (throw 'nextfile t))
14002 (t (error "Abort"))))))
14004 ;;; Agenda prepare and finalize
14006 (defvar org-agenda-multi nil) ; dynammically scoped
14007 (defvar org-agenda-buffer-name "*Org Agenda*")
14008 (defvar org-pre-agenda-window-conf nil)
14009 (defun org-prepare-agenda ()
14010 (if org-agenda-multi
14011 (progn
14012 (setq buffer-read-only nil)
14013 (goto-char (point-max))
14014 (unless (= (point) 1)
14015 (insert "\n" (make-string (window-width) ?=) "\n"))
14016 (narrow-to-region (point) (point-max)))
14017 (org-agenda-maybe-reset-markers 'force)
14018 (org-prepare-agenda-buffers (org-agenda-files))
14019 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
14020 (awin (get-buffer-window abuf)))
14021 (cond
14022 ((equal (current-buffer) abuf) nil)
14023 (awin (select-window awin))
14024 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
14025 ((equal org-agenda-window-setup 'current-window)
14026 (switch-to-buffer abuf))
14027 ((equal org-agenda-window-setup 'other-window)
14028 (switch-to-buffer-other-window abuf))
14029 ((equal org-agenda-window-setup 'other-frame)
14030 (switch-to-buffer-other-frame abuf))
14031 ((equal org-agenda-window-setup 'reorganize-frame)
14032 (delete-other-windows)
14033 (switch-to-buffer-other-window abuf))))
14034 (setq buffer-read-only nil)
14035 (erase-buffer)
14036 (org-agenda-mode))
14037 (setq buffer-read-only nil))
14039 (defun org-finalize-agenda ()
14040 "Finishing touch for the agenda buffer, called just before displaying it."
14041 (unless org-agenda-multi
14042 (org-agenda-align-tags)
14043 (save-excursion
14044 (let ((buffer-read-only))
14045 (goto-char (point-min))
14046 (while (org-activate-bracket-links (point-max))
14047 (add-text-properties (match-beginning 0) (match-end 0)
14048 '(face org-link))))
14049 (run-hooks 'org-finalize-agenda-hook))))
14051 (defun org-prepare-agenda-buffers (files)
14052 "Create buffers for all agenda files, protect archived trees and comments."
14053 (interactive)
14054 (let ((pa '(:org-archived t))
14055 (pc '(:org-comment t))
14056 (pall '(:org-archived t :org-comment t))
14057 (rea (concat ":" org-archive-tag ":"))
14058 bmp file re)
14059 (save-excursion
14060 (save-restriction
14061 (while (setq file (pop files))
14062 (org-check-agenda-file file)
14063 (set-buffer (org-get-agenda-file-buffer file))
14064 (widen)
14065 (setq bmp (buffer-modified-p))
14066 (save-excursion
14067 (remove-text-properties (point-min) (point-max) pall)
14068 (when org-agenda-skip-archived-trees
14069 (goto-char (point-min))
14070 (while (re-search-forward rea nil t)
14071 (if (org-on-heading-p t)
14072 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14073 (goto-char (point-min))
14074 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14075 (while (re-search-forward re nil t)
14076 (add-text-properties
14077 (match-beginning 0) (org-end-of-subtree t) pc)))
14078 (set-buffer-modified-p bmp))))))
14080 (defvar org-agenda-skip-function nil
14081 "Function to be called at each match during agenda construction.
14082 If this function return nil, the current match should not be skipped.
14083 Otherwise, the function must return a position from where the search
14084 should be continued.
14085 Never set this variable using `setq' or so, because then it will apply
14086 to all future agenda commands. Instead, bind it with `let' to scope
14087 it dynamically into the agenda-constructing command.")
14089 (defun org-agenda-skip ()
14090 "Throw to `:skip' in places that should be skipped.
14091 Also moves point to the end of the skipped region, so that search can
14092 continue from there."
14093 (let ((p (point-at-bol)) to)
14094 (and org-agenda-skip-archived-trees
14095 (get-text-property p :org-archived)
14096 (org-end-of-subtree t)
14097 (throw :skip t))
14098 (and (get-text-property p :org-comment)
14099 (org-end-of-subtree t)
14100 (throw :skip t))
14101 (if (equal (char-after p) ?#) (throw :skip t))
14102 (when (and (functionp org-agenda-skip-function)
14103 (setq to (save-excursion
14104 (save-match-data
14105 (funcall org-agenda-skip-function)))))
14106 (goto-char to)
14107 (throw :skip t))))
14109 (defvar org-agenda-markers nil
14110 "List of all currently active markers created by `org-agenda'.")
14111 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
14112 "Creation time of the last agenda marker.")
14114 (defun org-agenda-new-marker (&optional pos)
14115 "Return a new agenda marker.
14116 Org-mode keeps a list of these markers and resets them when they are
14117 no longer in use."
14118 (let ((m (copy-marker (or pos (point)))))
14119 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
14120 (push m org-agenda-markers)
14123 (defun org-agenda-maybe-reset-markers (&optional force)
14124 "Reset markers created by `org-agenda'. But only if they are old enough."
14125 (if (or (and force (not org-agenda-multi))
14126 (> (- (time-to-seconds (current-time))
14127 org-agenda-last-marker-time)
14129 (while org-agenda-markers
14130 (move-marker (pop org-agenda-markers) nil))))
14132 (defvar org-agenda-new-buffers nil
14133 "Buffers created to visit agenda files.")
14135 (defun org-get-agenda-file-buffer (file)
14136 "Get a buffer visiting FILE. If the buffer needs to be created, add
14137 it to the list of buffers which might be released later."
14138 (let ((buf (org-find-base-buffer-visiting file)))
14139 (if buf
14140 buf ; just return it
14141 ;; Make a new buffer and remember it
14142 (setq buf (find-file-noselect file))
14143 (if buf (push buf org-agenda-new-buffers))
14144 buf)))
14146 (defun org-release-buffers (blist)
14147 "Release all buffers in list, asking the user for confirmation when needed.
14148 When a buffer is unmodified, it is just killed. When modified, it is saved
14149 \(if the user agrees) and then killed."
14150 (let (buf file)
14151 (while (setq buf (pop blist))
14152 (setq file (buffer-file-name buf))
14153 (when (and (buffer-modified-p buf)
14154 file
14155 (y-or-n-p (format "Save file %s? " file)))
14156 (with-current-buffer buf (save-buffer)))
14157 (kill-buffer buf))))
14159 (defvar org-category-table nil)
14160 (defun org-get-category-table ()
14161 "Get the table of categories and positions in current buffer."
14162 (let (tbl)
14163 (save-excursion
14164 (goto-char (point-min))
14165 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
14166 (push (cons (point) (org-trim (match-string 2))) tbl)))
14167 tbl))
14169 (defun org-get-category (&optional pos)
14170 "Get the category applying to position POS."
14171 (if (not org-category-table)
14172 (cond
14173 ((null org-category)
14174 (setq org-category
14175 (if buffer-file-name
14176 (file-name-sans-extension
14177 (file-name-nondirectory buffer-file-name))
14178 "???")))
14179 ((symbolp org-category) (symbol-name org-category))
14180 (t org-category))
14181 (let ((tbl org-category-table)
14182 (pos (or pos (point))))
14183 (while (and tbl (> (caar tbl) pos))
14184 (pop tbl))
14185 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
14186 org-category-table))))))
14187 ;;; Agenda timeline
14189 (defun org-timeline (&optional include-all)
14190 "Show a time-sorted view of the entries in the current org file.
14191 Only entries with a time stamp of today or later will be listed. With
14192 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
14193 under the current date.
14194 If the buffer contains an active region, only check the region for
14195 dates."
14196 (interactive "P")
14197 (require 'calendar)
14198 (org-compile-prefix-format 'timeline)
14199 (org-set-sorting-strategy 'timeline)
14200 (let* ((dopast t)
14201 (dotodo include-all)
14202 (doclosed org-agenda-show-log)
14203 (entry buffer-file-name)
14204 (date (calendar-current-date))
14205 (beg (if (org-region-active-p) (region-beginning) (point-min)))
14206 (end (if (org-region-active-p) (region-end) (point-max)))
14207 (day-numbers (org-get-all-dates beg end 'no-ranges
14208 t doclosed ; always include today
14209 org-timeline-show-empty-dates))
14210 (today (time-to-days (current-time)))
14211 (past t)
14212 args
14213 s e rtn d emptyp)
14214 (setq org-agenda-redo-command
14215 (list 'progn
14216 (list 'switch-to-buffer-other-window (current-buffer))
14217 (list 'org-timeline (list 'quote include-all))))
14218 (if (not dopast)
14219 ;; Remove past dates from the list of dates.
14220 (setq day-numbers (delq nil (mapcar (lambda(x)
14221 (if (>= x today) x nil))
14222 day-numbers))))
14223 (org-prepare-agenda)
14224 (if doclosed (push :closed args))
14225 (push :timestamp args)
14226 (if dotodo (push :todo args))
14227 (while (setq d (pop day-numbers))
14228 (if (and (listp d) (eq (car d) :omitted))
14229 (progn
14230 (setq s (point))
14231 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
14232 (put-text-property s (1- (point)) 'face 'org-level-3))
14233 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
14234 (if (and (>= d today)
14235 dopast
14236 past)
14237 (progn
14238 (setq past nil)
14239 (insert (make-string 79 ?-) "\n")))
14240 (setq date (calendar-gregorian-from-absolute d))
14241 (setq s (point))
14242 (setq rtn (and (not emptyp)
14243 (apply 'org-agenda-get-day-entries
14244 entry date args)))
14245 (if (or rtn (equal d today) org-timeline-show-empty-dates)
14246 (progn
14247 (insert (calendar-day-name date) " "
14248 (number-to-string (extract-calendar-day date)) " "
14249 (calendar-month-name (extract-calendar-month date)) " "
14250 (number-to-string (extract-calendar-year date)) "\n")
14251 ; FIXME: this gives a timezone problem
14252 ; (insert (format-time-string org-agenda-date-format
14253 ; (calendar-time-from-absolute d 0))
14254 ; "\n")
14255 (put-text-property s (1- (point)) 'face 'org-level-3)
14256 (put-text-property s (1- (point)) 'org-date-line t)
14257 (if (equal d today)
14258 (put-text-property s (1- (point)) 'org-today t))
14259 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
14260 (put-text-property s (1- (point)) 'day d)))))
14261 (goto-char (point-min))
14262 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
14263 (point-min)))
14264 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
14265 (org-finalize-agenda)
14266 (setq buffer-read-only t)))
14268 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
14269 "Return a list of all relevant day numbers from BEG to END buffer positions.
14270 If NO-RANGES is non-nil, include only the start and end dates of a range,
14271 not every single day in the range. If FORCE-TODAY is non-nil, make
14272 sure that TODAY is included in the list. If INACTIVE is non-nil, also
14273 inactive time stamps (those in square brackets) are included.
14274 When EMPTY is non-nil, also include days without any entries."
14275 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
14276 dates dates1 date day day1 day2 ts1 ts2)
14277 (if force-today
14278 (setq dates (list (time-to-days (current-time)))))
14279 (save-excursion
14280 (goto-char beg)
14281 (while (re-search-forward re end t)
14282 (setq day (time-to-days (org-time-string-to-time
14283 (substring (match-string 1) 0 10))))
14284 (or (memq day dates) (push day dates)))
14285 (unless no-ranges
14286 (goto-char beg)
14287 (while (re-search-forward org-tr-regexp end t)
14288 (setq ts1 (substring (match-string 1) 0 10)
14289 ts2 (substring (match-string 2) 0 10)
14290 day1 (time-to-days (org-time-string-to-time ts1))
14291 day2 (time-to-days (org-time-string-to-time ts2)))
14292 (while (< (setq day1 (1+ day1)) day2)
14293 (or (memq day1 dates) (push day1 dates)))))
14294 (setq dates (sort dates '<))
14295 (when empty
14296 (while (setq day (pop dates))
14297 (setq day2 (car dates))
14298 (push day dates1)
14299 (when (and day2 empty)
14300 (if (or (eq empty t)
14301 (and (numberp empty) (<= (- day2 day) empty)))
14302 (while (< (setq day (1+ day)) day2)
14303 (push (list day) dates1))
14304 (push (cons :omitted (- day2 day)) dates1))))
14305 (setq dates (nreverse dates1)))
14306 dates)))
14308 ;;; Agenda Daily/Weekly
14310 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
14311 (defvar org-agenda-last-arguments nil
14312 "The arguments of the previous call to org-agenda")
14313 (defvar org-starting-day nil) ; local variable in the agenda buffer
14314 (defvar org-include-all-loc nil) ; local variable
14317 ;;;###autoload
14318 (defun org-agenda-list (&optional include-all start-day ndays)
14319 "Produce a weekly view from all files in variable `org-agenda-files'.
14320 The view will be for the current week, but from the overview buffer you
14321 will be able to go to other weeks.
14322 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
14323 also be shown, under the current date.
14324 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
14325 on the days are also shown. See the variable `org-log-done' for how
14326 to turn on logging.
14327 START-DAY defaults to TODAY, or to the most recent match for the weekday
14328 given in `org-agenda-start-on-weekday'.
14329 NDAYS defaults to `org-agenda-ndays'."
14330 (interactive "P")
14331 (if org-agenda-overriding-arguments
14332 (setq include-all (car org-agenda-overriding-arguments)
14333 start-day (nth 1 org-agenda-overriding-arguments)
14334 ndays (nth 2 org-agenda-overriding-arguments)))
14335 (setq org-agenda-last-arguments (list include-all start-day ndays))
14336 (org-compile-prefix-format 'agenda)
14337 (org-set-sorting-strategy 'agenda)
14338 (require 'calendar)
14339 (let* ((org-agenda-start-on-weekday
14340 (if (or (equal ndays 1)
14341 (and (null ndays) (equal 1 org-agenda-ndays)))
14342 nil org-agenda-start-on-weekday))
14343 (thefiles (org-agenda-files))
14344 (files thefiles)
14345 (today (time-to-days (current-time)))
14346 (sd (or start-day today))
14347 (start (if (or (null org-agenda-start-on-weekday)
14348 (< org-agenda-ndays 7))
14350 (let* ((nt (calendar-day-of-week
14351 (calendar-gregorian-from-absolute sd)))
14352 (n1 org-agenda-start-on-weekday)
14353 (d (- nt n1)))
14354 (- sd (+ (if (< d 0) 7 0) d)))))
14355 (day-numbers (list start))
14356 (inhibit-redisplay (not debug-on-error))
14357 s e rtn rtnall file date d start-pos end-pos todayp nd)
14358 (setq org-agenda-redo-command
14359 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
14360 ;; Make the list of days
14361 (setq ndays (or ndays org-agenda-ndays)
14362 nd ndays)
14363 (while (> ndays 1)
14364 (push (1+ (car day-numbers)) day-numbers)
14365 (setq ndays (1- ndays)))
14366 (setq day-numbers (nreverse day-numbers))
14367 (org-prepare-agenda)
14368 (org-set-local 'org-starting-day (car day-numbers))
14369 (org-set-local 'org-include-all-loc include-all)
14370 (when (and (or include-all org-agenda-include-all-todo)
14371 (member today day-numbers))
14372 (setq files thefiles
14373 rtnall nil)
14374 (while (setq file (pop files))
14375 (catch 'nextfile
14376 (org-check-agenda-file file)
14377 (setq date (calendar-gregorian-from-absolute today)
14378 rtn (org-agenda-get-day-entries
14379 file date :todo))
14380 (setq rtnall (append rtnall rtn))))
14381 (when rtnall
14382 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
14383 (add-text-properties (point-min) (1- (point))
14384 (list 'face 'org-level-3))
14385 (insert (org-finalize-agenda-entries rtnall) "\n")))
14386 (setq s (point))
14387 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
14388 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
14389 (while (setq d (pop day-numbers))
14390 (setq date (calendar-gregorian-from-absolute d)
14391 s (point))
14392 (if (or (setq todayp (= d today))
14393 (and (not start-pos) (= d sd)))
14394 (setq start-pos (point))
14395 (if (and start-pos (not end-pos))
14396 (setq end-pos (point))))
14397 (setq files thefiles
14398 rtnall nil)
14399 (while (setq file (pop files))
14400 (catch 'nextfile
14401 (org-check-agenda-file file)
14402 (if org-agenda-show-log
14403 (setq rtn (org-agenda-get-day-entries
14404 file date
14405 :deadline :scheduled :timestamp :closed))
14406 (setq rtn (org-agenda-get-day-entries
14407 file date
14408 :deadline :scheduled :timestamp)))
14409 (setq rtnall (append rtnall rtn))))
14410 (if org-agenda-include-diary
14411 (progn
14412 (require 'diary-lib)
14413 (setq rtn (org-get-entries-from-diary date))
14414 (setq rtnall (append rtnall rtn))))
14415 (if (or rtnall org-agenda-show-all-dates)
14416 (progn
14417 (insert (format "%-9s %2d %s %4d\n"
14418 (calendar-day-name date)
14419 (extract-calendar-day date)
14420 (calendar-month-name (extract-calendar-month date))
14421 (extract-calendar-year date)))
14422 ; FIXME: this gives a timezone problem
14423 ; (insert (format-time-string org-agenda-date-format
14424 ; (calendar-time-from-absolute d 0)) "\n")
14425 (put-text-property s (1- (point)) 'face 'org-level-3)
14426 (put-text-property s (1- (point)) 'org-date-line t)
14427 (if todayp (put-text-property s (1- (point)) 'org-today t))
14428 (if rtnall (insert
14429 (org-finalize-agenda-entries
14430 (org-agenda-add-time-grid-maybe
14431 rtnall nd todayp))
14432 "\n"))
14433 (put-text-property s (1- (point)) 'day d))))
14434 (goto-char (point-min))
14435 (org-fit-agenda-window)
14436 (unless (and (pos-visible-in-window-p (point-min))
14437 (pos-visible-in-window-p (point-max)))
14438 (goto-char (1- (point-max)))
14439 (recenter -1)
14440 (if (not (pos-visible-in-window-p (or start-pos 1)))
14441 (progn
14442 (goto-char (or start-pos 1))
14443 (recenter 1))))
14444 (goto-char (or start-pos 1))
14445 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14446 (org-finalize-agenda)
14447 (setq buffer-read-only t)
14448 (message "")))
14450 ;;; Agenda TODO list
14452 (defvar org-select-this-todo-keyword nil)
14453 (defvar org-last-arg nil)
14455 ;;;###autoload
14456 (defun org-todo-list (arg)
14457 "Show all TODO entries from all agenda file in a single list.
14458 The prefix arg can be used to select a specific TODO keyword and limit
14459 the list to these. When using \\[universal-argument], you will be prompted
14460 for a keyword. A numeric prefix directly selects the Nth keyword in
14461 `org-todo-keywords'."
14462 (interactive "P")
14463 (require 'calendar)
14464 (org-compile-prefix-format 'todo)
14465 (org-set-sorting-strategy 'todo)
14466 (let* ((today (time-to-days (current-time)))
14467 (date (calendar-gregorian-from-absolute today))
14468 (kwds org-todo-keywords)
14469 (completion-ignore-case t)
14470 (org-select-this-todo-keyword
14471 (if (stringp arg) arg
14472 (and arg (integerp arg) (> arg 0)
14473 (nth (1- arg) org-todo-keywords))))
14474 rtn rtnall files file pos)
14475 (when (equal arg '(4))
14476 (setq org-select-this-todo-keyword
14477 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
14478 nil t)))
14479 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14480 (org-prepare-agenda)
14481 (org-set-local 'org-last-arg arg)
14482 (org-set-local 'org-todo-keywords kwds)
14483 (setq org-agenda-redo-command
14484 '(org-todo-list (or current-prefix-arg org-last-arg)))
14485 (setq files (org-agenda-files)
14486 rtnall nil)
14487 (while (setq file (pop files))
14488 (catch 'nextfile
14489 (org-check-agenda-file file)
14490 (setq rtn (org-agenda-get-day-entries file date :todo))
14491 (setq rtnall (append rtnall rtn))))
14492 (if org-agenda-overriding-header
14493 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14494 nil 'face 'org-level-3) "\n")
14495 (insert "Global list of TODO items of type: ")
14496 (add-text-properties (point-min) (1- (point))
14497 (list 'face 'org-level-3))
14498 (setq pos (point))
14499 (insert (or org-select-this-todo-keyword "ALL") "\n")
14500 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14501 (setq pos (point))
14502 (unless org-agenda-multi
14503 (insert
14504 "Available with `N r': (0)ALL "
14505 (let ((n 0))
14506 (mapconcat (lambda (x)
14507 (format "(%d)%s" (setq n (1+ n)) x))
14508 org-todo-keywords " "))
14509 "\n"))
14510 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14511 (when rtnall
14512 (insert (org-finalize-agenda-entries rtnall) "\n"))
14513 (goto-char (point-min))
14514 (org-fit-agenda-window)
14515 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14516 (org-finalize-agenda)
14517 (setq buffer-read-only t)))
14519 ;;; Agenda tags match
14521 ;;;###autoload
14522 (defun org-tags-view (&optional todo-only match)
14523 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14524 The prefix arg TODO-ONLY limits the search to TODO entries."
14525 (interactive "P")
14526 (org-compile-prefix-format 'tags)
14527 (org-set-sorting-strategy 'tags)
14528 (let* ((org-tags-match-list-sublevels
14529 (if todo-only t org-tags-match-list-sublevels))
14530 (completion-ignore-case t)
14531 rtn rtnall files file pos matcher
14532 buffer)
14533 (setq matcher (org-make-tags-matcher match)
14534 match (car matcher) matcher (cdr matcher))
14535 (org-prepare-agenda)
14536 (setq org-agenda-redo-command
14537 (list 'org-tags-view (list 'quote todo-only)
14538 (list 'if 'current-prefix-arg nil match)))
14539 (setq files (org-agenda-files)
14540 rtnall nil)
14541 (while (setq file (pop files))
14542 (catch 'nextfile
14543 (org-check-agenda-file file)
14544 (setq buffer (if (file-exists-p file)
14545 (org-get-agenda-file-buffer file)
14546 (error "No such file %s" file)))
14547 (if (not buffer)
14548 ;; If file does not exist, merror message to agenda
14549 (setq rtn (list
14550 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14551 rtnall (append rtnall rtn))
14552 (with-current-buffer buffer
14553 (unless (org-mode-p)
14554 (error "Agenda file %s is not in `org-mode'" file))
14555 (setq org-category-table (org-get-category-table))
14556 (save-excursion
14557 (save-restriction
14558 (if org-agenda-restrict
14559 (narrow-to-region org-agenda-restrict-begin
14560 org-agenda-restrict-end)
14561 (widen))
14562 (setq rtn (org-scan-tags 'agenda matcher todo-only))
14563 (setq rtnall (append rtnall rtn))))))))
14564 (if org-agenda-overriding-header
14565 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14566 nil 'face 'org-level-3) "\n")
14567 (insert "Headlines with TAGS match: ")
14568 (add-text-properties (point-min) (1- (point))
14569 (list 'face 'org-level-3))
14570 (setq pos (point))
14571 (insert match "\n")
14572 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14573 (setq pos (point))
14574 (unless org-agenda-multi
14575 (insert "Press `C-u r' to search again with new search string\n"))
14576 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14577 (when rtnall
14578 (insert (org-finalize-agenda-entries rtnall) "\n"))
14579 (goto-char (point-min))
14580 (org-fit-agenda-window)
14581 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14582 (org-finalize-agenda)
14583 (setq buffer-read-only t)))
14585 ;;; Agenda Finding stuck projects
14587 (defvar org-agenda-skip-regexp nil
14588 "Regular expression used in skipping subtrees for the agenda.
14589 This is basically a temporary global variable that can be set and then
14590 used by user-defined selections using `org-agenda-skip-function'.")
14592 (defvar org-agenda-overriding-header nil
14593 "When this is set during todo and tags searches, will replace header.")
14595 (defun org-agenda-skip-subtree-when-regexp-matches ()
14596 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14597 If yes, it returns the end position of this tree, causing agenda commands
14598 to skip this subtree. This is a function that can be put into
14599 `org-agenda-skip-function' for the duration of a command."
14600 (save-match-data
14601 (let ((end (save-excursion (org-end-of-subtree t)))
14602 skip)
14603 (save-excursion
14604 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
14605 (and skip end))))
14607 (defun org-agenda-list-stuck-projects (&rest ignore)
14608 "Create agenda view for projects that are stuck.
14609 Stuck projects are project that have no next actions. For the definitions
14610 of what a project is and how to check if it stuck, customize the variable
14611 `org-stuck-projects'.
14612 MATCH is being ignored."
14613 (interactive)
14614 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14615 (org-agenda-overriding-header "List of stuck projects: ")
14616 (matcher (nth 0 org-stuck-projects))
14617 (todo (nth 1 org-stuck-projects))
14618 (tags (nth 2 org-stuck-projects))
14619 (todo-re (concat "^\\*+[ \t]+\\("
14620 (mapconcat 'identity todo "\\|")
14621 "\\)\\>"))
14622 (tags-re (concat "^\\*+.*:\\("
14623 (mapconcat 'identity tags "\\|")
14624 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14626 (setq org-agenda-skip-regexp
14627 (cond
14628 ((and todo tags)
14629 (concat todo-re "\\|" tags-re))
14630 (todo todo-re)
14631 (tags tags-re)
14632 (t (error "No information how to identify unstuck projects"))))
14633 (org-tags-view nil matcher)
14634 (with-current-buffer org-agenda-buffer-name
14635 (setq org-agenda-redo-command
14636 '(org-agenda-list-stuck-projects
14637 (or current-prefix-arg org-last-arg))))))
14639 ;;; Diary integration
14641 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
14643 (defun org-get-entries-from-diary (date)
14644 "Get the (Emacs Calendar) diary entries for DATE."
14645 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14646 (diary-display-hook '(fancy-diary-display))
14647 (list-diary-entries-hook
14648 (cons 'org-diary-default-entry list-diary-entries-hook))
14649 (diary-file-name-prefix-function nil) ; turn this feature off
14650 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14651 entries
14652 (org-disable-agenda-to-diary t))
14653 (save-excursion
14654 (save-window-excursion
14655 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
14656 (if (not (get-buffer fancy-diary-buffer))
14657 (setq entries nil)
14658 (with-current-buffer fancy-diary-buffer
14659 (setq buffer-read-only nil)
14660 (if (= (point-max) 1)
14661 ;; No entries
14662 (setq entries nil)
14663 ;; Omit the date and other unnecessary stuff
14664 (org-agenda-cleanup-fancy-diary)
14665 ;; Add prefix to each line and extend the text properties
14666 (if (= (point-max) 1)
14667 (setq entries nil)
14668 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14669 (set-buffer-modified-p nil)
14670 (kill-buffer fancy-diary-buffer)))
14671 (when entries
14672 (setq entries (org-split-string entries "\n"))
14673 (setq entries
14674 (mapcar
14675 (lambda (x)
14676 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14677 ;; Extend the text properties to the beginning of the line
14678 (org-add-props x (text-properties-at (1- (length x)) x)))
14679 entries)))))
14681 (defun org-agenda-cleanup-fancy-diary ()
14682 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14683 This gets rid of the date, the underline under the date, and
14684 the dummy entry installed by `org-mode' to ensure non-empty diary for each
14685 date. It also removes lines that contain only whitespace."
14686 (goto-char (point-min))
14687 (if (looking-at ".*?:[ \t]*")
14688 (progn
14689 (replace-match "")
14690 (re-search-forward "\n=+$" nil t)
14691 (replace-match "")
14692 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14693 (re-search-forward "\n=+$" nil t)
14694 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14695 (goto-char (point-min))
14696 (while (re-search-forward "^ +\n" nil t)
14697 (replace-match ""))
14698 (goto-char (point-min))
14699 (if (re-search-forward "^Org-mode dummy\n?" nil t)
14700 (replace-match "")))
14702 ;; Make sure entries from the diary have the right text properties.
14703 (eval-after-load "diary-lib"
14704 '(if (boundp 'diary-modify-entry-list-string-function)
14705 ;; We can rely on the hook, nothing to do
14707 ;; Hook not avaiable, must use advice to make this work
14708 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14709 "Make the position visible."
14710 (if (and org-disable-agenda-to-diary ;; called from org-agenda
14711 (stringp string)
14712 buffer-file-name)
14713 (setq string (org-modify-diary-entry-string string))))))
14715 (defun org-modify-diary-entry-string (string)
14716 "Add text properties to string, allowing org-mode to act on it."
14717 (org-add-props string nil
14718 'mouse-face 'highlight
14719 'keymap org-agenda-keymap
14720 'help-echo (format "mouse-2 or RET jump to diary file %s"
14721 (abbreviate-file-name buffer-file-name))
14722 'org-agenda-diary-link t
14723 'org-marker (org-agenda-new-marker (point-at-bol))))
14725 (defun org-diary-default-entry ()
14726 "Add a dummy entry to the diary.
14727 Needed to avoid empty dates which mess up holiday display."
14728 ;; Catch the error if dealing with the new add-to-diary-alist
14729 (when org-disable-agenda-to-diary
14730 (condition-case nil
14731 (add-to-diary-list original-date "Org-mode dummy" "")
14732 (error
14733 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
14735 ;;;###autoload
14736 (defun org-diary (&rest args)
14737 "Return diary information from org-files.
14738 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14739 It accesses org files and extracts information from those files to be
14740 listed in the diary. The function accepts arguments specifying what
14741 items should be listed. The following arguments are allowed:
14743 :timestamp List the headlines of items containing a date stamp or
14744 date range matching the selected date. Deadlines will
14745 also be listed, on the expiration day.
14747 :deadline List any deadlines past due, or due within
14748 `org-deadline-warning-days'. The listing occurs only
14749 in the diary for *today*, not at any other date. If
14750 an entry is marked DONE, it is no longer listed.
14752 :scheduled List all items which are scheduled for the given date.
14753 The diary for *today* also contains items which were
14754 scheduled earlier and are not yet marked DONE.
14756 :todo List all TODO items from the org-file. This may be a
14757 long list - so this is not turned on by default.
14758 Like deadlines, these entries only show up in the
14759 diary for *today*, not at any other date.
14761 The call in the diary file should look like this:
14763 &%%(org-diary) ~/path/to/some/orgfile.org
14765 Use a separate line for each org file to check. Or, if you omit the file name,
14766 all files listed in `org-agenda-files' will be checked automatically:
14768 &%%(org-diary)
14770 If you don't give any arguments (as in the example above), the default
14771 arguments (:deadline :scheduled :timestamp) are used. So the example above may
14772 also be written as
14774 &%%(org-diary :deadline :timestamp :scheduled)
14776 The function expects the lisp variables `entry' and `date' to be provided
14777 by the caller, because this is how the calendar works. Don't use this
14778 function from a program - use `org-agenda-get-day-entries' instead."
14779 (org-agenda-maybe-reset-markers)
14780 (org-compile-prefix-format 'agenda)
14781 (org-set-sorting-strategy 'agenda)
14782 (setq args (or args '(:deadline :scheduled :timestamp)))
14783 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
14784 (list entry)
14785 (org-agenda-files t)))
14786 file rtn results)
14787 ;; If this is called during org-agenda, don't return any entries to
14788 ;; the calendar. Org Agenda will list these entries itself.
14789 (if org-disable-agenda-to-diary (setq files nil))
14790 (while (setq file (pop files))
14791 (setq rtn (apply 'org-agenda-get-day-entries file date args))
14792 (setq results (append results rtn)))
14793 (if results
14794 (concat (org-finalize-agenda-entries results) "\n"))))
14796 ;;; Agenda entry finders
14798 (defun org-agenda-get-day-entries (file date &rest args)
14799 "Does the work for `org-diary' and `org-agenda'.
14800 FILE is the path to a file to be checked for entries. DATE is date like
14801 the one returned by `calendar-current-date'. ARGS are symbols indicating
14802 which kind of entries should be extracted. For details about these, see
14803 the documentation of `org-diary'."
14804 (setq args (or args '(:deadline :scheduled :timestamp)))
14805 (let* ((org-startup-folded nil)
14806 (org-startup-align-all-tables nil)
14807 (buffer (if (file-exists-p file)
14808 (org-get-agenda-file-buffer file)
14809 (error "No such file %s" file)))
14810 arg results rtn)
14811 (if (not buffer)
14812 ;; If file does not exist, make sure an error message ends up in diary
14813 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14814 (with-current-buffer buffer
14815 (unless (org-mode-p)
14816 (error "Agenda file %s is not in `org-mode'" file))
14817 (setq org-category-table (org-get-category-table))
14818 (let ((case-fold-search nil))
14819 (save-excursion
14820 (save-restriction
14821 (if org-agenda-restrict
14822 (narrow-to-region org-agenda-restrict-begin
14823 org-agenda-restrict-end)
14824 (widen))
14825 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
14826 (while (setq arg (pop args))
14827 (cond
14828 ((and (eq arg :todo)
14829 (equal date (calendar-current-date)))
14830 (setq rtn (org-agenda-get-todos))
14831 (setq results (append results rtn)))
14832 ((eq arg :timestamp)
14833 (setq rtn (org-agenda-get-blocks))
14834 (setq results (append results rtn))
14835 (setq rtn (org-agenda-get-timestamps))
14836 (setq results (append results rtn)))
14837 ((eq arg :scheduled)
14838 (setq rtn (org-agenda-get-scheduled))
14839 (setq results (append results rtn)))
14840 ((eq arg :closed)
14841 (setq rtn (org-agenda-get-closed))
14842 (setq results (append results rtn)))
14843 ((and (eq arg :deadline)
14844 (equal date (calendar-current-date)))
14845 (setq rtn (org-agenda-get-deadlines))
14846 (setq results (append results rtn))))))))
14847 results))))
14849 (defun org-entry-is-done-p ()
14850 "Is the current entry marked DONE?"
14851 (save-excursion
14852 (and (re-search-backward "[\r\n]\\*" nil t)
14853 (looking-at org-nl-done-regexp))))
14855 (defun org-at-date-range-p (&optional inactive-ok)
14856 "Is the cursor inside a date range?"
14857 (interactive)
14858 (save-excursion
14859 (catch 'exit
14860 (let ((pos (point)))
14861 (skip-chars-backward "^[<\r\n")
14862 (skip-chars-backward "<[")
14863 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14864 (>= (match-end 0) pos)
14865 (throw 'exit t))
14866 (skip-chars-backward "^<[\r\n")
14867 (skip-chars-backward "<[")
14868 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14869 (>= (match-end 0) pos)
14870 (throw 'exit t)))
14871 nil)))
14873 (defun org-agenda-get-todos ()
14874 "Return the TODO information for agenda display."
14875 (let* ((props (list 'face nil
14876 'done-face 'org-done
14877 'org-not-done-regexp org-not-done-regexp
14878 'mouse-face 'highlight
14879 'keymap org-agenda-keymap
14880 'help-echo
14881 (format "mouse-2 or RET jump to org file %s"
14882 (abbreviate-file-name buffer-file-name))))
14883 ;; FIXME: get rid of the \n at some point but watch out
14884 (regexp (concat "[\n\r]\\*+ *\\("
14885 (if org-select-this-todo-keyword
14886 (concat "\\<\\(" org-select-this-todo-keyword
14887 "\\)\\>")
14888 org-not-done-regexp)
14889 "[^\n\r]*\\)"))
14890 marker priority category tags
14891 ee txt beg end)
14892 (goto-char (point-min))
14893 (while (re-search-forward regexp nil t)
14894 (catch :skip
14895 (save-match-data
14896 (beginning-of-line)
14897 (setq beg (point) end (progn (outline-next-heading) (point)))
14898 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
14899 (re-search-forward org-scheduled-time-regexp end t))
14900 (and org-agenda-todo-ignore-deadlines (goto-char beg)
14901 (re-search-forward org-deadline-time-regexp end t)
14902 (org-deadline-close (match-string 1))))
14903 (goto-char beg)
14904 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
14905 (throw :skip nil)))
14906 (goto-char beg)
14907 (org-agenda-skip)
14908 (goto-char (match-beginning 1))
14909 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
14910 category (org-get-category)
14911 tags (org-get-tags-at (point))
14912 txt (org-format-agenda-item "" (match-string 1) category tags)
14913 priority (1+ (org-get-priority txt)))
14914 (org-add-props txt props
14915 'org-marker marker 'org-hd-marker marker
14916 'priority priority 'org-category category)
14917 (push txt ee)
14918 (if org-agenda-todo-list-sublevels
14919 (goto-char (match-end 1))
14920 (org-end-of-subtree 'invisible))))
14921 (nreverse ee)))
14923 (defconst org-agenda-no-heading-message
14924 "No heading for this item in buffer or region.")
14926 (defun org-agenda-get-timestamps ()
14927 "Return the date stamp information for agenda display."
14928 (let* ((props (list 'face nil
14929 'org-not-done-regexp org-not-done-regexp
14930 'mouse-face 'highlight
14931 'keymap org-agenda-keymap
14932 'help-echo
14933 (format "mouse-2 or RET jump to org file %s"
14934 (abbreviate-file-name buffer-file-name))))
14935 (regexp (regexp-quote
14936 (substring
14937 (format-time-string
14938 (car org-time-stamp-formats)
14939 (apply 'encode-time ; DATE bound by calendar
14940 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14941 0 11)))
14942 marker hdmarker deadlinep scheduledp donep tmp priority category
14943 ee txt timestr tags)
14944 (goto-char (point-min))
14945 (while (re-search-forward regexp nil t)
14946 (catch :skip
14947 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
14948 (org-agenda-skip)
14949 (setq marker (org-agenda-new-marker (match-beginning 0))
14950 category (org-get-category (match-beginning 0))
14951 tmp (buffer-substring (max (point-min)
14952 (- (match-beginning 0)
14953 org-ds-keyword-length))
14954 (match-beginning 0))
14955 timestr (buffer-substring (match-beginning 0) (point-at-eol))
14956 deadlinep (string-match org-deadline-regexp tmp)
14957 scheduledp (string-match org-scheduled-regexp tmp)
14958 donep (org-entry-is-done-p))
14959 (and org-agenda-skip-scheduled-if-done
14960 scheduledp donep
14961 (throw :skip t))
14962 (if (string-match ">" timestr)
14963 ;; substring should only run to end of time stamp
14964 (setq timestr (substring timestr 0 (match-end 0))))
14965 (save-excursion
14966 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14967 (progn
14968 (goto-char (match-end 1))
14969 (setq hdmarker (org-agenda-new-marker)
14970 tags (org-get-tags-at))
14971 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14972 (setq txt (org-format-agenda-item
14973 (format "%s%s"
14974 (if deadlinep "Deadline: " "")
14975 (if scheduledp "Scheduled: " ""))
14976 (match-string 1) category tags timestr)))
14977 (setq txt org-agenda-no-heading-message))
14978 (setq priority (org-get-priority txt))
14979 (org-add-props txt props
14980 'org-marker marker 'org-hd-marker hdmarker)
14981 (if deadlinep
14982 (org-add-props txt nil
14983 'face (if donep 'org-done 'org-warning)
14984 'undone-face 'org-warning 'done-face 'org-done
14985 'org-category category 'priority (+ 100 priority))
14986 (if scheduledp
14987 (org-add-props txt nil
14988 'face 'org-scheduled-today
14989 'undone-face 'org-scheduled-today 'done-face 'org-done
14990 'org-category category 'priority (+ 99 priority))
14991 (org-add-props txt nil 'priority priority 'org-category category)))
14992 (push txt ee))
14993 (outline-next-heading)))
14994 (nreverse ee)))
14996 (defun org-agenda-get-closed ()
14997 "Return the logged TODO entries for agenda display."
14998 (let* ((props (list 'mouse-face 'highlight
14999 'org-not-done-regexp org-not-done-regexp
15000 'keymap org-agenda-keymap
15001 'help-echo
15002 (format "mouse-2 or RET jump to org file %s"
15003 (abbreviate-file-name buffer-file-name))))
15004 (regexp (concat
15005 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
15006 (regexp-quote
15007 (substring
15008 (format-time-string
15009 (car org-time-stamp-formats)
15010 (apply 'encode-time ; DATE bound by calendar
15011 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
15012 1 11))))
15013 marker hdmarker priority category tags closedp
15014 ee txt timestr)
15015 (goto-char (point-min))
15016 (while (re-search-forward regexp nil t)
15017 (catch :skip
15018 (org-agenda-skip)
15019 (setq marker (org-agenda-new-marker (match-beginning 0))
15020 closedp (equal (match-string 1) org-closed-string)
15021 category (org-get-category (match-beginning 0))
15022 timestr (buffer-substring (match-beginning 0) (point-at-eol))
15023 ;; donep (org-entry-is-done-p)
15025 (if (string-match "\\]" timestr)
15026 ;; substring should only run to end of time stamp
15027 (setq timestr (substring timestr 0 (match-end 0))))
15028 (save-excursion
15029 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15030 (progn
15031 (goto-char (match-end 1))
15032 (setq hdmarker (org-agenda-new-marker)
15033 tags (org-get-tags-at))
15034 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15035 (setq txt (org-format-agenda-item
15036 (if closedp "Closed: " "Clocked: ")
15037 (match-string 1) category tags timestr)))
15038 (setq txt org-agenda-no-heading-message))
15039 (setq priority 100000)
15040 (org-add-props txt props
15041 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
15042 'priority priority 'org-category category
15043 'undone-face 'org-warning 'done-face 'org-done)
15044 (push txt ee))
15045 (outline-next-heading)))
15046 (nreverse ee)))
15048 (defun org-agenda-get-deadlines ()
15049 "Return the deadline information for agenda display."
15050 (let* ((wdays org-deadline-warning-days)
15051 (props (list 'mouse-face 'highlight
15052 'org-not-done-regexp org-not-done-regexp
15053 'keymap org-agenda-keymap
15054 'help-echo
15055 (format "mouse-2 or RET jump to org file %s"
15056 (abbreviate-file-name buffer-file-name))))
15057 (regexp org-deadline-time-regexp)
15058 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15059 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15060 d2 diff pos pos1 category tags
15061 ee txt head face)
15062 (goto-char (point-min))
15063 (while (re-search-forward regexp nil t)
15064 (catch :skip
15065 (org-agenda-skip)
15066 (setq pos (1- (match-beginning 1))
15067 d2 (time-to-days
15068 (org-time-string-to-time (match-string 1)))
15069 diff (- d2 d1))
15070 ;; When to show a deadline in the calendar:
15071 ;; If the expiration is within wdays warning time.
15072 ;; Past-due deadlines are only shown on the current date
15073 (if (and (< diff wdays) todayp (not (= diff 0)))
15074 (save-excursion
15075 (setq category (org-get-category))
15076 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15077 (progn
15078 (goto-char (match-end 0))
15079 (setq pos1 (match-end 1))
15080 (setq tags (org-get-tags-at pos1))
15081 (setq head (buffer-substring-no-properties
15082 (point)
15083 (progn (skip-chars-forward "^\r\n")
15084 (point))))
15085 (if (string-match org-looking-at-done-regexp head)
15086 (setq txt nil)
15087 (setq txt (org-format-agenda-item
15088 (format "In %3d d.: " diff) head category tags))))
15089 (setq txt org-agenda-no-heading-message))
15090 (when txt
15091 (setq face (cond ((<= diff 0) 'org-warning)
15092 ((<= diff 5) 'org-upcoming-deadline)
15093 (t nil)))
15094 (org-add-props txt props
15095 'org-marker (org-agenda-new-marker pos)
15096 'org-hd-marker (org-agenda-new-marker pos1)
15097 'priority (+ (- 10 diff) (org-get-priority txt))
15098 'org-category category
15099 'face face 'undone-face face 'done-face 'org-done)
15100 (push txt ee))))))
15101 ee))
15103 (defun org-agenda-get-scheduled ()
15104 "Return the scheduled information for agenda display."
15105 (let* ((props (list 'face 'org-scheduled-previously
15106 'org-not-done-regexp org-not-done-regexp
15107 'undone-face 'org-scheduled-previously
15108 'done-face 'org-done
15109 'mouse-face 'highlight
15110 'keymap org-agenda-keymap
15111 'help-echo
15112 (format "mouse-2 or RET jump to org file %s"
15113 (abbreviate-file-name buffer-file-name))))
15114 (regexp org-scheduled-time-regexp)
15115 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15116 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15117 d2 diff pos pos1 category tags
15118 ee txt head)
15119 (goto-char (point-min))
15120 (while (re-search-forward regexp nil t)
15121 (catch :skip
15122 (org-agenda-skip)
15123 (setq pos (1- (match-beginning 1))
15124 d2 (time-to-days
15125 (org-time-string-to-time (match-string 1)))
15126 diff (- d2 d1))
15127 ;; When to show a scheduled item in the calendar:
15128 ;; If it is on or past the date.
15129 (if (and (< diff 0) todayp)
15130 (save-excursion
15131 (setq category (org-get-category))
15132 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15133 (progn
15134 (goto-char (match-end 0))
15135 (setq pos1 (match-end 1))
15136 (setq tags (org-get-tags-at))
15137 (setq head (buffer-substring-no-properties
15138 (point)
15139 (progn (skip-chars-forward "^\r\n") (point))))
15140 (if (string-match org-looking-at-done-regexp head)
15141 (setq txt nil)
15142 (setq txt (org-format-agenda-item
15143 (format "Sched.%2dx: " (- 1 diff)) head
15144 category tags))))
15145 (setq txt org-agenda-no-heading-message))
15146 (when txt
15147 (org-add-props txt props
15148 'org-marker (org-agenda-new-marker pos)
15149 'org-hd-marker (org-agenda-new-marker pos1)
15150 'priority (+ (- 5 diff) (org-get-priority txt))
15151 'org-category category)
15152 (push txt ee))))))
15153 ee))
15155 (defun org-agenda-get-blocks ()
15156 "Return the date-range information for agenda display."
15157 (let* ((props (list 'face nil
15158 'org-not-done-regexp org-not-done-regexp
15159 'mouse-face 'highlight
15160 'keymap org-agenda-keymap
15161 'help-echo
15162 (format "mouse-2 or RET jump to org file %s"
15163 (abbreviate-file-name buffer-file-name))))
15164 (regexp org-tr-regexp)
15165 (d0 (calendar-absolute-from-gregorian date))
15166 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
15167 (goto-char (point-min))
15168 (while (re-search-forward regexp nil t)
15169 (catch :skip
15170 (org-agenda-skip)
15171 (setq pos (point))
15172 (setq timestr (match-string 0)
15173 s1 (match-string 1)
15174 s2 (match-string 2)
15175 d1 (time-to-days (org-time-string-to-time s1))
15176 d2 (time-to-days (org-time-string-to-time s2)))
15177 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
15178 ;; Only allow days between the limits, because the normal
15179 ;; date stamps will catch the limits.
15180 (save-excursion
15181 (setq marker (org-agenda-new-marker (point)))
15182 (setq category (org-get-category))
15183 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15184 (progn
15185 (setq hdmarker (org-agenda-new-marker (match-end 1)))
15186 (goto-char (match-end 1))
15187 (setq tags (org-get-tags-at))
15188 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15189 (setq txt (org-format-agenda-item
15190 (format (if (= d1 d2) "" "(%d/%d): ")
15191 (1+ (- d0 d1)) (1+ (- d2 d1)))
15192 (match-string 1) category tags
15193 (if (= d0 d1) timestr))))
15194 (setq txt org-agenda-no-heading-message))
15195 (org-add-props txt props
15196 'org-marker marker 'org-hd-marker hdmarker
15197 'priority (org-get-priority txt) 'org-category category)
15198 (push txt ee)))
15199 (goto-char pos)))
15200 ;; Sort the entries by expiration date.
15201 (nreverse ee)))
15203 ;;; Agenda presentation and sorting
15205 ;; FIXME: should I allow spaces around the dash?
15206 (defconst org-plain-time-of-day-regexp
15207 (concat
15208 "\\(\\<[012]?[0-9]"
15209 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15210 "\\(--?"
15211 "\\(\\<[012]?[0-9]"
15212 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15213 "\\)?")
15214 "Regular expression to match a plain time or time range.
15215 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
15216 groups carry important information:
15217 0 the full match
15218 1 the first time, range or not
15219 8 the second time, if it is a range.")
15221 (defconst org-stamp-time-of-day-regexp
15222 (concat
15223 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
15224 "\\([012][0-9]:[0-5][0-9]\\)>"
15225 "\\(--?"
15226 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
15227 "Regular expression to match a timestamp time or time range.
15228 After a match, the following groups carry important information:
15229 0 the full match
15230 1 date plus weekday, for backreferencing to make sure both times on same day
15231 2 the first time, range or not
15232 4 the second time, if it is a range.")
15234 (defvar org-prefix-has-time nil
15235 "A flag, set by `org-compile-prefix-format'.
15236 The flag is set if the currently compiled format contains a `%t'.")
15237 (defvar org-prefix-has-tag nil
15238 "A flag, set by `org-compile-prefix-format'.
15239 The flag is set if the currently compiled format contains a `%T'.")
15241 (defun org-format-agenda-item (extra txt &optional category tags dotime
15242 noprefix)
15243 "Format TXT to be inserted into the agenda buffer.
15244 In particular, it adds the prefix and corresponding text properties. EXTRA
15245 must be a string and replaces the `%s' specifier in the prefix format.
15246 CATEGORY (string, symbol or nil) may be used to overrule the default
15247 category taken from local variable or file name. It will replace the `%c'
15248 specifier in the format. DOTIME, when non-nil, indicates that a
15249 time-of-day should be extracted from TXT for sorting of this entry, and for
15250 the `%t' specifier in the format. When DOTIME is a string, this string is
15251 searched for a time before TXT is. NOPREFIX is a flag and indicates that
15252 only the correctly processes TXT should be returned - this is used by
15253 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
15254 (save-match-data
15255 ;; Diary entries sometimes have extra whitespace at the beginning
15256 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
15257 (let* ((category (or category
15258 org-category
15259 (if buffer-file-name
15260 (file-name-sans-extension
15261 (file-name-nondirectory buffer-file-name))
15262 "")))
15263 (tag (if tags (nth (1- (length tags)) tags) ""))
15264 time ; time and tag are needed for the eval of the prefix format
15265 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
15266 (time-of-day (and dotime (org-get-time-of-day ts)))
15267 stamp plain s0 s1 s2 rtn)
15268 (when (and dotime time-of-day org-prefix-has-time)
15269 ;; Extract starting and ending time and move them to prefix
15270 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
15271 (setq plain (string-match org-plain-time-of-day-regexp ts)))
15272 (setq s0 (match-string 0 ts)
15273 s1 (match-string (if plain 1 2) ts)
15274 s2 (match-string (if plain 8 4) ts))
15276 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
15277 ;; them, we might want to remove them there to avoid duplication.
15278 ;; The user can turn this off with a variable.
15279 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
15280 (string-match (concat (regexp-quote s0) " *") txt)
15281 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
15282 (= (match-beginning 0) 0)
15284 (setq txt (replace-match "" nil nil txt))))
15285 ;; Normalize the time(s) to 24 hour
15286 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
15287 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
15289 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
15290 ;; Tags are in the string
15291 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
15292 (and org-agenda-remove-tags-when-in-prefix
15293 org-prefix-has-tag))
15294 (setq txt (replace-match "" t t txt))
15295 (setq txt (replace-match
15296 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
15297 (match-string 2 txt))
15298 t t txt))))
15300 ;; Create the final string
15301 (if noprefix
15302 (setq rtn txt)
15303 ;; Prepare the variables needed in the eval of the compiled format
15304 (setq time (cond (s2 (concat s1 "-" s2))
15305 (s1 (concat s1 "......"))
15306 (t ""))
15307 extra (or extra "")
15308 category (if (symbolp category) (symbol-name category) category))
15309 ;; Evaluate the compiled format
15310 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
15312 ;; And finally add the text properties
15313 (org-add-props rtn nil
15314 'org-category (downcase category) 'tags tags
15315 'prefix-length (- (length rtn) (length txt))
15316 'time-of-day time-of-day
15317 'dotime dotime))))
15319 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
15320 (defvar org-agenda-sorting-strategy-selected nil)
15322 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
15323 (catch 'exit
15324 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
15325 ((and todayp (member 'today (car org-agenda-time-grid))))
15326 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
15327 ((member 'weekly (car org-agenda-time-grid)))
15328 (t (throw 'exit list)))
15329 (let* ((have (delq nil (mapcar
15330 (lambda (x) (get-text-property 1 'time-of-day x))
15331 list)))
15332 (string (nth 1 org-agenda-time-grid))
15333 (gridtimes (nth 2 org-agenda-time-grid))
15334 (req (car org-agenda-time-grid))
15335 (remove (member 'remove-match req))
15336 new time)
15337 (if (and (member 'require-timed req) (not have))
15338 ;; don't show empty grid
15339 (throw 'exit list))
15340 (while (setq time (pop gridtimes))
15341 (unless (and remove (member time have))
15342 (setq time (int-to-string time))
15343 (push (org-format-agenda-item
15344 nil string "" nil
15345 (concat (substring time 0 -2) ":" (substring time -2)))
15346 new)
15347 (put-text-property
15348 1 (length (car new)) 'face 'org-time-grid (car new))))
15349 (if (member 'time-up org-agenda-sorting-strategy-selected)
15350 (append new list)
15351 (append list new)))))
15353 (defun org-compile-prefix-format (key)
15354 "Compile the prefix format into a Lisp form that can be evaluated.
15355 The resulting form is returned and stored in the variable
15356 `org-prefix-format-compiled'."
15357 (setq org-prefix-has-time nil org-prefix-has-tag nil)
15358 (let ((s (cond
15359 ((stringp org-agenda-prefix-format)
15360 org-agenda-prefix-format)
15361 ((assq key org-agenda-prefix-format)
15362 (cdr (assq key org-agenda-prefix-format)))
15363 (t " %-12:c%?-12t% s")))
15364 (start 0)
15365 varform vars var e c f opt)
15366 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
15367 s start)
15368 (setq var (cdr (assoc (match-string 4 s)
15369 '(("c" . category) ("t" . time) ("s" . extra)
15370 ("T" . tag))))
15371 c (or (match-string 3 s) "")
15372 opt (match-beginning 1)
15373 start (1+ (match-beginning 0)))
15374 (if (equal var 'time) (setq org-prefix-has-time t))
15375 (if (equal var 'tag) (setq org-prefix-has-tag t))
15376 (setq f (concat "%" (match-string 2 s) "s"))
15377 (if opt
15378 (setq varform
15379 `(if (equal "" ,var)
15381 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
15382 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
15383 (setq s (replace-match "%s" t nil s))
15384 (push varform vars))
15385 (setq vars (nreverse vars))
15386 (setq org-prefix-format-compiled `(format ,s ,@vars))))
15388 (defun org-set-sorting-strategy (key)
15389 (if (symbolp (car org-agenda-sorting-strategy))
15390 ;; the old format
15391 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
15392 (setq org-agenda-sorting-strategy-selected
15393 (or (cdr (assq key org-agenda-sorting-strategy))
15394 (cdr (assq 'agenda org-agenda-sorting-strategy))
15395 '(time-up category-keep priority-down)))))
15397 (defun org-get-time-of-day (s &optional string mod24)
15398 "Check string S for a time of day.
15399 If found, return it as a military time number between 0 and 2400.
15400 If not found, return nil.
15401 The optional STRING argument forces conversion into a 5 character wide string
15402 HH:MM."
15403 (save-match-data
15404 (when
15406 (string-match
15407 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
15408 (string-match
15409 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
15410 (let* ((h (string-to-number (match-string 1 s)))
15411 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
15412 (ampm (if (match-end 4) (downcase (match-string 4 s))))
15413 (am-p (equal ampm "am"))
15414 (h1 (cond ((not ampm) h)
15415 ((= h 12) (if am-p 0 12))
15416 (t (+ h (if am-p 0 12)))))
15417 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
15418 (mod h1 24) h1))
15419 (t0 (+ (* 100 h2) m))
15420 (t1 (concat (if (>= h1 24) "+" " ")
15421 (if (< t0 100) "0" "")
15422 (if (< t0 10) "0" "")
15423 (int-to-string t0))))
15424 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
15426 (defun org-finalize-agenda-entries (list &optional nosort)
15427 "Sort and concatenate the agenda items."
15428 (setq list (mapcar 'org-agenda-highlight-todo list))
15429 (if nosort
15430 list
15431 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15433 (defun org-agenda-highlight-todo (x)
15434 (let (re pl)
15435 (if (eq x 'line)
15436 (save-excursion
15437 (beginning-of-line 1)
15438 (setq re (get-text-property (point) 'org-not-done-regexp))
15439 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15440 (and (looking-at (concat "[ \t]*\\.*" re))
15441 (add-text-properties (match-beginning 0) (match-end 0)
15442 '(face org-todo))))
15443 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15444 pl (get-text-property 0 'prefix-length x))
15445 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15446 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15447 '(face org-todo) x))
15448 x)))
15450 (defsubst org-cmp-priority (a b)
15451 "Compare the priorities of string A and B."
15452 (let ((pa (or (get-text-property 1 'priority a) 0))
15453 (pb (or (get-text-property 1 'priority b) 0)))
15454 (cond ((> pa pb) +1)
15455 ((< pa pb) -1)
15456 (t nil))))
15458 (defsubst org-cmp-category (a b)
15459 "Compare the string values of categories of strings A and B."
15460 (let ((ca (or (get-text-property 1 'category a) ""))
15461 (cb (or (get-text-property 1 'category b) "")))
15462 (cond ((string-lessp ca cb) -1)
15463 ((string-lessp cb ca) +1)
15464 (t nil))))
15466 (defsubst org-cmp-tag (a b)
15467 "Compare the string values of categories of strings A and B."
15468 (let ((ta (car (last (get-text-property 1 'tags a))))
15469 (tb (car (last (get-text-property 1 'tags b)))))
15470 (cond ((not ta) +1)
15471 ((not tb) -1)
15472 ((string-lessp ta tb) -1)
15473 ((string-lessp tb ta) +1)
15474 (t nil))))
15476 (defsubst org-cmp-time (a b)
15477 "Compare the time-of-day values of strings A and B."
15478 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15479 (ta (or (get-text-property 1 'time-of-day a) def))
15480 (tb (or (get-text-property 1 'time-of-day b) def)))
15481 (cond ((< ta tb) -1)
15482 ((< tb ta) +1)
15483 (t nil))))
15485 (defun org-entries-lessp (a b)
15486 "Predicate for sorting agenda entries."
15487 ;; The following variables will be used when the form is evaluated.
15488 ;; So even though the compiler complains, keep them.
15489 (let* ((time-up (org-cmp-time a b))
15490 (time-down (if time-up (- time-up) nil))
15491 (priority-up (org-cmp-priority a b))
15492 (priority-down (if priority-up (- priority-up) nil))
15493 (category-up (org-cmp-category a b))
15494 (category-down (if category-up (- category-up) nil))
15495 (category-keep (if category-up +1 nil))
15496 (tag-up (org-cmp-tag a b))
15497 (tag-down (if tag-up (- tag-up) nil)))
15498 (cdr (assoc
15499 (eval (cons 'or org-agenda-sorting-strategy-selected))
15500 '((-1 . t) (1 . nil) (nil . nil))))))
15502 ;;; Agenda commands
15504 (defun org-agenda-check-type (error &rest types)
15505 "Check if agenda buffer is of allowed type.
15506 If ERROR is non-nil, throw an error, otherwise just return nil."
15507 (if (memq org-agenda-type types)
15509 (if error
15510 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
15511 nil)))
15513 (defun org-agenda-quit ()
15514 "Exit agenda by removing the window or the buffer."
15515 (interactive)
15516 (let ((buf (current-buffer)))
15517 (if (not (one-window-p)) (delete-window))
15518 (kill-buffer buf)
15519 (org-agenda-maybe-reset-markers 'force))
15520 ;; Maybe restore the pre-agenda window configuration.
15521 (and org-agenda-restore-windows-after-quit
15522 (not (eq org-agenda-window-setup 'other-frame))
15523 org-pre-agenda-window-conf
15524 (set-window-configuration org-pre-agenda-window-conf)))
15526 (defun org-agenda-exit ()
15527 "Exit agenda by removing the window or the buffer.
15528 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15529 Org-mode buffers visited directly by the user will not be touched."
15530 (interactive)
15531 (org-release-buffers org-agenda-new-buffers)
15532 (setq org-agenda-new-buffers nil)
15533 (org-agenda-quit))
15535 (defun org-save-all-org-buffers ()
15536 "Save all Org-mode buffers without user confirmation."
15537 (interactive)
15538 (message "Saving all Org-mode buffers...")
15539 (save-some-buffers t 'org-mode-p)
15540 (message "Saving all Org-mode buffers... done"))
15542 (defun org-agenda-redo ()
15543 "Rebuild Agenda.
15544 When this is the global TODO list, a prefix argument will be interpreted."
15545 (interactive)
15546 (let* ((org-agenda-keep-modes t)
15547 (line (org-current-line))
15548 (window-line (- line (org-current-line (window-start)))))
15549 (message "Rebuilding agenda buffer...")
15550 (eval org-agenda-redo-command)
15551 (setq org-agenda-undo-list nil
15552 org-agenda-pending-undo-list nil)
15553 (message "Rebuilding agenda buffer...done")
15554 (goto-line line)
15555 (recenter window-line)))
15557 (defun org-agenda-goto-today ()
15558 "Go to today."
15559 (interactive)
15560 (org-agenda-check-type t 'timeline 'agenda)
15561 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15562 (cond
15563 (tdpos (goto-char tdpos))
15564 ((eq org-agenda-type 'agenda)
15565 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15566 (setf (nth 1 org-agenda-overriding-arguments) nil)
15567 (org-agenda-redo)
15568 (org-agenda-find-today-or-agenda)))
15569 (t (error "Cannot find today")))))
15571 (defun org-agenda-find-today-or-agenda ()
15572 (goto-char
15573 (or (text-property-any (point-min) (point-max) 'org-today t)
15574 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15575 (point-min))))
15577 (defun org-agenda-later (arg)
15578 "Go forward in time by `org-agenda-ndays' days.
15579 With prefix ARG, go forward that many times `org-agenda-ndays'."
15580 (interactive "p")
15581 (org-agenda-check-type t 'agenda)
15582 (let ((org-agenda-overriding-arguments
15583 (list (car org-agenda-last-arguments)
15584 (+ org-starting-day (* arg org-agenda-ndays))
15585 nil t)))
15586 (org-agenda-redo)
15587 (org-agenda-find-today-or-agenda)))
15589 (defun org-agenda-earlier (arg)
15590 "Go back in time by `org-agenda-ndays' days.
15591 With prefix ARG, go back that many times `org-agenda-ndays'."
15592 (interactive "p")
15593 (org-agenda-check-type t 'agenda)
15594 (let ((org-agenda-overriding-arguments
15595 (list (car org-agenda-last-arguments)
15596 (- org-starting-day (* arg org-agenda-ndays))
15597 nil t)))
15598 (org-agenda-redo)
15599 (org-agenda-find-today-or-agenda)))
15601 (defun org-agenda-week-view ()
15602 "Switch to weekly view for agenda."
15603 (interactive)
15604 (org-agenda-check-type t 'agenda)
15605 (if (= org-agenda-ndays 7)
15606 (error "This is already the week view"))
15607 (setq org-agenda-ndays 7)
15608 (let ((org-agenda-overriding-arguments
15609 (list (car org-agenda-last-arguments)
15610 (or (get-text-property (point) 'day)
15611 org-starting-day)
15612 nil t)))
15613 (org-agenda-redo)
15614 (org-agenda-find-today-or-agenda))
15615 (org-agenda-set-mode-name)
15616 (message "Switched to week view"))
15618 (defun org-agenda-day-view ()
15619 "Switch to daily view for agenda."
15620 (interactive)
15621 (org-agenda-check-type t 'agenda)
15622 (if (= org-agenda-ndays 1)
15623 (error "This is already the day view"))
15624 (setq org-agenda-ndays 1)
15625 (let ((org-agenda-overriding-arguments
15626 (list (car org-agenda-last-arguments)
15627 (or (get-text-property (point) 'day)
15628 org-starting-day)
15629 nil t)))
15630 (org-agenda-redo)
15631 (org-agenda-find-today-or-agenda))
15632 (org-agenda-set-mode-name)
15633 (message "Switched to day view"))
15635 ;; FIXME: this no longer works if user make date format that starts with a blank
15636 (defun org-agenda-next-date-line (&optional arg)
15637 "Jump to the next line indicating a date in agenda buffer."
15638 (interactive "p")
15639 (org-agenda-check-type t 'agenda 'timeline)
15640 (beginning-of-line 1)
15641 (if (looking-at "^\\S-") (forward-char 1))
15642 (if (not (re-search-forward "^\\S-" nil t arg))
15643 (progn
15644 (backward-char 1)
15645 (error "No next date after this line in this buffer")))
15646 (goto-char (match-beginning 0)))
15648 (defun org-agenda-previous-date-line (&optional arg)
15649 "Jump to the previous line indicating a date in agenda buffer."
15650 (interactive "p")
15651 (org-agenda-check-type t 'agenda 'timeline)
15652 (beginning-of-line 1)
15653 (if (not (re-search-backward "^\\S-" nil t arg))
15654 (error "No previous date before this line in this buffer")))
15656 ;; Initialize the highlight
15657 (defvar org-hl (org-make-overlay 1 1))
15658 (org-overlay-put org-hl 'face 'highlight)
15660 (defun org-highlight (begin end &optional buffer)
15661 "Highlight a region with overlay."
15662 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15663 org-hl begin end (or buffer (current-buffer))))
15665 (defun org-unhighlight ()
15666 "Detach overlay INDEX."
15667 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15669 ;; FIXME this is currently not used.
15670 (defun org-highlight-until-next-command (beg end &optional buffer)
15671 (org-highlight beg end buffer)
15672 (add-hook 'pre-command-hook 'org-unhighlight-once))
15674 (defun org-unhighlight-once ()
15675 (remove-hook 'pre-command-hook 'org-unhighlight-once)
15676 (org-unhighlight))
15678 (defun org-agenda-follow-mode ()
15679 "Toggle follow mode in an agenda buffer."
15680 (interactive)
15681 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15682 (org-agenda-set-mode-name)
15683 (message "Follow mode is %s"
15684 (if org-agenda-follow-mode "on" "off")))
15686 (defun org-agenda-log-mode ()
15687 "Toggle log mode in an agenda buffer."
15688 (interactive)
15689 (org-agenda-check-type t 'agenda 'timeline)
15690 (setq org-agenda-show-log (not org-agenda-show-log))
15691 (org-agenda-set-mode-name)
15692 (org-agenda-redo)
15693 (message "Log mode is %s"
15694 (if org-agenda-show-log "on" "off")))
15696 (defun org-agenda-toggle-diary ()
15697 "Toggle diary inclusion in an agenda buffer."
15698 (interactive)
15699 (org-agenda-check-type t 'agenda)
15700 (setq org-agenda-include-diary (not org-agenda-include-diary))
15701 (org-agenda-redo)
15702 (org-agenda-set-mode-name)
15703 (message "Diary inclusion turned %s"
15704 (if org-agenda-include-diary "on" "off")))
15706 (defun org-agenda-toggle-time-grid ()
15707 "Toggle time grid in an agenda buffer."
15708 (interactive)
15709 (org-agenda-check-type t 'agenda)
15710 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15711 (org-agenda-redo)
15712 (org-agenda-set-mode-name)
15713 (message "Time-grid turned %s"
15714 (if org-agenda-use-time-grid "on" "off")))
15716 (defun org-agenda-set-mode-name ()
15717 "Set the mode name to indicate all the small mode settings."
15718 (setq mode-name
15719 (concat "Org-Agenda"
15720 (if (equal org-agenda-ndays 1) " Day" "")
15721 (if (equal org-agenda-ndays 7) " Week" "")
15722 (if org-agenda-follow-mode " Follow" "")
15723 (if org-agenda-include-diary " Diary" "")
15724 (if org-agenda-use-time-grid " Grid" "")
15725 (if org-agenda-show-log " Log" "")))
15726 (force-mode-line-update))
15728 (defun org-agenda-post-command-hook ()
15729 (and (eolp) (not (bolp)) (backward-char 1))
15730 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15731 (if (and org-agenda-follow-mode
15732 (get-text-property (point) 'org-marker))
15733 (org-agenda-show)))
15735 (defun org-agenda-show-priority ()
15736 "Show the priority of the current item.
15737 This priority is composed of the main priority given with the [#A] cookies,
15738 and by additional input from the age of a schedules or deadline entry."
15739 (interactive)
15740 (let* ((pri (get-text-property (point-at-bol) 'priority)))
15741 (message "Priority is %d" (if pri pri -1000))))
15743 (defun org-agenda-show-tags ()
15744 "Show the tags applicable to the current item."
15745 (interactive)
15746 (let* ((tags (get-text-property (point-at-bol) 'tags)))
15747 (if tags
15748 (message "Tags are :%s:"
15749 (org-no-properties (mapconcat 'identity tags ":")))
15750 (message "No tags associated with this line"))))
15752 (defun org-agenda-goto (&optional highlight)
15753 "Go to the Org-mode file which contains the item at point."
15754 (interactive)
15755 (let* ((marker (or (get-text-property (point) 'org-marker)
15756 (org-agenda-error)))
15757 (buffer (marker-buffer marker))
15758 (pos (marker-position marker)))
15759 (switch-to-buffer-other-window buffer)
15760 (widen)
15761 (goto-char pos)
15762 (when (org-mode-p)
15763 (org-show-context 'agenda)
15764 (save-excursion
15765 (and (outline-next-heading)
15766 (org-flag-heading nil)))) ; show the next heading
15767 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15769 (defun org-agenda-kill ()
15770 "Kill the entry or subtree belonging to the current agenda entry."
15771 (interactive)
15772 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15773 (let* ((marker (or (get-text-property (point) 'org-marker)
15774 (org-agenda-error)))
15775 (buffer (marker-buffer marker))
15776 (pos (marker-position marker))
15777 dbeg dend (n 0) conf)
15778 (org-with-remote-undo buffer
15779 (with-current-buffer buffer
15780 (save-excursion
15781 (goto-char pos)
15782 (if (org-mode-p)
15783 (setq dbeg (progn (org-back-to-heading t) (point))
15784 dend (org-end-of-subtree t))
15785 (setq dbeg (point-at-bol)
15786 dend (min (point-max) (1+ (point-at-eol)))))
15787 (goto-char dbeg)
15788 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
15789 (setq conf (or (eq t org-agenda-confirm-kill)
15790 (and (numberp org-agenda-confirm-kill)
15791 (> n org-agenda-confirm-kill))))
15792 (and conf
15793 (not (y-or-n-p
15794 (format "Delete entry with %d lines in buffer \"%s\"? "
15795 n (buffer-name buffer))))
15796 (error "Abort"))
15797 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
15798 (with-current-buffer buffer (delete-region dbeg dend))
15799 (message "Agenda item and source killed"))))
15801 (defun org-agenda-archive ()
15802 "Kill the entry or subtree belonging to the current agenda entry."
15803 (interactive)
15804 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15805 (let* ((marker (or (get-text-property (point) 'org-marker)
15806 (org-agenda-error)))
15807 (buffer (marker-buffer marker))
15808 (pos (marker-position marker)))
15809 (org-with-remote-undo buffer
15810 (with-current-buffer buffer
15811 (if (org-mode-p)
15812 (save-excursion
15813 (goto-char pos)
15814 (org-remove-subtree-entries-from-agenda)
15815 (org-back-to-heading t)
15816 (org-archive-subtree))
15817 (error "Archiving works only in Org-mode files"))))))
15819 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
15820 "Remove all lines in the agenda that correspond to a given subtree.
15821 The subtree is the one in buffer BUF, starting at BEG and ending at END.
15822 If this information is not given, the function uses the tree at point."
15823 (let ((buf (or buf (current-buffer))) m p)
15824 (save-excursion
15825 (unless (and beg end)
15826 (org-back-to-heading t)
15827 (setq beg (point))
15828 (org-end-of-subtree t)
15829 (setq end (point)))
15830 (set-buffer (get-buffer org-agenda-buffer-name))
15831 (save-excursion
15832 (goto-char (point-max))
15833 (beginning-of-line 1)
15834 (while (not (bobp))
15835 (when (and (setq m (get-text-property (point) 'org-marker))
15836 (equal buf (marker-buffer m))
15837 (setq p (marker-position m))
15838 (>= p beg)
15839 (<= p end))
15840 (let (buffer-read-only)
15841 (delete-region (point-at-bol) (1+ (point-at-eol)))))
15842 (beginning-of-line 0))))))
15844 (defun org-agenda-open-link ()
15845 "Follow the link in the current line, if any."
15846 (interactive)
15847 (let ((eol (point-at-eol)))
15848 (save-excursion
15849 (if (or (re-search-forward org-bracket-link-regexp eol t)
15850 (re-search-forward org-angle-link-re eol t)
15851 (re-search-forward org-plain-link-re eol t))
15852 (call-interactively 'org-open-at-point)
15853 (error "No link in current line")))))
15855 (defun org-agenda-switch-to (&optional delete-other-windows)
15856 "Go to the Org-mode file which contains the item at point."
15857 (interactive)
15858 (let* ((marker (or (get-text-property (point) 'org-marker)
15859 (org-agenda-error)))
15860 (buffer (marker-buffer marker))
15861 (pos (marker-position marker)))
15862 (switch-to-buffer buffer)
15863 (and delete-other-windows (delete-other-windows))
15864 (widen)
15865 (goto-char pos)
15866 (when (org-mode-p)
15867 (org-show-context 'agenda)
15868 (save-excursion
15869 (and (outline-next-heading)
15870 (org-flag-heading nil)))))) ; show the next heading
15872 (defun org-agenda-goto-mouse (ev)
15873 "Go to the Org-mode file which contains the item at the mouse click."
15874 (interactive "e")
15875 (mouse-set-point ev)
15876 (org-agenda-goto))
15878 (defun org-agenda-show ()
15879 "Display the Org-mode file which contains the item at point."
15880 (interactive)
15881 (let ((win (selected-window)))
15882 (org-agenda-goto t)
15883 (select-window win)))
15885 (defun org-agenda-recenter (arg)
15886 "Display the Org-mode file which contains the item at point and recenter."
15887 (interactive "P")
15888 (let ((win (selected-window)))
15889 (org-agenda-goto t)
15890 (recenter arg)
15891 (select-window win)))
15893 (defun org-agenda-show-mouse (ev)
15894 "Display the Org-mode file which contains the item at the mouse click."
15895 (interactive "e")
15896 (mouse-set-point ev)
15897 (org-agenda-show))
15899 (defun org-agenda-check-no-diary ()
15900 "Check if the entry is a diary link and abort if yes."
15901 (if (get-text-property (point) 'org-agenda-diary-link)
15902 (org-agenda-error)))
15904 (defun org-agenda-error ()
15905 (error "Command not allowed in this line"))
15907 (defun org-agenda-tree-to-indirect-buffer ()
15908 "Show the subtree corresponding to the current entry in an indirect buffer.
15909 This calls the command `org-tree-to-indirect-buffer' from the original
15910 Org-mode buffer.
15911 With numerical prefix arg ARG, go up to this level and then take that tree.
15912 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
15913 dedicated frame)."
15914 (interactive)
15915 (org-agenda-check-no-diary)
15916 (let* ((marker (or (get-text-property (point) 'org-marker)
15917 (org-agenda-error)))
15918 (buffer (marker-buffer marker))
15919 (pos (marker-position marker)))
15920 (with-current-buffer buffer
15921 (save-excursion
15922 (goto-char pos)
15923 (call-interactively 'org-tree-to-indirect-buffer)))))
15925 (defvar org-last-heading-marker (make-marker)
15926 "Marker pointing to the headline that last changed its TODO state
15927 by a remote command from the agenda.")
15929 (defun org-agenda-todo (&optional arg)
15930 "Cycle TODO state of line at point, also in Org-mode file.
15931 This changes the line at point, all other lines in the agenda referring to
15932 the same tree node, and the headline of the tree node in the Org-mode file."
15933 (interactive "P")
15934 (org-agenda-check-no-diary)
15935 (let* ((col (current-column))
15936 (marker (or (get-text-property (point) 'org-marker)
15937 (org-agenda-error)))
15938 (buffer (marker-buffer marker))
15939 (pos (marker-position marker))
15940 (hdmarker (get-text-property (point) 'org-hd-marker))
15941 (buffer-read-only nil)
15942 newhead)
15943 (org-with-remote-undo buffer
15944 (with-current-buffer buffer
15945 (widen)
15946 (goto-char pos)
15947 (org-show-context 'agenda)
15948 (save-excursion
15949 (and (outline-next-heading)
15950 (org-flag-heading nil))) ; show the next heading
15951 (org-todo arg)
15952 (and (bolp) (forward-char 1))
15953 (setq newhead (org-get-heading))
15954 (save-excursion
15955 (org-back-to-heading)
15956 (move-marker org-last-heading-marker (point))))
15957 (beginning-of-line 1)
15958 (save-excursion
15959 (org-agenda-change-all-lines newhead hdmarker 'fixface))
15960 (move-to-column col))))
15962 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
15963 "Change all lines in the agenda buffer which match HDMARKER.
15964 The new content of the line will be NEWHEAD (as modified by
15965 `org-format-agenda-item'). HDMARKER is checked with
15966 `equal' against all `org-hd-marker' text properties in the file.
15967 If FIXFACE is non-nil, the face of each item is modified acording to
15968 the new TODO state."
15969 (let* ((buffer-read-only nil)
15970 props m pl undone-face done-face finish new dotime cat tags)
15971 (save-excursion
15972 (goto-char (point-max))
15973 (beginning-of-line 1)
15974 (while (not finish)
15975 (setq finish (bobp))
15976 (when (and (setq m (get-text-property (point) 'org-hd-marker))
15977 (equal m hdmarker))
15978 (setq props (text-properties-at (point))
15979 dotime (get-text-property (point) 'dotime)
15980 cat (get-text-property (point) 'org-category)
15981 tags (get-text-property (point) 'tags)
15982 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
15983 pl (get-text-property (point) 'prefix-length)
15984 undone-face (get-text-property (point) 'undone-face)
15985 done-face (get-text-property (point) 'done-face))
15986 (move-to-column pl)
15987 (cond
15988 ((equal new "")
15989 (beginning-of-line 1)
15990 (and (looking-at ".*\n?") (replace-match "")))
15991 ((looking-at ".*")
15992 (replace-match new t t)
15993 (beginning-of-line 1)
15994 (add-text-properties (point-at-bol) (point-at-eol) props)
15995 (when fixface
15996 (add-text-properties
15997 (point-at-bol) (point-at-eol)
15998 (list 'face
15999 (if org-last-todo-state-is-todo
16000 undone-face done-face))))
16001 (org-agenda-highlight-todo 'line)
16002 (beginning-of-line 1))
16003 (t (error "Line update did not work"))))
16004 (beginning-of-line 0)))
16005 (org-finalize-agenda)))
16007 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
16008 ;; See the code in set-tags for the way to do this.
16009 (defun org-agenda-align-tags (&optional line)
16010 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
16011 (let ((buffer-read-only))
16012 (save-excursion
16013 (goto-char (if line (point-at-bol) (point-min)))
16014 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
16015 (if line (point-at-eol) nil) t)
16016 (delete-region (match-beginning 1) (match-end 1))
16017 (goto-char (match-beginning 1))
16018 (insert (org-add-props
16019 (make-string (max 1 (- org-agenda-align-tags-to-column
16020 (current-column))) ?\ )
16021 (text-properties-at (point))))))))
16023 (defun org-agenda-priority-up ()
16024 "Increase the priority of line at point, also in Org-mode file."
16025 (interactive)
16026 (org-agenda-priority 'up))
16028 (defun org-agenda-priority-down ()
16029 "Decrease the priority of line at point, also in Org-mode file."
16030 (interactive)
16031 (org-agenda-priority 'down))
16033 (defun org-agenda-priority (&optional force-direction)
16034 "Set the priority of line at point, also in Org-mode file.
16035 This changes the line at point, all other lines in the agenda referring to
16036 the same tree node, and the headline of the tree node in the Org-mode file."
16037 (interactive)
16038 (org-agenda-check-no-diary)
16039 (let* ((marker (or (get-text-property (point) 'org-marker)
16040 (org-agenda-error)))
16041 (buffer (marker-buffer marker))
16042 (pos (marker-position marker))
16043 (hdmarker (get-text-property (point) 'org-hd-marker))
16044 (buffer-read-only nil)
16045 newhead)
16046 (org-with-remote-undo buffer
16047 (with-current-buffer buffer
16048 (widen)
16049 (goto-char pos)
16050 (org-show-context 'agenda)
16051 (save-excursion
16052 (and (outline-next-heading)
16053 (org-flag-heading nil))) ; show the next heading
16054 (funcall 'org-priority force-direction)
16055 (end-of-line 1)
16056 (setq newhead (org-get-heading)))
16057 (org-agenda-change-all-lines newhead hdmarker)
16058 (beginning-of-line 1))))
16060 (defun org-get-tags-at (&optional pos)
16061 "Get a list of all headline tags applicable at POS.
16062 POS defaults to point. If tags are inherited, the list contains
16063 the targets in the same sequence as the headlines appear, i.e.
16064 the tags of the current headline come last."
16065 (interactive)
16066 (let (tags)
16067 (save-excursion
16068 (save-restriction
16069 (widen)
16070 (goto-char (or pos (point)))
16071 (save-match-data
16072 (org-back-to-heading t)
16073 (condition-case nil
16074 (while t
16075 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
16076 (setq tags (append (org-split-string
16077 (org-match-string-no-properties 1) ":")
16078 tags)))
16079 (or org-use-tag-inheritance (error ""))
16080 (org-up-heading-all 1))
16081 (error nil))))
16082 tags)))
16084 ;; FIXME: should fix the tags property of the agenda line.
16085 (defun org-agenda-set-tags ()
16086 "Set tags for the current headline."
16087 (interactive)
16088 (org-agenda-check-no-diary)
16089 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16090 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16091 (org-agenda-error)))
16092 (buffer (marker-buffer hdmarker))
16093 (pos (marker-position hdmarker))
16094 (buffer-read-only nil)
16095 newhead)
16096 (org-with-remote-undo buffer
16097 (with-current-buffer buffer
16098 (widen)
16099 (goto-char pos)
16100 (save-excursion
16101 (org-show-context 'agenda))
16102 (save-excursion
16103 (and (outline-next-heading)
16104 (org-flag-heading nil))) ; show the next heading
16105 (goto-char pos)
16106 (call-interactively 'org-set-tags)
16107 (end-of-line 1)
16108 (setq newhead (org-get-heading)))
16109 (org-agenda-change-all-lines newhead hdmarker)
16110 (beginning-of-line 1))))
16112 (defun org-agenda-toggle-archive-tag ()
16113 "Toggle the archive tag for the current entry."
16114 (interactive)
16115 (org-agenda-check-no-diary)
16116 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16117 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16118 (org-agenda-error)))
16119 (buffer (marker-buffer hdmarker))
16120 (pos (marker-position hdmarker))
16121 (buffer-read-only nil)
16122 newhead)
16123 (org-with-remote-undo buffer
16124 (with-current-buffer buffer
16125 (widen)
16126 (goto-char pos)
16127 (org-show-context 'agenda)
16128 (save-excursion
16129 (and (outline-next-heading)
16130 (org-flag-heading nil))) ; show the next heading
16131 (call-interactively 'org-toggle-archive-tag)
16132 (end-of-line 1)
16133 (setq newhead (org-get-heading)))
16134 (org-agenda-change-all-lines newhead hdmarker)
16135 (beginning-of-line 1))))
16137 (defun org-agenda-date-later (arg &optional what)
16138 "Change the date of this item to one day later."
16139 (interactive "p")
16140 (org-agenda-check-type t 'agenda 'timeline)
16141 (org-agenda-check-no-diary)
16142 (let* ((marker (or (get-text-property (point) 'org-marker)
16143 (org-agenda-error)))
16144 (buffer (marker-buffer marker))
16145 (pos (marker-position marker)))
16146 (org-with-remote-undo buffer
16147 (with-current-buffer buffer
16148 (widen)
16149 (goto-char pos)
16150 (if (not (org-at-timestamp-p))
16151 (error "Cannot find time stamp"))
16152 (org-timestamp-change arg (or what 'day)))
16153 (org-agenda-show-new-time marker org-last-changed-timestamp))
16154 (message "Time stamp changed to %s" org-last-changed-timestamp)))
16156 (defun org-agenda-date-earlier (arg &optional what)
16157 "Change the date of this item to one day earlier."
16158 (interactive "p")
16159 (org-agenda-date-later (- arg) what))
16161 (defun org-agenda-show-new-time (marker stamp)
16162 "Show new date stamp via text properties."
16163 ;; We use text properties to make this undoable
16164 (let ((buffer-read-only nil))
16165 (setq stamp (concat " => " stamp))
16166 (save-excursion
16167 (goto-char (point-max))
16168 (while (not (bobp))
16169 (when (equal marker (get-text-property (point) 'org-marker))
16170 (move-to-column (- (window-width) (length stamp)) t)
16171 (if (featurep 'xemacs)
16172 ;; Use `duplicable' property to trigger undo recording
16173 (let ((ex (make-extent nil nil))
16174 (gl (make-glyph stamp)))
16175 (set-glyph-face gl 'secondary-selection)
16176 (set-extent-properties
16177 ex (list 'invisible t 'end-glyph gl 'duplicable t))
16178 (insert-extent ex (1- (point)) (point-at-eol)))
16179 (add-text-properties
16180 (1- (point)) (point-at-eol)
16181 (list 'display (org-add-props stamp nil
16182 'face 'secondary-selection))))
16183 (beginning-of-line 1))
16184 (beginning-of-line 0)))))
16186 (defun org-agenda-date-prompt (arg)
16187 "Change the date of this item. Date is prompted for, with default today.
16188 The prefix ARG is passed to the `org-time-stamp' command and can therefore
16189 be used to request time specification in the time stamp."
16190 (interactive "P")
16191 (org-agenda-check-type t 'agenda 'timeline)
16192 (org-agenda-check-no-diary)
16193 (let* ((marker (or (get-text-property (point) 'org-marker)
16194 (org-agenda-error)))
16195 (buffer (marker-buffer marker))
16196 (pos (marker-position marker)))
16197 (org-with-remote-undo buffer
16198 (with-current-buffer buffer
16199 (widen)
16200 (goto-char pos)
16201 (if (not (org-at-timestamp-p))
16202 (error "Cannot find time stamp"))
16203 (org-time-stamp arg)
16204 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
16206 (defun org-agenda-schedule (arg)
16207 "Schedule the item at point."
16208 (interactive "P")
16209 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16210 (org-agenda-check-no-diary)
16211 (let* ((marker (or (get-text-property (point) 'org-marker)
16212 (org-agenda-error)))
16213 (buffer (marker-buffer marker))
16214 (pos (marker-position marker))
16215 (org-insert-labeled-timestamps-at-point nil)
16217 (org-with-remote-undo buffer
16218 (with-current-buffer buffer
16219 (widen)
16220 (goto-char pos)
16221 (setq ts (org-schedule))
16222 (message "Item scheduled for %s" ts)))))
16224 (defun org-agenda-deadline (arg)
16225 "Schedule the item at point."
16226 (interactive "P")
16227 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16228 (org-agenda-check-no-diary)
16229 (let* ((marker (or (get-text-property (point) 'org-marker)
16230 (org-agenda-error)))
16231 (buffer (marker-buffer marker))
16232 (pos (marker-position marker))
16233 (org-insert-labeled-timestamps-at-point nil)
16235 (org-with-remote-undo buffer
16236 (with-current-buffer buffer
16237 (widen)
16238 (goto-char pos)
16239 (setq ts (org-deadline))
16240 (message "Deadline for this item set to %s" ts)))))
16242 (defun org-get-heading ()
16243 "Return the heading of the current entry, without the stars."
16244 (save-excursion
16245 (org-back-to-heading t)
16246 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
16248 (defun org-agenda-clock-in (&optional arg)
16249 "Start the clock on the currently selected item."
16250 (interactive "P")
16251 (org-agenda-check-no-diary)
16252 (let* ((marker (or (get-text-property (point) 'org-marker)
16253 (org-agenda-error)))
16254 (pos (marker-position marker)))
16255 (org-with-remote-undo (marker-buffer marker)
16256 (with-current-buffer (marker-buffer marker)
16257 (widen)
16258 (goto-char pos)
16259 (org-clock-in)))))
16261 (defun org-agenda-clock-out (&optional arg)
16262 "Stop the currently running clock."
16263 (interactive "P")
16264 (unless (marker-buffer org-clock-marker)
16265 (error "No running clock"))
16266 (org-with-remote-undo (marker-buffer org-clock-marker)
16267 (org-clock-out)))
16269 (defun org-agenda-clock-cancel (&optional arg)
16270 "Cancel the currently running clock."
16271 (interactive "P")
16272 (unless (marker-buffer org-clock-marker)
16273 (error "No running clock"))
16274 (org-with-remote-undo (marker-buffer org-clock-marker)
16275 (org-clock-cancel)))
16277 (defun org-agenda-diary-entry ()
16278 "Make a diary entry, like the `i' command from the calendar.
16279 All the standard commands work: block, weekly etc."
16280 (interactive)
16281 (org-agenda-check-type t 'agenda 'timeline)
16282 (require 'diary-lib)
16283 (let* ((char (progn
16284 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
16285 (read-char-exclusive)))
16286 (cmd (cdr (assoc char
16287 '((?d . insert-diary-entry)
16288 (?w . insert-weekly-diary-entry)
16289 (?m . insert-monthly-diary-entry)
16290 (?y . insert-yearly-diary-entry)
16291 (?a . insert-anniversary-diary-entry)
16292 (?b . insert-block-diary-entry)
16293 (?c . insert-cyclic-diary-entry)))))
16294 (oldf (symbol-function 'calendar-cursor-to-date))
16295 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
16296 (point (point))
16297 (mark (or (mark t) (point))))
16298 (unless cmd
16299 (error "No command associated with <%c>" char))
16300 (unless (and (get-text-property point 'day)
16301 (or (not (equal ?b char))
16302 (get-text-property mark 'day)))
16303 (error "Don't know which date to use for diary entry"))
16304 ;; We implement this by hacking the `calendar-cursor-to-date' function
16305 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
16306 (let ((calendar-mark-ring
16307 (list (calendar-gregorian-from-absolute
16308 (or (get-text-property mark 'day)
16309 (get-text-property point 'day))))))
16310 (unwind-protect
16311 (progn
16312 (fset 'calendar-cursor-to-date
16313 (lambda (&optional error)
16314 (calendar-gregorian-from-absolute
16315 (get-text-property point 'day))))
16316 (call-interactively cmd))
16317 (fset 'calendar-cursor-to-date oldf)))))
16320 (defun org-agenda-execute-calendar-command (cmd)
16321 "Execute a calendar command from the agenda, with the date associated to
16322 the cursor position."
16323 (org-agenda-check-type t 'agenda 'timeline)
16324 (require 'diary-lib)
16325 (unless (get-text-property (point) 'day)
16326 (error "Don't know which date to use for calendar command"))
16327 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
16328 (point (point))
16329 (date (calendar-gregorian-from-absolute
16330 (get-text-property point 'day)))
16331 ;; the following 3 vars are needed in the calendar
16332 (displayed-day (extract-calendar-day date))
16333 (displayed-month (extract-calendar-month date))
16334 (displayed-year (extract-calendar-year date)))
16335 (unwind-protect
16336 (progn
16337 (fset 'calendar-cursor-to-date
16338 (lambda (&optional error)
16339 (calendar-gregorian-from-absolute
16340 (get-text-property point 'day))))
16341 (call-interactively cmd))
16342 (fset 'calendar-cursor-to-date oldf))))
16344 (defun org-agenda-phases-of-moon ()
16345 "Display the phases of the moon for the 3 months around the cursor date."
16346 (interactive)
16347 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
16349 (defun org-agenda-holidays ()
16350 "Display the holidays for the 3 months around the cursor date."
16351 (interactive)
16352 (org-agenda-execute-calendar-command 'list-calendar-holidays))
16354 (defun org-agenda-sunrise-sunset (arg)
16355 "Display sunrise and sunset for the cursor date.
16356 Latitude and longitude can be specified with the variables
16357 `calendar-latitude' and `calendar-longitude'. When called with prefix
16358 argument, latitude and longitude will be prompted for."
16359 (interactive "P")
16360 (let ((calendar-longitude (if arg nil calendar-longitude))
16361 (calendar-latitude (if arg nil calendar-latitude))
16362 (calendar-location-name
16363 (if arg "the given coordinates" calendar-location-name)))
16364 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
16366 (defun org-agenda-goto-calendar ()
16367 "Open the Emacs calendar with the date at the cursor."
16368 (interactive)
16369 (org-agenda-check-type t 'agenda 'timeline)
16370 (let* ((day (or (get-text-property (point) 'day)
16371 (error "Don't know which date to open in calendar")))
16372 (date (calendar-gregorian-from-absolute day))
16373 (calendar-move-hook nil)
16374 (view-calendar-holidays-initially nil)
16375 (view-diary-entries-initially nil))
16376 (calendar)
16377 (calendar-goto-date date)))
16379 (defun org-calendar-goto-agenda ()
16380 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
16381 This is a command that has to be installed in `calendar-mode-map'."
16382 (interactive)
16383 (org-agenda-list nil (calendar-absolute-from-gregorian
16384 (calendar-cursor-to-date))
16385 nil))
16387 (defun org-agenda-convert-date ()
16388 (interactive)
16389 (org-agenda-check-type t 'agenda 'timeline)
16390 (let ((day (get-text-property (point) 'day))
16391 date s)
16392 (unless day
16393 (error "Don't know which date to convert"))
16394 (setq date (calendar-gregorian-from-absolute day))
16395 (setq s (concat
16396 "Gregorian: " (calendar-date-string date) "\n"
16397 "ISO: " (calendar-iso-date-string date) "\n"
16398 "Day of Yr: " (calendar-day-of-year-string date) "\n"
16399 "Julian: " (calendar-julian-date-string date) "\n"
16400 "Astron. JD: " (calendar-astro-date-string date)
16401 " (Julian date number at noon UTC)\n"
16402 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
16403 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
16404 "French: " (calendar-french-date-string date) "\n"
16405 "Mayan: " (calendar-mayan-date-string date) "\n"
16406 "Coptic: " (calendar-coptic-date-string date) "\n"
16407 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
16408 "Persian: " (calendar-persian-date-string date) "\n"
16409 "Chinese: " (calendar-chinese-date-string date) "\n"))
16410 (with-output-to-temp-buffer "*Dates*"
16411 (princ s))
16412 (if (fboundp 'fit-window-to-buffer)
16413 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
16416 ;;;; Embedded LaTeX
16418 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16419 "Keymap for the minor `org-cdlatex-mode'.")
16421 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16422 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16423 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16424 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16425 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16427 (defvar org-cdlatex-texmathp-advice-is-done nil
16428 "Flag remembering if we have applied the advice to texmathp already.")
16430 (define-minor-mode org-cdlatex-mode
16431 "Toggle the minor `org-cdlatex-mode'.
16432 This mode supports entering LaTeX environment and math in LaTeX fragments
16433 in Org-mode.
16434 \\{org-cdlatex-mode-map}"
16435 nil " OCDL" nil
16436 (when org-cdlatex-mode (require 'cdlatex))
16437 (unless org-cdlatex-texmathp-advice-is-done
16438 (setq org-cdlatex-texmathp-advice-is-done t)
16439 (defadvice texmathp (around org-math-always-on activate)
16440 "Always return t in org-mode buffers.
16441 This is because we want to insert math symbols without dollars even outside
16442 the LaTeX math segments. If Orgmode thinks that point is actually inside
16443 en embedded LaTeX fragement, let texmathp do its job.
16444 \\[org-cdlatex-mode-map]"
16445 (interactive)
16446 (let (p)
16447 (cond
16448 ((not (org-mode-p)) ad-do-it)
16449 ((eq this-command 'cdlatex-math-symbol)
16450 (setq ad-return-value t
16451 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16453 (let ((p (org-inside-LaTeX-fragment-p)))
16454 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16455 (setq ad-return-value t
16456 texmathp-why '("Org-mode embedded math" . 0))
16457 (if p ad-do-it)))))))))
16459 (defun turn-on-org-cdlatex ()
16460 "Unconditionally turn on `org-cdlatex-mode'."
16461 (org-cdlatex-mode 1))
16463 (defun org-inside-LaTeX-fragment-p ()
16464 "Test if point is inside a LaTeX fragment.
16465 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16466 sequence appearing also before point.
16467 Even though the matchers for math are configurable, this function assumes
16468 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16469 delimiters are skipped when they have been removed by customization.
16470 The return value is nil, or a cons cell with the delimiter and
16471 and the position of this delimiter.
16473 This function does a reasonably good job, but can locally be fooled by
16474 for example currency specifications. For example it will assume being in
16475 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16476 fragments that are properly closed, but during editing, we have to live
16477 with the uncertainty caused by missing closing delimiters. This function
16478 looks only before point, not after."
16479 (catch 'exit
16480 (let ((pos (point))
16481 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16482 (lim (progn
16483 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16484 (point)))
16485 dd-on str (start 0) m re)
16486 (goto-char pos)
16487 (when dodollar
16488 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16489 re (nth 1 (assoc "$" org-latex-regexps)))
16490 (while (string-match re str start)
16491 (cond
16492 ((= (match-end 0) (length str))
16493 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16494 ((= (match-end 0) (- (length str) 5))
16495 (throw 'exit nil))
16496 (t (setq start (match-end 0))))))
16497 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16498 (goto-char pos)
16499 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16500 (and (match-beginning 2) (throw 'exit nil))
16501 ;; count $$
16502 (while (re-search-backward "\\$\\$" lim t)
16503 (setq dd-on (not dd-on)))
16504 (goto-char pos)
16505 (if dd-on (cons "$$" m))))))
16508 (defun org-try-cdlatex-tab ()
16509 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16510 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16511 - inside a LaTeX fragment, or
16512 - after the first word in a line, where an abbreviation expansion could
16513 insert a LaTeX environment."
16514 (when org-cdlatex-mode
16515 (cond
16516 ((save-excursion
16517 (skip-chars-backward "a-zA-Z0-9*")
16518 (skip-chars-backward " \t")
16519 (bolp))
16520 (cdlatex-tab) t)
16521 ((org-inside-LaTeX-fragment-p)
16522 (cdlatex-tab) t)
16523 (t nil))))
16525 (defun org-cdlatex-underscore-caret (&optional arg)
16526 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16527 Revert to the normal definition outside of these fragments."
16528 (interactive "P")
16529 (if (org-inside-LaTeX-fragment-p)
16530 (call-interactively 'cdlatex-sub-superscript)
16531 (let (org-cdlatex-mode)
16532 (call-interactively (key-binding (vector last-input-event))))))
16534 (defun org-cdlatex-math-modify (&optional arg)
16535 "Execute `cdlatex-math-modify' in LaTeX fragments.
16536 Revert to the normal definition outside of these fragments."
16537 (interactive "P")
16538 (if (org-inside-LaTeX-fragment-p)
16539 (call-interactively 'cdlatex-math-modify)
16540 (let (org-cdlatex-mode)
16541 (call-interactively (key-binding (vector last-input-event))))))
16543 (defvar org-latex-fragment-image-overlays nil
16544 "List of overlays carrying the images of latex fragments.")
16545 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16547 (defun org-remove-latex-fragment-image-overlays ()
16548 "Remove all overlays with LaTeX fragment images in current buffer."
16549 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16550 (setq org-latex-fragment-image-overlays nil))
16552 (defun org-preview-latex-fragment (&optional subtree)
16553 "Preview the LaTeX fragment at point, or all locally or globally.
16554 If the cursor is in a LaTeX fragment, create the image and overlay
16555 it over the source code. If there is no fragment at point, display
16556 all fragments in the current text, from one headline to the next. With
16557 prefix SUBTREE, display all fragments in the current subtree. With a
16558 double prefix `C-u C-u', or when the cursor is before the first headline,
16559 display all fragments in the buffer.
16560 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16561 (interactive "P")
16562 (org-remove-latex-fragment-image-overlays)
16563 (save-excursion
16564 (save-restriction
16565 (let (beg end at msg)
16566 (cond
16567 ((or (equal subtree '(16))
16568 (not (save-excursion
16569 (re-search-backward (concat "^" outline-regexp) nil t))))
16570 (setq beg (point-min) end (point-max)
16571 msg "Creating images for buffer...%s"))
16572 ((equal subtree '(4))
16573 (org-back-to-heading)
16574 (setq beg (point) end (org-end-of-subtree t)
16575 msg "Creating images for subtree...%s"))
16577 (if (setq at (org-inside-LaTeX-fragment-p))
16578 (goto-char (max (point-min) (- (cdr at) 2)))
16579 (org-back-to-heading))
16580 (setq beg (point) end (progn (outline-next-heading) (point))
16581 msg (if at "Creating image...%s"
16582 "Creating images for entry...%s"))))
16583 (message msg "")
16584 (narrow-to-region beg end)
16585 (org-format-latex
16586 (concat "ltxpng/" (file-name-sans-extension
16587 (file-name-nondirectory
16588 buffer-file-name)))
16589 default-directory 'overlays msg at)
16590 (message msg "done. Use `C-c C-c' to remove images.")))))
16592 (defvar org-latex-regexps
16593 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16594 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16595 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16596 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16597 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16598 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16599 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16600 "Regular expressions for matching embedded LaTeX.")
16602 (defun org-format-latex (prefix &optional dir overlays msg at)
16603 "Replace LaTeX fragments with links to an image, and produce images."
16604 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16605 (let* ((prefixnodir (file-name-nondirectory prefix))
16606 (absprefix (expand-file-name prefix dir))
16607 (todir (file-name-directory absprefix))
16608 (opt org-format-latex-options)
16609 (matchers (plist-get opt :matchers))
16610 (re-list org-latex-regexps)
16611 (cnt 0) txt link beg end re e checkdir
16612 m n block linkfile movefile ov)
16613 ;; Check if there are old images files with this prefix, and remove them
16614 (when (file-directory-p todir)
16615 (mapc 'delete-file
16616 (directory-files
16617 todir 'full
16618 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16619 ;; Check the different regular expressions
16620 (while (setq e (pop re-list))
16621 (setq m (car e) re (nth 1 e) n (nth 2 e)
16622 block (if (nth 3 e) "\n\n" ""))
16623 (when (member m matchers)
16624 (goto-char (point-min))
16625 (while (re-search-forward re nil t)
16626 (when (or (not at) (equal (cdr at) (match-beginning n)))
16627 (setq txt (match-string n)
16628 beg (match-beginning n) end (match-end n)
16629 cnt (1+ cnt)
16630 linkfile (format "%s_%04d.png" prefix cnt)
16631 movefile (format "%s_%04d.png" absprefix cnt)
16632 link (concat block "[[file:" linkfile "]]" block))
16633 (if msg (message msg cnt))
16634 (goto-char beg)
16635 (unless checkdir ; make sure the directory exists
16636 (setq checkdir t)
16637 (or (file-directory-p todir) (make-directory todir)))
16638 (org-create-formula-image
16639 txt movefile opt)
16640 (if overlays
16641 (progn
16642 (setq ov (org-make-overlay beg end))
16643 (if (featurep 'xemacs)
16644 (progn
16645 (org-overlay-put ov 'invisible t)
16646 (org-overlay-put
16647 ov 'end-glyph
16648 (make-glyph (vector 'png :file movefile))))
16649 (org-overlay-put
16650 ov 'display
16651 (list 'image :type 'png :file movefile :ascent 'center)))
16652 (push ov org-latex-fragment-image-overlays)
16653 (goto-char end))
16654 (delete-region beg end)
16655 (insert link))))))))
16657 ;; This function borrows from Ganesh Swami's latex2png.el
16658 (defun org-create-formula-image (string tofile options)
16659 (let* ((tmpdir (if (featurep 'xemacs)
16660 (temp-directory)
16661 temporary-file-directory))
16662 (texfilebase (make-temp-name
16663 (expand-file-name "orgtex" tmpdir)))
16665 ;(texfilebase (make-temp-file "orgtex"))
16666 ; (dummy (delete-file texfilebase))
16667 (texfile (concat texfilebase ".tex"))
16668 (dvifile (concat texfilebase ".dvi"))
16669 (pngfile (concat texfilebase ".png"))
16670 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16671 (fg (or (plist-get options :foreground) "Black"))
16672 (bg (or (plist-get options :background) "Transparent")))
16673 (with-temp-file texfile
16674 (insert "\\documentclass{article}
16675 \\usepackage{fullpage}
16676 \\usepackage{amssymb}
16677 \\usepackage[usenames]{color}
16678 \\usepackage{amsmath}
16679 \\usepackage{latexsym}
16680 \\usepackage[mathscr]{eucal}
16681 \\pagestyle{empty}
16682 \\begin{document}\n" string "\n\\end{document}\n"))
16683 (let ((dir default-directory))
16684 (condition-case nil
16685 (progn
16686 (cd tmpdir)
16687 (call-process "latex" nil nil nil texfile))
16688 (error nil))
16689 (cd dir))
16690 (if (not (file-exists-p dvifile))
16691 (progn (message "Failed to create dvi file from %s" texfile) nil)
16692 (call-process "dvipng" nil nil nil
16693 "-E" "-fg" fg "-bg" bg
16694 "-x" scale "-y" scale "-T" "tight"
16695 "-o" pngfile
16696 dvifile)
16697 (if (not (file-exists-p pngfile))
16698 (progn (message "Failed to create png file from %s" texfile) nil)
16699 ;; Use the requested file name and clean up
16700 (copy-file pngfile tofile 'replace)
16701 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16702 (delete-file (concat texfilebase e)))
16703 pngfile))))
16705 ;;;; Exporting
16707 ;;; Variables, constants, and parameter plists
16709 (defconst org-level-max 20)
16711 (defvar org-export-html-preamble nil
16712 "Preamble, to be inserted just after <body>. Set by publishing functions.")
16713 (defvar org-export-html-postamble nil
16714 "Preamble, to be inserted just before </body>. Set by publishing functions.")
16715 (defvar org-export-html-auto-preamble t
16716 "Should default preamble be inserted? Set by publishing functions.")
16717 (defvar org-export-html-auto-postamble t
16718 "Should default postamble be inserted? Set by publishing functions.")
16719 (defvar org-current-export-file nil) ; dynamically scoped parameter
16720 (defvar org-current-export-dir nil) ; dynamically scoped parameter
16723 (defconst org-export-plist-vars
16724 '((:language . org-export-default-language)
16725 (:customtime . org-display-custom-times)
16726 (:headline-levels . org-export-headline-levels)
16727 (:section-numbers . org-export-with-section-numbers)
16728 (:table-of-contents . org-export-with-toc)
16729 (:archived-trees . org-export-with-archived-trees)
16730 (:emphasize . org-export-with-emphasize)
16731 (:sub-superscript . org-export-with-sub-superscripts)
16732 (:TeX-macros . org-export-with-TeX-macros)
16733 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
16734 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
16735 (:fixed-width . org-export-with-fixed-width)
16736 (:timestamps . org-export-with-timestamps)
16737 (:tables . org-export-with-tables)
16738 (:table-auto-headline . org-export-highlight-first-table-line)
16739 (:style . org-export-html-style)
16740 (:convert-org-links . org-export-html-link-org-files-as-html)
16741 (:inline-images . org-export-html-inline-images)
16742 (:expand-quoted-html . org-export-html-expand)
16743 (:timestamp . org-export-html-with-timestamp)
16744 (:publishing-directory . org-export-publishing-directory)
16745 (:preamble . org-export-html-preamble)
16746 (:postamble . org-export-html-postamble)
16747 (:auto-preamble . org-export-html-auto-preamble)
16748 (:auto-postamble . org-export-html-auto-postamble)
16749 (:author . user-full-name)
16750 (:email . user-mail-address)))
16752 (defun org-default-export-plist ()
16753 "Return the property list with default settings for the export variables."
16754 (let ((l org-export-plist-vars) rtn e)
16755 (while (setq e (pop l))
16756 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
16757 rtn))
16759 (defun org-infile-export-plist ()
16760 "Return the property list with file-local settings for export."
16761 (save-excursion
16762 (goto-char 0)
16763 (let ((re (org-make-options-regexp
16764 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
16765 p key val text options)
16766 (while (re-search-forward re nil t)
16767 (setq key (org-match-string-no-properties 1)
16768 val (org-match-string-no-properties 2))
16769 (cond
16770 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
16771 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
16772 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
16773 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
16774 ((string-equal key "TEXT")
16775 (setq text (if text (concat text "\n" val) val)))
16776 ((string-equal key "OPTIONS") (setq options val))))
16777 (setq p (plist-put p :text text))
16778 (when options
16779 (let ((op '(("H" . :headline-levels)
16780 ("num" . :section-numbers)
16781 ("toc" . :table-of-contents)
16782 ("\\n" . :preserve-breaks)
16783 ("@" . :expand-quoted-html)
16784 (":" . :fixed-width)
16785 ("|" . :tables)
16786 ("^" . :sub-superscript)
16787 ("*" . :emphasize)
16788 ("TeX" . :TeX-macros)
16789 ("LaTeX" . :LaTeX-fragments)
16790 ("skip" . :skip-before-1st-heading)))
16792 (while (setq o (pop op))
16793 (if (string-match (concat (regexp-quote (car o))
16794 ":\\([^ \t\n\r;,.]*\\)")
16795 options)
16796 (setq p (plist-put p (cdr o)
16797 (car (read-from-string
16798 (match-string 1 options)))))))))
16799 p)))
16801 (defun org-export-directory (type plist)
16802 (let* ((val (plist-get plist :publishing-directory))
16803 (dir (if (listp val)
16804 (or (cdr (assoc type val)) ".")
16805 val)))
16806 dir))
16808 (defun org-skip-comments (lines)
16809 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
16810 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
16811 (re2 "^\\(\\*+\\)[ \t\n\r]")
16812 rtn line level)
16813 (while (setq line (pop lines))
16814 (cond
16815 ((and (string-match re1 line)
16816 (setq level (- (match-end 1) (match-beginning 1))))
16817 ;; Beginning of a COMMENT subtree. Skip it.
16818 (while (and (setq line (pop lines))
16819 (or (not (string-match re2 line))
16820 (> (- (match-end 1) (match-beginning 1)) level))))
16821 (setq lines (cons line lines)))
16822 ((string-match "^#" line)
16823 ;; an ordinary comment line
16825 ((and org-export-table-remove-special-lines
16826 (string-match "^[ \t]*|" line)
16827 (or (string-match "^[ \t]*| *[!_^] *|" line)
16828 (and (string-match "| *<[0-9]+> *|" line)
16829 (not (string-match "| *[^ <|]" line)))))
16830 ;; a special table line that should be removed
16832 (t (setq rtn (cons line rtn)))))
16833 (nreverse rtn)))
16835 (defun org-export (&optional arg)
16836 (interactive)
16837 (let ((help "[t] insert the export option template
16838 \[v] limit export to visible part of outline tree
16840 \[a] export as ASCII
16841 \[h] export as HTML
16842 \[b] export as HTML and browse immediately
16843 \[x] export as XOXO
16845 \[i] export current file as iCalendar file
16846 \[I] export all agenda files as iCalendar files
16847 \[c] export agenda files into combined iCalendar file
16849 \[F] publish current file
16850 \[P] publish current project
16851 \[X] publish... (project will be prompted for)
16852 \[A] publish all projects")
16853 (cmds
16854 '((?t . org-insert-export-options-template)
16855 (?v . org-export-visible)
16856 (?a . org-export-as-ascii)
16857 (?h . org-export-as-html)
16858 (?b . org-export-as-html-and-open)
16859 (?x . org-export-as-xoxo)
16860 (?i . org-export-icalendar-this-file)
16861 (?I . org-export-icalendar-all-agenda-files)
16862 (?c . org-export-icalendar-combine-agenda-files)
16863 (?F . org-publish-current-file)
16864 (?P . org-publish-current-project)
16865 (?X . org-publish)
16866 (?A . org-publish-all)))
16867 r1 r2 ass)
16868 (save-window-excursion
16869 (delete-other-windows)
16870 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
16871 (princ help))
16872 (message "Select command: ")
16873 (setq r1 (read-char-exclusive)))
16874 (setq r2 (if (< r1 27) (+ r1 96) r1))
16875 (if (setq ass (assq r2 cmds))
16876 (call-interactively (cdr ass))
16877 (error "No command associated with key %c" r1))))
16879 (defconst org-html-entities
16880 '(("nbsp")
16881 ("iexcl")
16882 ("cent")
16883 ("pound")
16884 ("curren")
16885 ("yen")
16886 ("brvbar")
16887 ("sect")
16888 ("uml")
16889 ("copy")
16890 ("ordf")
16891 ("laquo")
16892 ("not")
16893 ("shy")
16894 ("reg")
16895 ("macr")
16896 ("deg")
16897 ("plusmn")
16898 ("sup2")
16899 ("sup3")
16900 ("acute")
16901 ("micro")
16902 ("para")
16903 ("middot")
16904 ("odot"."o")
16905 ("star"."*")
16906 ("cedil")
16907 ("sup1")
16908 ("ordm")
16909 ("raquo")
16910 ("frac14")
16911 ("frac12")
16912 ("frac34")
16913 ("iquest")
16914 ("Agrave")
16915 ("Aacute")
16916 ("Acirc")
16917 ("Atilde")
16918 ("Auml")
16919 ("Aring") ("AA"."&Aring;")
16920 ("AElig")
16921 ("Ccedil")
16922 ("Egrave")
16923 ("Eacute")
16924 ("Ecirc")
16925 ("Euml")
16926 ("Igrave")
16927 ("Iacute")
16928 ("Icirc")
16929 ("Iuml")
16930 ("ETH")
16931 ("Ntilde")
16932 ("Ograve")
16933 ("Oacute")
16934 ("Ocirc")
16935 ("Otilde")
16936 ("Ouml")
16937 ("times")
16938 ("Oslash")
16939 ("Ugrave")
16940 ("Uacute")
16941 ("Ucirc")
16942 ("Uuml")
16943 ("Yacute")
16944 ("THORN")
16945 ("szlig")
16946 ("agrave")
16947 ("aacute")
16948 ("acirc")
16949 ("atilde")
16950 ("auml")
16951 ("aring")
16952 ("aelig")
16953 ("ccedil")
16954 ("egrave")
16955 ("eacute")
16956 ("ecirc")
16957 ("euml")
16958 ("igrave")
16959 ("iacute")
16960 ("icirc")
16961 ("iuml")
16962 ("eth")
16963 ("ntilde")
16964 ("ograve")
16965 ("oacute")
16966 ("ocirc")
16967 ("otilde")
16968 ("ouml")
16969 ("divide")
16970 ("oslash")
16971 ("ugrave")
16972 ("uacute")
16973 ("ucirc")
16974 ("uuml")
16975 ("yacute")
16976 ("thorn")
16977 ("yuml")
16978 ("fnof")
16979 ("Alpha")
16980 ("Beta")
16981 ("Gamma")
16982 ("Delta")
16983 ("Epsilon")
16984 ("Zeta")
16985 ("Eta")
16986 ("Theta")
16987 ("Iota")
16988 ("Kappa")
16989 ("Lambda")
16990 ("Mu")
16991 ("Nu")
16992 ("Xi")
16993 ("Omicron")
16994 ("Pi")
16995 ("Rho")
16996 ("Sigma")
16997 ("Tau")
16998 ("Upsilon")
16999 ("Phi")
17000 ("Chi")
17001 ("Psi")
17002 ("Omega")
17003 ("alpha")
17004 ("beta")
17005 ("gamma")
17006 ("delta")
17007 ("epsilon")
17008 ("varepsilon"."&epsilon;")
17009 ("zeta")
17010 ("eta")
17011 ("theta")
17012 ("iota")
17013 ("kappa")
17014 ("lambda")
17015 ("mu")
17016 ("nu")
17017 ("xi")
17018 ("omicron")
17019 ("pi")
17020 ("rho")
17021 ("sigmaf") ("varsigma"."&sigmaf;")
17022 ("sigma")
17023 ("tau")
17024 ("upsilon")
17025 ("phi")
17026 ("chi")
17027 ("psi")
17028 ("omega")
17029 ("thetasym") ("vartheta"."&thetasym;")
17030 ("upsih")
17031 ("piv")
17032 ("bull") ("bullet"."&bull;")
17033 ("hellip") ("dots"."&hellip;")
17034 ("prime")
17035 ("Prime")
17036 ("oline")
17037 ("frasl")
17038 ("weierp")
17039 ("image")
17040 ("real")
17041 ("trade")
17042 ("alefsym")
17043 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
17044 ("uarr") ("uparrow"."&uarr;")
17045 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
17046 ("darr")("downarrow"."&darr;")
17047 ("harr") ("leftrightarrow"."&harr;")
17048 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
17049 ("lArr") ("Leftarrow"."&lArr;")
17050 ("uArr") ("Uparrow"."&uArr;")
17051 ("rArr") ("Rightarrow"."&rArr;")
17052 ("dArr") ("Downarrow"."&dArr;")
17053 ("hArr") ("Leftrightarrow"."&hArr;")
17054 ("forall")
17055 ("part") ("partial"."&part;")
17056 ("exist") ("exists"."&exist;")
17057 ("empty") ("emptyset"."&empty;")
17058 ("nabla")
17059 ("isin") ("in"."&isin;")
17060 ("notin")
17061 ("ni")
17062 ("prod")
17063 ("sum")
17064 ("minus")
17065 ("lowast") ("ast"."&lowast;")
17066 ("radic")
17067 ("prop") ("proptp"."&prop;")
17068 ("infin") ("infty"."&infin;")
17069 ("ang") ("angle"."&ang;")
17070 ("and") ("vee"."&and;")
17071 ("or") ("wedge"."&or;")
17072 ("cap")
17073 ("cup")
17074 ("int")
17075 ("there4")
17076 ("sim")
17077 ("cong") ("simeq"."&cong;")
17078 ("asymp")("approx"."&asymp;")
17079 ("ne") ("neq"."&ne;")
17080 ("equiv")
17081 ("le")
17082 ("ge")
17083 ("sub") ("subset"."&sub;")
17084 ("sup") ("supset"."&sup;")
17085 ("nsub")
17086 ("sube")
17087 ("supe")
17088 ("oplus")
17089 ("otimes")
17090 ("perp")
17091 ("sdot") ("cdot"."&sdot;")
17092 ("lceil")
17093 ("rceil")
17094 ("lfloor")
17095 ("rfloor")
17096 ("lang")
17097 ("rang")
17098 ("loz") ("Diamond"."&loz;")
17099 ("spades") ("spadesuit"."&spades;")
17100 ("clubs") ("clubsuit"."&clubs;")
17101 ("hearts") ("diamondsuit"."&hearts;")
17102 ("diams") ("diamondsuit"."&diams;")
17103 ("quot")
17104 ("amp")
17105 ("lt")
17106 ("gt")
17107 ("OElig")
17108 ("oelig")
17109 ("Scaron")
17110 ("scaron")
17111 ("Yuml")
17112 ("circ")
17113 ("tilde")
17114 ("ensp")
17115 ("emsp")
17116 ("thinsp")
17117 ("zwnj")
17118 ("zwj")
17119 ("lrm")
17120 ("rlm")
17121 ("ndash")
17122 ("mdash")
17123 ("lsquo")
17124 ("rsquo")
17125 ("sbquo")
17126 ("ldquo")
17127 ("rdquo")
17128 ("bdquo")
17129 ("dagger")
17130 ("Dagger")
17131 ("permil")
17132 ("lsaquo")
17133 ("rsaquo")
17134 ("euro")
17136 ("arccos"."arccos")
17137 ("arcsin"."arcsin")
17138 ("arctan"."arctan")
17139 ("arg"."arg")
17140 ("cos"."cos")
17141 ("cosh"."cosh")
17142 ("cot"."cot")
17143 ("coth"."coth")
17144 ("csc"."csc")
17145 ("deg"."deg")
17146 ("det"."det")
17147 ("dim"."dim")
17148 ("exp"."exp")
17149 ("gcd"."gcd")
17150 ("hom"."hom")
17151 ("inf"."inf")
17152 ("ker"."ker")
17153 ("lg"."lg")
17154 ("lim"."lim")
17155 ("liminf"."liminf")
17156 ("limsup"."limsup")
17157 ("ln"."ln")
17158 ("log"."log")
17159 ("max"."max")
17160 ("min"."min")
17161 ("Pr"."Pr")
17162 ("sec"."sec")
17163 ("sin"."sin")
17164 ("sinh"."sinh")
17165 ("sup"."sup")
17166 ("tan"."tan")
17167 ("tanh"."tanh")
17169 "Entities for TeX->HTML translation.
17170 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
17171 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
17172 In that case, \"\\ent\" will be translated to \"&other;\".
17173 The list contains HTML entities for Latin-1, Greek and other symbols.
17174 It is supplemented by a number of commonly used TeX macros with appropriate
17175 translations. There is currently no way for users to extend this.")
17177 ;;; General functions for all backends
17179 (defun org-cleaned-string-for-export (string &rest parameters)
17180 "Cleanup a buffer substring so that links can be created safely."
17181 (interactive)
17182 (let* ((re-radio (and org-target-link-regexp
17183 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
17184 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
17185 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
17186 (re-archive (concat ":" org-archive-tag ":"))
17187 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
17188 (htmlp (plist-get parameters :for-html))
17189 (outline-regexp "\\*+")
17190 rtn)
17191 (save-excursion
17192 (set-buffer (get-buffer-create " org-mode-tmp"))
17193 (erase-buffer)
17194 (insert string)
17195 (let ((org-inhibit-startup t)) (org-mode))
17196 (untabify (point-min) (point-max))
17198 ;; Get the correct stuff before the first headline
17199 (when (plist-get parameters :skip-before-1st-heading)
17200 (goto-char (point-min))
17201 (when (re-search-forward "^\\*+[ \t]" nil t)
17202 (delete-region (point-min) (match-beginning 0))
17203 (goto-char (point-min))
17204 (insert "\n")))
17205 (when (plist-get parameters :add-text)
17206 (goto-char (point-min))
17207 (insert (plist-get parameters :add-text) "\n"))
17209 ;; Get rid of archived trees
17210 (when (not (eq org-export-with-archived-trees t))
17211 (goto-char (point-min))
17212 (while (re-search-forward re-archive nil t)
17213 (if (not (org-on-heading-p t))
17214 (org-end-of-subtree t)
17215 (beginning-of-line 1)
17216 (delete-region
17217 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
17218 (org-end-of-subtree t)))))
17220 ;; Protect stuff from HTML processing
17221 (goto-char (point-min))
17222 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
17223 (add-text-properties (match-beginning 0) (match-end 0)
17224 '(org-protected t)))
17225 (when htmlp
17226 (goto-char (point-min))
17227 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
17228 (replace-match "\\1" t)
17229 (add-text-properties
17230 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
17231 '(org-protected t))))
17232 (goto-char (point-min))
17233 (while (re-search-forward
17234 "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" nil t)
17235 (if htmlp
17236 (add-text-properties (match-beginning 1) (1+ (match-end 1))
17237 '(org-protected t))
17238 (delete-region (match-beginning 0) (match-end 0))))
17239 (goto-char (point-min))
17240 (while (re-search-forward re-quote nil t)
17241 (goto-char (match-beginning 0))
17242 (end-of-line 1)
17243 (add-text-properties (point) (org-end-of-subtree t)
17244 '(org-protected t)))
17246 ;; Find targets in comments and move them out of comments,
17247 ;; but mark them as targets that should be invisible
17248 (goto-char (point-min))
17249 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
17250 (replace-match "\\1(INVISIBLE)"))
17252 ;; Remove comments
17253 (goto-char (point-min))
17254 (while (re-search-forward "^#.*\n?" nil t)
17255 (replace-match ""))
17257 ;; Find matches for radio targets and turn them into internal links
17258 (goto-char (point-min))
17259 (when re-radio
17260 (while (re-search-forward re-radio nil t)
17261 (org-if-unprotected
17262 (replace-match "\\1[[\\2]]"))))
17264 ;; Find all links that contain a newline and put them into a single line
17265 (goto-char (point-min))
17266 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
17267 (org-if-unprotected
17268 (replace-match "\\1 \\3")
17269 (goto-char (match-beginning 0))))
17271 ;; Convert LaTeX fragments to images
17272 (when (plist-get parameters :LaTeX-fragments)
17273 (org-format-latex
17274 (concat "ltxpng/" (file-name-sans-extension
17275 (file-name-nondirectory
17276 org-current-export-file)))
17277 org-current-export-dir nil "Creating LaTeX image %s"))
17278 (message "Exporting...")
17280 ;; Normalize links: Convert angle and plain links into bracket links
17281 ;; Expand link abbreviations
17282 (goto-char (point-min))
17283 (while (re-search-forward re-plain-link nil t)
17284 (org-if-unprotected
17285 (replace-match
17286 (concat
17287 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17288 t t)))
17289 (goto-char (point-min))
17290 (while (re-search-forward re-angle-link nil t)
17291 (org-if-unprotected
17292 (replace-match
17293 (concat
17294 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17295 t t)))
17296 (goto-char (point-min))
17297 (while (re-search-forward org-bracket-link-regexp nil t)
17298 (org-if-unprotected
17299 (replace-match
17300 (concat "[[" (save-match-data
17301 (org-link-expand-abbrev (match-string 1)))
17303 (if (match-end 3)
17304 (match-string 2)
17305 (concat "[" (match-string 1) "]"))
17306 "]")
17307 t t)))
17309 ;; Find multiline emphasis and put them into single line
17310 (when (plist-get parameters :emph-multiline)
17311 (goto-char (point-min))
17312 (while (re-search-forward org-emph-re nil t)
17313 (org-if-unprotected
17314 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
17315 (goto-char (1- (match-end 0))))))
17317 (setq rtn (buffer-string)))
17318 (kill-buffer " org-mode-tmp")
17319 rtn))
17321 (defun org-solidify-link-text (s &optional alist)
17322 "Take link text and make a safe target out of it."
17323 (save-match-data
17324 (let* ((rtn
17325 (mapconcat
17326 'identity
17327 (org-split-string s "[ \t\r\n]+") "--"))
17328 (a (assoc rtn alist)))
17329 (or (cdr a) rtn))))
17331 ;; Variable holding the vector with section numbers
17332 (defvar org-section-numbers (make-vector org-level-max 0))
17334 (defun org-init-section-numbers ()
17335 "Initialize the vector for the section numbers."
17336 (let* ((level -1)
17337 (numbers (nreverse (org-split-string "" "\\.")))
17338 (depth (1- (length org-section-numbers)))
17339 (i depth) number-string)
17340 (while (>= i 0)
17341 (if (> i level)
17342 (aset org-section-numbers i 0)
17343 (setq number-string (or (car numbers) "0"))
17344 (if (string-match "\\`[A-Z]\\'" number-string)
17345 (aset org-section-numbers i
17346 (- (string-to-char number-string) ?A -1))
17347 (aset org-section-numbers i (string-to-number number-string)))
17348 (pop numbers))
17349 (setq i (1- i)))))
17351 (defun org-section-number (&optional level)
17352 "Return a string with the current section number.
17353 When LEVEL is non-nil, increase section numbers on that level."
17354 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
17355 (when level
17356 (when (> level -1)
17357 (aset org-section-numbers
17358 level (1+ (aref org-section-numbers level))))
17359 (setq idx (1+ level))
17360 (while (<= idx depth)
17361 (if (not (= idx 1))
17362 (aset org-section-numbers idx 0))
17363 (setq idx (1+ idx))))
17364 (setq idx 0)
17365 (while (<= idx depth)
17366 (setq n (aref org-section-numbers idx))
17367 (setq string (concat string (if (not (string= string "")) "." "")
17368 (int-to-string n)))
17369 (setq idx (1+ idx)))
17370 (save-match-data
17371 (if (string-match "\\`\\([@0]\\.\\)+" string)
17372 (setq string (replace-match "" t nil string)))
17373 (if (string-match "\\(\\.0\\)+\\'" string)
17374 (setq string (replace-match "" t nil string))))
17375 string))
17377 ;;; ASCII export
17379 (defvar org-last-level nil) ; dynamically scoped variable
17380 (defvar org-levels-open nil) ; dynamically scoped parameter
17381 (defvar org-ascii-current-indentation nil) ; For communication
17383 (defun org-export-as-ascii (arg)
17384 "Export the outline as a pretty ASCII file.
17385 If there is an active region, export only the region.
17386 The prefix ARG specifies how many levels of the outline should become
17387 underlined headlines. The default is 3."
17388 (interactive "P")
17389 (setq-default org-todo-line-regexp org-todo-line-regexp)
17390 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17391 (org-infile-export-plist)))
17392 (region
17393 (buffer-substring
17394 (if (org-region-active-p) (region-beginning) (point-min))
17395 (if (org-region-active-p) (region-end) (point-max))))
17396 (custom-times org-display-custom-times)
17397 (lines (org-skip-comments
17398 (org-split-string
17399 (org-cleaned-string-for-export
17400 region
17401 :skip-before-1st-heading
17402 (plist-get opt-plist :skip-before-1st-heading)
17403 :add-text (plist-get opt-plist :text))
17404 "[\r\n]")))
17405 (org-ascii-current-indentation '(0 . 0))
17406 (level 0) line txt
17407 (umax nil)
17408 (umax-toc nil)
17409 (case-fold-search nil)
17410 (filename (concat (file-name-as-directory
17411 (org-export-directory :ascii opt-plist))
17412 (file-name-sans-extension
17413 (file-name-nondirectory buffer-file-name))
17414 ".txt"))
17415 (buffer (find-file-noselect filename))
17416 (org-levels-open (make-vector org-level-max nil))
17417 (odd org-odd-levels-only)
17418 (date (format-time-string "%Y/%m/%d" (current-time)))
17419 (time (format-time-string "%X" (org-current-time)))
17420 (author (plist-get opt-plist :author))
17421 (title (or (plist-get opt-plist :title)
17422 (file-name-sans-extension
17423 (file-name-nondirectory buffer-file-name))))
17424 (email (plist-get opt-plist :email))
17425 (language (plist-get opt-plist :language))
17426 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17427 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17428 (todo nil)
17429 (lang-words nil)
17430 thetoc first-heading-pos)
17432 (setq org-last-level 1)
17433 (org-init-section-numbers)
17435 (find-file-noselect filename)
17437 (setq lang-words (or (assoc language org-export-language-setup)
17438 (assoc "en" org-export-language-setup)))
17439 (switch-to-buffer-other-window buffer)
17440 (erase-buffer)
17441 (fundamental-mode)
17442 ;; create local variables for all options, to make sure all called
17443 ;; functions get the correct information
17444 (mapcar (lambda (x)
17445 (set (make-local-variable (cdr x))
17446 (plist-get opt-plist (car x))))
17447 org-export-plist-vars)
17448 (org-set-local 'org-odd-levels-only odd)
17449 (setq umax (if arg (prefix-numeric-value arg)
17450 org-export-headline-levels))
17451 (setq umax-toc (if (integerp org-export-with-toc)
17452 (min org-export-with-toc umax)
17453 umax))
17455 ;; File header
17456 (if title (org-insert-centered title ?=))
17457 (insert "\n")
17458 (if (or author email)
17459 (insert (concat (nth 1 lang-words) ": " (or author "")
17460 (if email (concat " <" email ">") "")
17461 "\n")))
17462 (if (and date time)
17463 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17465 (insert "\n\n")
17467 (if org-export-with-toc
17468 (progn
17469 (push (concat (nth 3 lang-words) "\n") thetoc)
17470 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
17471 (mapcar '(lambda (line)
17472 (if (string-match org-todo-line-regexp
17473 line)
17474 ;; This is a headline
17475 (progn
17476 (setq level (- (match-end 1) (match-beginning 1))
17477 level (org-tr-level level)
17478 txt (match-string 3 line)
17479 todo
17480 (or (and org-export-mark-todo-in-toc
17481 (match-beginning 2)
17482 (not (member (match-string 2 line)
17483 org-done-keywords)))
17484 ; TODO, not DONE
17485 (and org-export-mark-todo-in-toc
17486 (= level umax-toc)
17487 (org-search-todo-below
17488 line lines level))))
17489 (setq txt (org-html-expand-for-ascii txt))
17491 (if (and (memq org-export-with-tags '(not-in-toc nil))
17492 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17493 (setq txt (replace-match "" t t txt)))
17494 (if (string-match quote-re0 txt)
17495 (setq txt (replace-match "" t t txt)))
17497 (if org-export-with-section-numbers
17498 (setq txt (concat (org-section-number level)
17499 " " txt)))
17500 (if (<= level umax-toc)
17501 (progn
17502 (push
17503 (concat
17504 (make-string (* (1- level) 4) ?\ )
17505 (format (if todo "%s (*)\n" "%s\n") txt))
17506 thetoc)
17507 (setq org-last-level level))
17508 ))))
17509 lines)
17510 (setq thetoc (nreverse thetoc))))
17512 (org-init-section-numbers)
17513 (while (setq line (pop lines))
17514 ;; Remove the quoted HTML tags.
17515 (setq line (org-html-expand-for-ascii line))
17516 ;; Remove targets
17517 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17518 (setq line (replace-match "" t t line)))
17519 ;; Replace internal links
17520 (while (string-match org-bracket-link-regexp line)
17521 (setq line (replace-match
17522 (if (match-end 3) "[\\3]" "[\\1]")
17523 t nil line)))
17524 (when custom-times
17525 (setq line (org-translate-time line)))
17526 (cond
17527 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17528 ;; a Headline
17529 (setq first-heading-pos (or first-heading-pos (point)))
17530 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17531 txt (match-string 2 line))
17532 (org-ascii-level-start level txt umax lines))
17534 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17535 (normal-mode)
17537 ;; insert the table of contents
17538 (when thetoc
17539 (goto-char (point-min))
17540 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
17541 (progn
17542 (goto-char (match-beginning 0))
17543 (replace-match ""))
17544 (goto-char first-heading-pos))
17545 (mapc 'insert thetoc)
17546 (or (looking-at "[ \t]*\n[ \t]*\n")
17547 (insert "\n\n")))
17549 (save-buffer)
17550 ;; remove display and invisible chars
17551 (let (beg end)
17552 (goto-char (point-min))
17553 (while (setq beg (next-single-property-change (point) 'display))
17554 (setq end (next-single-property-change beg 'display))
17555 (delete-region beg end)
17556 (goto-char beg)
17557 (insert "=>"))
17558 (goto-char (point-min))
17559 (while (setq beg (next-single-property-change (point) 'org-cwidth))
17560 (setq end (next-single-property-change beg 'org-cwidth))
17561 (delete-region beg end)
17562 (goto-char beg)))
17563 (goto-char (point-min))))
17565 (defun org-search-todo-below (line lines level)
17566 "Search the subtree below LINE for any TODO entries."
17567 (let ((rest (cdr (memq line lines)))
17568 (re org-todo-line-regexp)
17569 line lv todo)
17570 (catch 'exit
17571 (while (setq line (pop rest))
17572 (if (string-match re line)
17573 (progn
17574 (setq lv (- (match-end 1) (match-beginning 1))
17575 todo (and (match-beginning 2)
17576 (not (member (match-string 2 line)
17577 org-done-keywords))))
17578 ; TODO, not DONE
17579 (if (<= lv level) (throw 'exit nil))
17580 (if todo (throw 'exit t))))))))
17582 (defun org-html-expand-for-ascii (line)
17583 "Handle quoted HTML for ASCII export."
17584 (if org-export-html-expand
17585 (while (string-match "@<[^<>\n]*>" line)
17586 ;; We just remove the tags for now.
17587 (setq line (replace-match "" nil nil line))))
17588 line)
17590 (defun org-insert-centered (s &optional underline)
17591 "Insert the string S centered and underline it with character UNDERLINE."
17592 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17593 (insert (make-string ind ?\ ) s "\n")
17594 (if underline
17595 (insert (make-string ind ?\ )
17596 (make-string (string-width s) underline)
17597 "\n"))))
17599 (defun org-ascii-level-start (level title umax &optional lines)
17600 "Insert a new level in ASCII export."
17601 (let (char (n (- level umax 1)) (ind 0))
17602 (if (> level umax)
17603 (progn
17604 (insert (make-string (* 2 n) ?\ )
17605 (char-to-string (nth (% n (length org-export-ascii-bullets))
17606 org-export-ascii-bullets))
17607 " " title "\n")
17608 ;; find the indentation of the next non-empty line
17609 (catch 'stop
17610 (while lines
17611 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17612 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17613 (throw 'stop (setq ind (org-get-indentation (car lines)))))
17614 (pop lines)))
17615 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17616 (if (or (not (equal (char-before) ?\n))
17617 (not (equal (char-before (1- (point))) ?\n)))
17618 (insert "\n"))
17619 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17620 (unless org-export-with-tags
17621 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17622 (setq title (replace-match "" t t title))))
17623 (if org-export-with-section-numbers
17624 (setq title (concat (org-section-number level) " " title)))
17625 (insert title "\n" (make-string (string-width title) char) "\n")
17626 (setq org-ascii-current-indentation '(0 . 0)))))
17628 (defun org-export-visible (type arg)
17629 "Create a copy of the visible part of the current buffer, and export it.
17630 The copy is created in a temporary buffer and removed after use.
17631 TYPE is the final key (as a string) that also select the export command in
17632 the `C-c C-e' export dispatcher.
17633 As a special case, if the you type SPC at the prompt, the temporary
17634 org-mode file will not be removed but presented to you so that you can
17635 continue to use it. The prefix arg ARG is passed through to the exporting
17636 command."
17637 (interactive
17638 (list (progn
17639 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
17640 (read-char-exclusive))
17641 current-prefix-arg))
17642 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17643 (error "Invalid export key"))
17644 (let* ((binding (cdr (assoc type
17645 '((?a . org-export-as-ascii)
17646 (?\C-a . org-export-as-ascii)
17647 (?b . org-export-as-html-and-open)
17648 (?\C-b . org-export-as-html-and-open)
17649 (?h . org-export-as-html)
17650 (?x . org-export-as-xoxo)))))
17651 (keepp (equal type ?\ ))
17652 (file buffer-file-name)
17653 (buffer (get-buffer-create "*Org Export Visible*"))
17654 s e)
17655 (with-current-buffer buffer (erase-buffer))
17656 (save-excursion
17657 (setq s (goto-char (point-min)))
17658 (while (not (= (point) (point-max)))
17659 (goto-char (org-find-invisible))
17660 (append-to-buffer buffer s (point))
17661 (setq s (goto-char (org-find-visible))))
17662 (goto-char (point-min))
17663 (unless keepp
17664 ;; Copy all comment lines to the end, to make sure #+ settings are
17665 ;; still available for the second export step. Kind of a hack, but
17666 ;; does do the trick.
17667 (if (looking-at "#[^\r\n]*")
17668 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17669 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17670 (append-to-buffer buffer (1+ (match-beginning 0))
17671 (min (point-max) (1+ (match-end 0))))))
17672 (set-buffer buffer)
17673 (let ((buffer-file-name file)
17674 (org-inhibit-startup t))
17675 (org-mode)
17676 (show-all)
17677 (unless keepp (funcall binding arg))))
17678 (if (not keepp)
17679 (kill-buffer buffer)
17680 (switch-to-buffer-other-window buffer)
17681 (goto-char (point-min)))))
17683 (defun org-find-visible ()
17684 (let ((s (point)))
17685 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17686 (get-char-property s 'invisible)))
17688 (defun org-find-invisible ()
17689 (let ((s (point)))
17690 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17691 (not (get-char-property s 'invisible))))
17694 ;;; HTML export
17696 (defun org-get-current-options ()
17697 "Return a string with current options as keyword options.
17698 Does include HTML export options as well as TODO and CATEGORY stuff."
17699 (format
17700 "#+TITLE: %s
17701 #+AUTHOR: %s
17702 #+EMAIL: %s
17703 #+LANGUAGE: %s
17704 #+TEXT: Some descriptive text to be emitted. Several lines OK.
17705 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s skip:%s
17706 #+CATEGORY: %s
17707 #+SEQ_TODO: %s
17708 #+TYP_TODO: %s
17709 #+STARTUP: %s %s %s %s %s
17710 #+TAGS: %s
17711 #+ARCHIVE: %s
17712 #+LINK: %s
17714 (buffer-name) (user-full-name) user-mail-address org-export-default-language
17715 org-export-headline-levels
17716 org-export-with-section-numbers
17717 org-export-with-toc
17718 org-export-preserve-breaks
17719 org-export-html-expand
17720 org-export-with-fixed-width
17721 org-export-with-tables
17722 org-export-with-sub-superscripts
17723 org-export-with-emphasize
17724 org-export-with-TeX-macros
17725 org-export-with-LaTeX-fragments
17726 org-export-skip-text-before-1st-heading
17727 (file-name-nondirectory buffer-file-name)
17728 "TODO FEEDBACK VERIFY DONE"
17729 "Me Jason Marie DONE"
17730 (cdr (assoc org-startup-folded
17731 '((nil . "showall") (t . "overview") (content . "content"))))
17732 (if org-odd-levels-only "odd" "oddeven")
17733 (if org-hide-leading-stars "hidestars" "showstars")
17734 (if org-startup-align-all-tables "align" "noalign")
17735 (cond ((eq t org-log-done) "logdone")
17736 ((not org-log-done) "nologging")
17737 ((listp org-log-done)
17738 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
17739 org-log-done " ")))
17740 (or (mapconcat (lambda (x)
17741 (cond
17742 ((equal '(:startgroup) x) "{")
17743 ((equal '(:endgroup) x) "}")
17744 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
17745 (t (car x))))
17746 (or org-tag-alist (org-get-buffer-tags)) " ") "")
17747 org-archive-location
17748 "org file:~/org/%s.org"
17751 (defun org-insert-export-options-template ()
17752 "Insert into the buffer a template with information for exporting."
17753 (interactive)
17754 (if (not (bolp)) (newline))
17755 (let ((s (org-get-current-options)))
17756 (and (string-match "#\\+CATEGORY" s)
17757 (setq s (substring s 0 (match-beginning 0))))
17758 (insert s)))
17760 (defun org-toggle-fixed-width-section (arg)
17761 "Toggle the fixed-width export.
17762 If there is no active region, the QUOTE keyword at the current headline is
17763 inserted or removed. When present, it causes the text between this headline
17764 and the next to be exported as fixed-width text, and unmodified.
17765 If there is an active region, this command adds or removes a colon as the
17766 first character of this line. If the first character of a line is a colon,
17767 this line is also exported in fixed-width font."
17768 (interactive "P")
17769 (let* ((cc 0)
17770 (regionp (org-region-active-p))
17771 (beg (if regionp (region-beginning) (point)))
17772 (end (if regionp (region-end)))
17773 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17774 (re "[ \t]*\\(:\\)")
17775 off)
17776 (if regionp
17777 (save-excursion
17778 (goto-char beg)
17779 (setq cc (current-column))
17780 (beginning-of-line 1)
17781 (setq off (looking-at re))
17782 (while (> nlines 0)
17783 (setq nlines (1- nlines))
17784 (beginning-of-line 1)
17785 (cond
17786 (arg
17787 (move-to-column cc t)
17788 (insert ":\n")
17789 (forward-line -1))
17790 ((and off (looking-at re))
17791 (replace-match "" t t nil 1))
17792 ((not off) (move-to-column cc t) (insert ":")))
17793 (forward-line 1)))
17794 (save-excursion
17795 (org-back-to-heading)
17796 (if (looking-at (concat outline-regexp
17797 "\\( +\\<" org-quote-string "\\>\\)"))
17798 (replace-match "" t t nil 1)
17799 (if (looking-at outline-regexp)
17800 (progn
17801 (goto-char (match-end 0))
17802 (insert " " org-quote-string))))))))
17804 (defun org-export-as-html-and-open (arg)
17805 "Export the outline as HTML and immediately open it with a browser.
17806 If there is an active region, export only the region.
17807 The prefix ARG specifies how many levels of the outline should become
17808 headlines. The default is 3. Lower levels will become bulleted lists."
17809 (interactive "P")
17810 (org-export-as-html arg 'hidden)
17811 (org-open-file buffer-file-name))
17813 (defun org-export-as-html-batch ()
17814 "Call `org-export-as-html', may be used in batch processing as
17815 emacs --batch
17816 --load=$HOME/lib/emacs/org.el
17817 --eval \"(setq org-export-headline-levels 2)\"
17818 --visit=MyFile --funcall org-export-as-html-batch"
17819 (org-export-as-html org-export-headline-levels 'hidden))
17821 (defun org-export-as-html (arg &optional hidden ext-plist)
17822 "Export the outline as a pretty HTML file.
17823 If there is an active region, export only the region.
17824 The prefix ARG specifies how many levels of the outline should become
17825 headlines. The default is 3. Lower levels will become bulleted lists.
17826 When HIDDEN is non-nil, don't display the HTML buffer.
17827 EXT-PLIST is a property list with external parameters overriding
17828 org-mode's default settings, but still inferior to file-local settings."
17829 (interactive "P")
17830 (message "Exporting...")
17831 (setq-default org-todo-line-regexp org-todo-line-regexp)
17832 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
17833 (setq-default org-done-keywords org-done-keywords)
17834 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
17835 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17836 ext-plist
17837 (org-infile-export-plist)))
17839 (style (plist-get opt-plist :style))
17840 (link-validate (plist-get opt-plist :link-validation-function))
17841 valid thetoc first-heading-pos
17842 (odd org-odd-levels-only)
17843 (region-p (org-region-active-p))
17844 (region
17845 (buffer-substring
17846 (if region-p (region-beginning) (point-min))
17847 (if region-p (region-end) (point-max))))
17848 ;; The following two are dynamically scoped into other
17849 ;; routines below.
17850 (org-current-export-dir (org-export-directory :html opt-plist))
17851 (org-current-export-file buffer-file-name)
17852 (lines
17853 (org-skip-comments (org-split-string
17854 (org-cleaned-string-for-export
17855 region
17856 :emph-multiline t
17857 :for-html t
17858 :skip-before-1st-heading
17859 (plist-get opt-plist :skip-before-1st-heading)
17860 :add-text
17861 (plist-get opt-plist :text)
17862 :LaTeX-fragments
17863 (plist-get opt-plist :LaTeX-fragments))
17864 "[\r\n]")))
17865 (level 0) (line "") (origline "") txt todo
17866 (umax nil)
17867 (umax-toc nil)
17868 (filename (concat (file-name-as-directory
17869 (org-export-directory :html opt-plist))
17870 (file-name-sans-extension
17871 (file-name-nondirectory buffer-file-name))
17872 ".html"))
17873 (current-dir (file-name-directory buffer-file-name))
17874 (buffer (find-file-noselect filename))
17875 (org-levels-open (make-vector org-level-max nil))
17876 (date (format-time-string "%Y/%m/%d" (current-time)))
17877 (time (format-time-string "%X" (org-current-time)))
17878 (author (plist-get opt-plist :author))
17879 (title (or (plist-get opt-plist :title)
17880 (file-name-sans-extension
17881 (file-name-nondirectory buffer-file-name))))
17882 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17883 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17884 (inquote nil)
17885 (infixed nil)
17886 (in-local-list nil)
17887 (local-list-num nil)
17888 (local-list-indent nil)
17889 (llt org-plain-list-ordered-item-terminator)
17890 (email (plist-get opt-plist :email))
17891 (language (plist-get opt-plist :language))
17892 (lang-words nil)
17893 (target-alist nil) tg
17894 (head-count 0) cnt
17895 (start 0)
17896 (coding-system (and (boundp 'buffer-file-coding-system)
17897 buffer-file-coding-system))
17898 (coding-system-for-write coding-system)
17899 (save-buffer-coding-system coding-system)
17900 (charset (and coding-system
17901 (fboundp 'coding-system-get)
17902 (coding-system-get coding-system 'mime-charset)))
17903 table-open type
17904 table-buffer table-orig-buffer
17905 ind start-is-num starter didclose
17906 rpl path desc descp desc1 desc2 link
17908 (message "Exporting...")
17910 (setq org-last-level 1)
17911 (org-init-section-numbers)
17913 ;; Get the language-dependent settings
17914 (setq lang-words (or (assoc language org-export-language-setup)
17915 (assoc "en" org-export-language-setup)))
17917 ;; Switch to the output buffer
17918 (if (or hidden t)
17919 (set-buffer buffer)
17920 (switch-to-buffer-other-window buffer))
17921 (erase-buffer)
17922 (fundamental-mode)
17923 (let ((case-fold-search nil)
17924 (org-odd-levels-only odd))
17925 ;; create local variables for all options, to make sure all called
17926 ;; functions get the correct information
17927 (mapcar (lambda (x)
17928 (set (make-local-variable (cdr x))
17929 (plist-get opt-plist (car x))))
17930 org-export-plist-vars)
17931 (setq umax (if arg (prefix-numeric-value arg)
17932 org-export-headline-levels))
17933 (setq umax-toc (if (integerp org-export-with-toc)
17934 (min org-export-with-toc umax)
17935 umax))
17936 ;; File header
17937 (insert (format
17938 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
17939 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
17940 <html xmlns=\"http://www.w3.org/1999/xhtml\"
17941 lang=\"%s\" xml:lang=\"%s\">
17942 <head>
17943 <title>%s</title>
17944 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
17945 <meta name=\"generator\" content=\"Org-mode\"/>
17946 <meta name=\"generated\" content=\"%s %s\"/>
17947 <meta name=\"author\" content=\"%s\"/>
17949 </head><body>
17951 language language (org-html-expand title) (or charset "iso-8859-1")
17952 date time author style))
17955 (insert (or (plist-get opt-plist :preamble) ""))
17957 (when (plist-get opt-plist :auto-preamble)
17958 (if title (insert (format org-export-html-title-format
17959 (org-html-expand title)))))
17961 (if org-export-with-toc
17962 (progn
17963 (push (format "<h%d>%s</h%d>\n"
17964 org-export-html-toplevel-hlevel
17965 (nth 3 lang-words)
17966 org-export-html-toplevel-hlevel)
17967 thetoc)
17968 (push "<ul>\n<li>" thetoc)
17969 (setq lines
17970 (mapcar '(lambda (line)
17971 (if (string-match org-todo-line-regexp line)
17972 ;; This is a headline
17973 (progn
17974 (setq level (- (match-end 1) (match-beginning 1))
17975 level (org-tr-level level)
17976 txt (save-match-data
17977 (org-html-expand
17978 (org-export-cleanup-toc-line
17979 (match-string 3 line))))
17980 todo
17981 (or (and org-export-mark-todo-in-toc
17982 (match-beginning 2)
17983 (not (member (match-string 2 line)
17984 org-done-keywords)))
17985 ; TODO, not DONE
17986 (and org-export-mark-todo-in-toc
17987 (= level umax-toc)
17988 (org-search-todo-below
17989 line lines level))))
17990 (if (and (memq org-export-with-tags '(not-in-toc nil))
17991 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17992 (setq txt (replace-match "" t t txt)))
17993 (if (string-match quote-re0 txt)
17994 (setq txt (replace-match "" t t txt)))
17995 (if org-export-with-section-numbers
17996 (setq txt (concat (org-section-number level)
17997 " " txt)))
17998 (if (<= level umax-toc)
17999 (progn
18000 (setq head-count (+ head-count 1))
18001 (if (> level org-last-level)
18002 (progn
18003 (setq cnt (- level org-last-level))
18004 (while (>= (setq cnt (1- cnt)) 0)
18005 (push "\n<ul>\n<li>" thetoc))
18006 (push "\n" thetoc)))
18007 (if (< level org-last-level)
18008 (progn
18009 (setq cnt (- org-last-level level))
18010 (while (>= (setq cnt (1- cnt)) 0)
18011 (push "</li>\n</ul>" thetoc))
18012 (push "\n" thetoc)))
18013 ;; Check for targets
18014 (while (string-match org-target-regexp line)
18015 (setq tg (match-string 1 line)
18016 line (replace-match
18017 (concat "@<span class=\"target\">" tg "@</span> ")
18018 t t line))
18019 (push (cons (org-solidify-link-text tg)
18020 (format "sec-%d" head-count))
18021 target-alist))
18022 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
18023 (setq txt (replace-match "" t t txt)))
18024 (push
18025 (format
18026 (if todo
18027 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
18028 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
18029 head-count txt) thetoc)
18031 (setq org-last-level level))
18033 line)
18034 lines))
18035 (while (> org-last-level 0)
18036 (setq org-last-level (1- org-last-level))
18037 (push "</li>\n</ul>\n" thetoc))
18038 (setq thetoc (nreverse thetoc))))
18039 (setq head-count 0)
18040 (org-init-section-numbers)
18042 (while (setq line (pop lines) origline line)
18043 (catch 'nextline
18045 ;; end of quote section?
18046 (when (and inquote (string-match "^\\*+" line))
18047 (insert "</pre>\n")
18048 (setq inquote nil))
18049 ;; inside a quote section?
18050 (when inquote
18051 (insert (org-html-protect line) "\n")
18052 (throw 'nextline nil))
18054 ;; verbatim lines
18055 (when (and org-export-with-fixed-width
18056 (string-match "^[ \t]*:\\(.*\\)" line))
18057 (when (not infixed)
18058 (setq infixed t)
18059 (insert "<pre>\n"))
18060 (insert (org-html-protect (match-string 1 line)) "\n")
18061 (when (and lines
18062 (not (string-match "^[ \t]*\\(:.*\\)"
18063 (car lines))))
18064 (setq infixed nil)
18065 (insert "</pre>\n"))
18066 (throw 'nextline nil))
18068 ;; Protected HTML
18069 (when (get-text-property 0 'org-protected line)
18070 (let (par)
18071 (when (re-search-backward
18072 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
18073 (setq par (match-string 1))
18074 (replace-match "\\2\n"))
18075 (insert line "\n")
18076 (while (and lines
18077 (get-text-property 0 'org-protected (car lines)))
18078 (insert (pop lines) "\n"))
18079 (and par (insert "<p>\n")))
18080 (throw 'nextline nil))
18082 ;; Horizontal line
18083 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
18084 (insert "\n<hr/>\n")
18085 (throw 'nextline nil))
18087 ;; make targets to anchors
18088 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
18089 (cond
18090 ((match-end 2)
18091 (setq line (replace-match
18092 (concat "@<a name=\""
18093 (org-solidify-link-text (match-string 1 line))
18094 "\">\\nbsp@</a>")
18095 t t line)))
18096 ((and org-export-with-toc (equal (string-to-char line) ?*))
18097 (setq line (replace-match
18098 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
18099 ; (concat "@<i>" (match-string 1 line) "@</i> ")
18100 t t line)))
18102 (setq line (replace-match
18103 (concat "@<a name=\""
18104 (org-solidify-link-text (match-string 1 line))
18105 "\" class=\"target\">" (match-string 1 line) "@</a> ")
18106 t t line)))))
18108 (setq line (org-html-handle-time-stamps line))
18110 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
18111 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
18112 ;; Also handle sub_superscripts and checkboxes
18113 (setq line (org-html-expand line))
18115 ;; Format the links
18116 (setq start 0)
18117 (while (string-match org-bracket-link-analytic-regexp line start)
18118 (setq start (match-beginning 0))
18119 (setq type (if (match-end 2) (match-string 2 line) "internal"))
18120 (setq path (match-string 3 line))
18121 (setq desc1 (if (match-end 5) (match-string 5 line))
18122 desc2 (if (match-end 2) (concat type ":" path) path)
18123 descp (and desc1 (not (equal desc1 desc2)))
18124 desc (or desc1 desc2))
18125 ;; Make an image out of the description if that is so wanted
18126 (when (and descp (org-file-image-p desc))
18127 (save-match-data
18128 (if (string-match "^file:" desc)
18129 (setq desc (substring desc (match-end 0)))))
18130 (setq desc (concat "<img src=\"" desc "\"/>")))
18131 ;; FIXME: do we need to unescape here somewhere?
18132 (cond
18133 ((equal type "internal")
18134 (setq rpl
18135 (concat
18136 "<a href=\"#"
18137 (org-solidify-link-text path target-alist)
18138 "\">" desc "</a>")))
18139 ((member type '("http" "https")) ; FIXME: need to test this.
18140 ;; standard URL, just check if we need to inline an image
18141 (if (and (or (eq t org-export-html-inline-images)
18142 (and org-export-html-inline-images (not descp)))
18143 (org-file-image-p path))
18144 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
18145 (setq link (concat type ":" path))
18146 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
18147 ((member type '("ftp" "mailto" "news"))
18148 ;; standard URL
18149 (setq link (concat type ":" path))
18150 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
18151 ((string= type "file")
18152 ;; FILE link
18153 (let* ((filename path)
18154 (abs-p (file-name-absolute-p filename))
18155 thefile file-is-image-p search)
18156 (save-match-data
18157 (if (string-match "::\\(.*\\)" filename)
18158 (setq search (match-string 1 filename)
18159 filename (replace-match "" t nil filename)))
18160 (setq valid
18161 (if (functionp link-validate)
18162 (funcall link-validate filename current-dir)
18164 (setq file-is-image-p (org-file-image-p filename))
18165 (setq thefile (if abs-p (expand-file-name filename) filename))
18166 (when (and org-export-html-link-org-files-as-html
18167 (string-match "\\.org$" thefile))
18168 (setq thefile (concat (substring thefile 0
18169 (match-beginning 0))
18170 ".html"))
18171 (if (and search
18172 ;; make sure this is can be used as target search
18173 (not (string-match "^[0-9]*$" search))
18174 (not (string-match "^\\*" search))
18175 (not (string-match "^/.*/$" search)))
18176 (setq thefile (concat thefile "#"
18177 (org-solidify-link-text
18178 (org-link-unescape search)))))
18179 (when (string-match "^file:" desc)
18180 (setq desc (replace-match "" t t desc))
18181 (if (string-match "\\.org$" desc)
18182 (setq desc (replace-match "" t t desc))))))
18183 (setq rpl (if (and file-is-image-p
18184 (or (eq t org-export-html-inline-images)
18185 (and org-export-html-inline-images
18186 (not descp))))
18187 (concat "<img src=\"" thefile "\"/>")
18188 (concat "<a href=\"" thefile "\">" desc "</a>")))
18189 (if (not valid) (setq rpl desc))))
18190 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
18191 (setq rpl (concat "<i>&lt;" type ":"
18192 (save-match-data (org-link-unescape path))
18193 "&gt;</i>"))))
18194 (setq line (replace-match rpl t t line)
18195 start (+ start (length rpl))))
18196 ;; TODO items
18197 (if (and (string-match org-todo-line-regexp line)
18198 (match-beginning 2))
18199 (if (member (match-string 2 line) org-done-keywords)
18200 (setq line (replace-match
18201 "<span class=\"done\">\\2</span>"
18202 t nil line 2))
18203 (setq line (replace-match "<span class=\"todo\">\\2</span>"
18204 t nil line 2))))
18206 (cond
18207 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
18208 ;; This is a headline
18209 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
18210 txt (match-string 2 line))
18211 (if (string-match quote-re0 txt)
18212 (setq txt (replace-match "" t t txt)))
18213 (if (<= level umax) (setq head-count (+ head-count 1)))
18214 (when in-local-list
18215 ;; Close any local lists before inserting a new header line
18216 (while local-list-num
18217 (org-close-li)
18218 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18219 (pop local-list-num))
18220 (setq local-list-indent nil
18221 in-local-list nil))
18222 (setq first-heading-pos (or first-heading-pos (point)))
18223 (org-html-level-start level txt umax
18224 (and org-export-with-toc (<= level umax))
18225 head-count)
18226 ;; QUOTES
18227 (when (string-match quote-re line)
18228 (insert "<pre>")
18229 (setq inquote t)))
18231 ((and org-export-with-tables
18232 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
18233 (if (not table-open)
18234 ;; New table starts
18235 (setq table-open t table-buffer nil table-orig-buffer nil))
18236 ;; Accumulate lines
18237 (setq table-buffer (cons line table-buffer)
18238 table-orig-buffer (cons origline table-orig-buffer))
18239 (when (or (not lines)
18240 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
18241 (car lines))))
18242 (setq table-open nil
18243 table-buffer (nreverse table-buffer)
18244 table-orig-buffer (nreverse table-orig-buffer))
18245 (org-close-par-maybe)
18246 (insert (org-format-table-html table-buffer table-orig-buffer))))
18248 ;; Normal lines
18249 (when (string-match
18250 (cond
18251 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18252 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18253 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18254 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
18255 line)
18256 (setq ind (org-get-string-indentation line)
18257 start-is-num (match-beginning 4)
18258 starter (if (match-beginning 2)
18259 (substring (match-string 2 line) 0 -1))
18260 line (substring line (match-beginning 5)))
18261 (unless (string-match "[^ \t]" line)
18262 ;; empty line. Pretend indentation is large.
18263 (setq ind (if org-empty-line-terminates-plain-lists
18265 (1+ (or (car local-list-indent) 1)))))
18266 (setq didclose nil)
18267 (while (and in-local-list
18268 (or (and (= ind (car local-list-indent))
18269 (not starter))
18270 (< ind (car local-list-indent))))
18271 (setq didclose t)
18272 (org-close-li)
18273 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18274 (pop local-list-num) (pop local-list-indent)
18275 (setq in-local-list local-list-indent))
18276 (cond
18277 ((and starter
18278 (or (not in-local-list)
18279 (> ind (car local-list-indent))))
18280 ;; Start new (level of) list
18281 (org-close-par-maybe)
18282 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
18283 (push start-is-num local-list-num)
18284 (push ind local-list-indent)
18285 (setq in-local-list t))
18286 (starter
18287 ;; continue current list
18288 (org-close-li)
18289 (insert "<li>\n"))
18290 (didclose
18291 ;; we did close a list, normal text follows: need <p>
18292 (org-open-par)))
18293 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
18294 (setq line
18295 (replace-match
18296 (if (equal (match-string 1 line) "X")
18297 "<b>[X]</b>"
18298 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
18299 t t line))))
18301 ;; Empty lines start a new paragraph. If hand-formatted lists
18302 ;; are not fully interpreted, lines starting with "-", "+", "*"
18303 ;; also start a new paragraph.
18304 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
18306 ;; Check if the line break needs to be conserved
18307 (cond
18308 ((string-match "\\\\\\\\[ \t]*$" line)
18309 (setq line (replace-match "<br/>" t t line)))
18310 (org-export-preserve-breaks
18311 (setq line (concat line "<br/>"))))
18313 (insert line "\n")))))
18315 ;; Properly close all local lists and other lists
18316 (when inquote (insert "</pre>\n"))
18317 (when in-local-list
18318 ;; Close any local lists before inserting a new header line
18319 (while local-list-num
18320 (org-close-li)
18321 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
18322 (pop local-list-num))
18323 (setq local-list-indent nil
18324 in-local-list nil))
18325 (org-html-level-start 1 nil umax
18326 (and org-export-with-toc (<= level umax))
18327 head-count)
18329 (when (plist-get opt-plist :auto-postamble)
18330 (when author
18331 (insert "<p class=\"author\"> "
18332 (nth 1 lang-words) ": " author "\n")
18333 (when email
18334 (insert "<a href=\"mailto:" email "\">&lt;"
18335 email "&gt;</a>\n"))
18336 (insert "</p>\n"))
18337 (when (and date time)
18338 (insert "<p class=\"date\"> "
18339 (nth 2 lang-words) ": "
18340 date " " time "</p>\n")))
18342 (if org-export-html-with-timestamp
18343 (insert org-export-html-html-helper-timestamp))
18344 (insert (or (plist-get opt-plist :postamble) ""))
18345 (insert "</body>\n</html>\n")
18346 (normal-mode)
18347 ;; insert the table of contents
18348 (goto-char (point-min))
18349 (when thetoc
18350 (if (or (re-search-forward
18351 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
18352 (re-search-forward
18353 "\\[TABLE-OF-CONTENTS\\]" nil t))
18354 (progn
18355 (goto-char (match-beginning 0))
18356 (replace-match ""))
18357 (goto-char first-heading-pos)
18358 (when (looking-at "\\s-*</p>")
18359 (goto-char (match-end 0))
18360 (insert "\n")))
18361 (mapc 'insert thetoc))
18362 ;; remove empty paragraphs and lists
18363 (goto-char (point-min))
18364 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
18365 (replace-match ""))
18366 (goto-char (point-min))
18367 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
18368 (replace-match ""))
18369 (save-buffer)
18370 (goto-char (point-min))
18371 (message "Exporting... done"))))
18374 (defun org-format-table-html (lines olines)
18375 "Find out which HTML converter to use and return the HTML code."
18376 (if (string-match "^[ \t]*|" (car lines))
18377 ;; A normal org table
18378 (org-format-org-table-html lines)
18379 ;; Table made by table.el - test for spanning
18380 (let* ((hlines (delq nil (mapcar
18381 (lambda (x)
18382 (if (string-match "^[ \t]*\\+-" x) x
18383 nil))
18384 lines)))
18385 (first (car hlines))
18386 (ll (and (string-match "\\S-+" first)
18387 (match-string 0 first)))
18388 (re (concat "^[ \t]*" (regexp-quote ll)))
18389 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
18390 hlines))))
18391 (if (and (not spanning)
18392 (not org-export-prefer-native-exporter-for-tables))
18393 ;; We can use my own converter with HTML conversions
18394 (org-format-table-table-html lines)
18395 ;; Need to use the code generator in table.el, with the original text.
18396 (org-format-table-table-html-using-table-generate-source olines)))))
18398 (defun org-format-org-table-html (lines &optional splice)
18399 "Format a table into HTML."
18400 ;; Get rid of hlines at beginning and end
18401 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18402 (setq lines (nreverse lines))
18403 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18404 (setq lines (nreverse lines))
18405 (when org-export-table-remove-special-lines
18406 ;; Check if the table has a marking column. If yes remove the
18407 ;; column and the special lines
18408 (setq lines (org-table-clean-before-export lines)))
18410 (let ((head (and org-export-highlight-first-table-line
18411 (delq nil (mapcar
18412 (lambda (x) (string-match "^[ \t]*|-" x))
18413 (cdr lines)))))
18414 (nlines 0) fnum i
18415 tbopen line fields html)
18416 (if splice (setq head nil))
18417 (unless splice (push (if head "<thead>" "<tbody>") html))
18418 (setq tbopen t)
18419 (while (setq line (pop lines))
18420 (catch 'next-line
18421 (if (string-match "^[ \t]*|-" line)
18422 (progn
18423 (unless splice
18424 (push (if head "</thead>" "</tbody>") html)
18425 (if lines (push "<tbody>" html) (setq tbopen nil)))
18426 (setq head nil) ;; head ends here, first time around
18427 ;; ignore this line
18428 (throw 'next-line t)))
18429 ;; Break the line into fields
18430 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18431 (unless fnum (setq fnum (make-vector (length fields) 0)))
18432 (setq nlines (1+ nlines) i -1)
18433 (push (concat "<tr>"
18434 (mapconcat
18435 (lambda (x)
18436 (setq i (1+ i))
18437 (if (and (< i nlines)
18438 (string-match org-table-number-regexp x))
18439 (incf (aref fnum i)))
18440 (if head
18441 (concat "<th>" x "</th>")
18442 (concat "<td>" x "</td>")))
18443 fields "")
18444 "</tr>")
18445 html)))
18446 (unless splice (if tbopen (push "</tbody>" html)))
18447 (unless splice (push "</table>\n" html))
18448 (setq html (nreverse html))
18449 (unless splice
18450 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
18451 (push (mapconcat
18452 (lambda (x)
18453 (format "<COL align=\"%s\">"
18454 (if (> (/ (float x) nlines) org-table-number-fraction)
18455 "right" "left")))
18456 fnum "")
18457 html)
18458 (push org-export-html-table-tag html))
18459 (concat (mapconcat 'identity html "\n") "\n")))
18461 (defun org-table-clean-before-export (lines)
18462 "Check if the table has a marking column.
18463 If yes remove the column and the special lines."
18464 (if (memq nil
18465 (mapcar
18466 (lambda (x) (or (string-match "^[ \t]*|-" x)
18467 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
18468 lines))
18469 (progn
18470 (setq org-table-clean-did-remove-column-1 nil)
18471 lines)
18472 (setq org-table-clean-did-remove-column-1 t)
18473 (delq nil
18474 (mapcar
18475 (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
18476 nil ; ignore this line
18477 (and (or (string-match "^[ \t]*|-+\\+" x)
18478 (string-match "^[ \t]*|[^|]*|" x))
18479 (replace-match "|" t t x))))
18480 lines))))
18482 (defun org-format-table-table-html (lines)
18483 "Format a table generated by table.el into HTML.
18484 This conversion does *not* use `table-generate-source' from table.el.
18485 This has the advantage that Org-mode's HTML conversions can be used.
18486 But it has the disadvantage, that no cell- or row-spanning is allowed."
18487 (let (line field-buffer
18488 (head org-export-highlight-first-table-line)
18489 fields html empty)
18490 (setq html (concat org-export-html-table-tag "\n"))
18491 (while (setq line (pop lines))
18492 (setq empty "&nbsp;")
18493 (catch 'next-line
18494 (if (string-match "^[ \t]*\\+-" line)
18495 (progn
18496 (if field-buffer
18497 (progn
18498 (setq html (concat
18499 html
18500 "<tr>"
18501 (mapconcat
18502 (lambda (x)
18503 (if (equal x "") (setq x empty))
18504 (if head
18505 (concat "<th>" x "</th>\n")
18506 (concat "<td>" x "</td>\n")))
18507 field-buffer "\n")
18508 "</tr>\n"))
18509 (setq head nil)
18510 (setq field-buffer nil)))
18511 ;; Ignore this line
18512 (throw 'next-line t)))
18513 ;; Break the line into fields and store the fields
18514 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18515 (if field-buffer
18516 (setq field-buffer (mapcar
18517 (lambda (x)
18518 (concat x "<br/>" (pop fields)))
18519 field-buffer))
18520 (setq field-buffer fields))))
18521 (setq html (concat html "</table>\n"))
18522 html))
18524 (defun org-format-table-table-html-using-table-generate-source (lines)
18525 "Format a table into html, using `table-generate-source' from table.el.
18526 This has the advantage that cell- or row-spanning is allowed.
18527 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18528 (require 'table)
18529 (with-current-buffer (get-buffer-create " org-tmp1 ")
18530 (erase-buffer)
18531 (insert (mapconcat 'identity lines "\n"))
18532 (goto-char (point-min))
18533 (if (not (re-search-forward "|[^+]" nil t))
18534 (error "Error processing table"))
18535 (table-recognize-table)
18536 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18537 (table-generate-source 'html " org-tmp2 ")
18538 (set-buffer " org-tmp2 ")
18539 (buffer-substring (point-min) (point-max))))
18541 (defun org-html-handle-time-stamps (s)
18542 "Format time stamps in string S, or remove them."
18543 (catch 'exit
18544 (let (r b)
18545 (while (string-match org-maybe-keyword-time-regexp s)
18546 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18547 ;; never export CLOCK
18548 (throw 'exit ""))
18549 (or b (setq b (substring s 0 (match-beginning 0))))
18550 (if (not org-export-with-timestamps)
18551 (setq r (concat r (substring s 0 (match-beginning 0)))
18552 s (substring s (match-end 0)))
18553 (setq r (concat
18554 r (substring s 0 (match-beginning 0))
18555 (if (match-end 1)
18556 (format "@<span class=\"timestamp-kwd\">%s @</span>"
18557 (match-string 1 s)))
18558 (format " @<span class=\"timestamp\">%s@</span>"
18559 (substring
18560 (org-translate-time (match-string 3 s)) 1 -1)))
18561 s (substring s (match-end 0)))))
18562 ;; Line break if line started and ended with time stamp stuff
18563 (if (not r)
18565 (setq r (concat r s))
18566 (unless (string-match "\\S-" (concat b s))
18567 (setq r (concat r "@<br/>")))
18568 r))))
18570 (defun org-html-protect (s)
18571 ;; convert & to &amp;, < to &lt; and > to &gt;
18572 (let ((start 0))
18573 (while (string-match "&" s start)
18574 (setq s (replace-match "&amp;" t t s)
18575 start (1+ (match-beginning 0))))
18576 (while (string-match "<" s)
18577 (setq s (replace-match "&lt;" t t s)))
18578 (while (string-match ">" s)
18579 (setq s (replace-match "&gt;" t t s))))
18582 (defun org-export-cleanup-toc-line (s)
18583 "Remove tags and time staps from lines going into the toc."
18584 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18585 (setq s (replace-match "" t t s)))
18586 (when org-export-remove-timestamps-from-toc
18587 (while (string-match org-maybe-keyword-time-regexp s)
18588 (setq s (replace-match "" t t s))))
18591 (defun org-html-expand (string)
18592 "Prepare STRING for HTML export. Applies all active conversions.
18593 If there are links in the string, don't modify these."
18594 (let* (m s l res)
18595 (while (setq m (string-match org-bracket-link-regexp string))
18596 (setq s (substring string 0 m)
18597 l (match-string 0 string)
18598 string (substring string (match-end 0)))
18599 (push (org-html-do-expand s) res)
18600 (push l res))
18601 (push (org-html-do-expand string) res)
18602 (apply 'concat (nreverse res))))
18604 (defun org-html-do-expand (s)
18605 "Apply all active conversions to translate special ASCII to HTML."
18606 (setq s (org-html-protect s))
18607 (if org-export-html-expand
18608 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18609 (setq s (replace-match "<\\1>" t nil s))))
18610 (if org-export-with-emphasize
18611 (setq s (org-export-html-convert-emphasize s)))
18612 (if org-export-with-sub-superscripts
18613 (setq s (org-export-html-convert-sub-super s)))
18614 (if org-export-with-TeX-macros
18615 (let ((start 0) wd ass)
18616 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18617 (setq wd (match-string 1 s))
18618 (if (setq ass (assoc wd org-html-entities))
18619 (setq s (replace-match (or (cdr ass)
18620 (concat "&" (car ass) ";"))
18621 t t s))
18622 (setq start (+ start (length wd)))))))
18625 (defun org-create-multibrace-regexp (left right n)
18626 "Create a regular expression which will match a balanced sexp.
18627 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18628 as single character strings.
18629 The regexp returned will match the entire expression including the
18630 delimiters. It will also define a single group which contains the
18631 match except for the outermost delimiters. The maximum depth of
18632 stacked delimiters is N. Escaping delimiters is not possible."
18633 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18634 (or "\\|")
18635 (re nothing)
18636 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18637 (while (> n 1)
18638 (setq n (1- n)
18639 re (concat re or next)
18640 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18641 (concat left "\\(" re "\\)" right)))
18643 (defvar org-match-substring-regexp
18644 (concat
18645 "\\([^\\]\\)\\([_^]\\)\\("
18646 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18647 "\\|"
18648 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18649 "\\|"
18650 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18651 "The regular expression matching a sub- or superscript.")
18653 (defun org-export-html-convert-sub-super (string)
18654 "Convert sub- and superscripts in STRING to HTML."
18655 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
18656 (while (string-match org-match-substring-regexp string s)
18657 (if (and requireb (match-end 8))
18658 (setq s (match-end 2))
18659 (setq s (match-end 1)
18660 key (if (string= (match-string 2 string) "_") "sub" "sup")
18661 c (or (match-string 8 string)
18662 (match-string 6 string)
18663 (match-string 5 string))
18664 string (replace-match
18665 (concat (match-string 1 string)
18666 "<" key ">" c "</" key ">")
18667 t t string)))
18668 (while (string-match "\\\\\\([_^]\\)" string)
18669 (setq string (replace-match (match-string 1 string) t t string))))
18670 string))
18672 (defun org-export-html-convert-emphasize (string)
18673 "Apply emphasis."
18674 (while (string-match org-emph-re string)
18675 (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
18676 string)
18678 (defvar org-par-open nil)
18679 (defun org-open-par ()
18680 "Insert <p>, but first close previous paragraph if any."
18681 (org-close-par-maybe)
18682 (insert "\n<p>")
18683 (setq org-par-open t))
18684 (defun org-close-par-maybe ()
18685 "Close paragraph if there is one open."
18686 (when org-par-open
18687 (insert "</p>")
18688 (setq org-par-open nil)))
18689 (defun org-close-li ()
18690 "Close <li> if necessary."
18691 (org-close-par-maybe)
18692 (insert "</li>\n"))
18694 (defun org-html-level-start (level title umax with-toc head-count)
18695 "Insert a new level in HTML export.
18696 When TITLE is nil, just close all open levels."
18697 (org-close-par-maybe)
18698 (let ((l (1+ (max level umax))))
18699 (while (<= l org-level-max)
18700 (if (aref org-levels-open (1- l))
18701 (progn
18702 (org-html-level-close l)
18703 (aset org-levels-open (1- l) nil)))
18704 (setq l (1+ l)))
18705 (when title
18706 ;; If title is nil, this means this function is called to close
18707 ;; all levels, so the rest is done only if title is given
18708 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18709 (setq title (replace-match
18710 (if org-export-with-tags
18711 (save-match-data
18712 (concat
18713 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
18714 (mapconcat 'identity (org-split-string
18715 (match-string 1 title) ":")
18716 "&nbsp;")
18717 "</span>"))
18719 t t title)))
18720 (if (> level umax)
18721 (progn
18722 (if (aref org-levels-open (1- level))
18723 (progn
18724 (org-close-li)
18725 (insert "<li>" title "<br/>\n"))
18726 (aset org-levels-open (1- level) t)
18727 (org-close-par-maybe)
18728 (insert "<ul>\n<li>" title "<br/>\n")))
18729 (if org-export-with-section-numbers
18730 (setq title (concat (org-section-number level) " " title)))
18731 (setq level (+ level org-export-html-toplevel-hlevel -1))
18732 (if with-toc
18733 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
18734 level head-count title level))
18735 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
18736 (org-open-par)))))
18738 (defun org-html-level-close (&rest args)
18739 "Terminate one level in HTML export."
18740 (org-close-li)
18741 (insert "</ul>\n"))
18743 ;;; iCalendar export
18745 ;;;###autoload
18746 (defun org-export-icalendar-this-file ()
18747 "Export current file as an iCalendar file.
18748 The iCalendar file will be located in the same directory as the Org-mode
18749 file, but with extension `.ics'."
18750 (interactive)
18751 (org-export-icalendar nil buffer-file-name))
18753 ;;;###autoload
18754 (defun org-export-icalendar-all-agenda-files ()
18755 "Export all files in `org-agenda-files' to iCalendar .ics files.
18756 Each iCalendar file will be located in the same directory as the Org-mode
18757 file, but with extension `.ics'."
18758 (interactive)
18759 (apply 'org-export-icalendar nil (org-agenda-files t)))
18761 ;;;###autoload
18762 (defun org-export-icalendar-combine-agenda-files ()
18763 "Export all files in `org-agenda-files' to a single combined iCalendar file.
18764 The file is stored under the name `org-combined-agenda-icalendar-file'."
18765 (interactive)
18766 (apply 'org-export-icalendar t (org-agenda-files t)))
18768 (defun org-export-icalendar (combine &rest files)
18769 "Create iCalendar files for all elements of FILES.
18770 If COMBINE is non-nil, combine all calendar entries into a single large
18771 file and store it under the name `org-combined-agenda-icalendar-file'."
18772 (save-excursion
18773 (let* ((dir (org-export-directory
18774 :ical (list :publishing-directory
18775 org-export-publishing-directory)))
18776 file ical-file ical-buffer category started org-agenda-new-buffers)
18778 (when combine
18779 (setq ical-file
18780 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
18781 org-combined-agenda-icalendar-file
18782 (expand-file-name org-combined-agenda-icalendar-file dir))
18783 ical-buffer (org-get-agenda-file-buffer ical-file))
18784 (set-buffer ical-buffer) (erase-buffer))
18785 (while (setq file (pop files))
18786 (catch 'nextfile
18787 (org-check-agenda-file file)
18788 (set-buffer (org-get-agenda-file-buffer file))
18789 (unless combine
18790 (setq ical-file (concat (file-name-as-directory dir)
18791 (file-name-sans-extension
18792 (file-name-nondirectory buffer-file-name))
18793 ".ics"))
18794 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
18795 (with-current-buffer ical-buffer (erase-buffer)))
18796 (setq category (or org-category
18797 (file-name-sans-extension
18798 (file-name-nondirectory buffer-file-name))))
18799 (if (symbolp category) (setq category (symbol-name category)))
18800 (let ((standard-output ical-buffer))
18801 (if combine
18802 (and (not started) (setq started t)
18803 (org-start-icalendar-file org-icalendar-combined-name))
18804 (org-start-icalendar-file category))
18805 (org-print-icalendar-entries combine)
18806 (when (or (and combine (not files)) (not combine))
18807 (org-finish-icalendar-file)
18808 (set-buffer ical-buffer)
18809 (save-buffer)
18810 (run-hooks 'org-after-save-iCalendar-file-hook)))))
18811 (org-release-buffers org-agenda-new-buffers))))
18813 (defvar org-after-save-iCalendar-file-hook nil
18814 "Hook run after an iCalendar file has been saved.
18815 The iCalendar buffer is still current when this hook is run.
18816 A good way to use this is to tell a desktop calenndar application to re-read
18817 the iCalendar file.")
18819 (defun org-print-icalendar-entries (&optional combine)
18820 "Print iCalendar entries for the current Org-mode file to `standard-output'.
18821 When COMBINE is non nil, add the category to each line."
18822 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
18823 (org-category-table (org-get-category-table))
18824 (dts (org-ical-ts-to-string
18825 (format-time-string (cdr org-time-stamp-formats) (current-time))
18826 "DTSTART"))
18827 hd ts ts2 state status (inc t) pos
18828 scheduledp deadlinep tmp pri category)
18829 (save-excursion
18830 (goto-char (point-min))
18831 (while (re-search-forward org-ts-regexp nil t)
18832 (setq pos (match-beginning 0)
18833 ts (match-string 0)
18834 inc t
18835 hd (org-get-heading)
18836 category (org-get-category))
18837 (if (looking-at re2)
18838 (progn
18839 (goto-char (match-end 0))
18840 (setq ts2 (match-string 1) inc nil))
18841 (setq ts2 ts
18842 tmp (buffer-substring (max (point-min)
18843 (- pos org-ds-keyword-length))
18844 pos)
18845 deadlinep (string-match org-deadline-regexp tmp)
18846 scheduledp (string-match org-scheduled-regexp tmp)
18847 ;; donep (org-entry-is-done-p)
18849 (if (or (string-match org-tr-regexp hd)
18850 (string-match org-ts-regexp hd))
18851 (setq hd (replace-match "" t t hd)))
18852 (if (string-match org-bracket-link-regexp hd)
18853 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18854 (match-string 1 hd))
18855 t t hd)))
18856 (if deadlinep (setq hd (concat "DL: " hd)))
18857 (if scheduledp (setq hd (concat "S: " hd)))
18858 (princ (format "BEGIN:VEVENT
18861 SUMMARY:%s
18862 CATEGORIES:%s
18863 END:VEVENT\n"
18864 (org-ical-ts-to-string ts "DTSTART")
18865 (org-ical-ts-to-string ts2 "DTEND" inc)
18866 hd category)))
18867 (when org-icalendar-include-todo
18868 (goto-char (point-min))
18869 (while (re-search-forward org-todo-line-regexp nil t)
18870 (setq state (match-string 2))
18871 (setq status (if (member state org-done-keywords)
18872 "COMPLETED" "NEEDS-ACTION"))
18873 (when (and state
18874 (or (not (member state org-done-keywords))
18875 (eq org-icalendar-include-todo 'all)))
18876 (setq hd (match-string 3))
18877 (if (string-match org-bracket-link-regexp hd)
18878 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18879 (match-string 1 hd))
18880 t t hd)))
18881 (if (string-match org-priority-regexp hd)
18882 (setq pri (string-to-char (match-string 2 hd))
18883 hd (concat (substring hd 0 (match-beginning 1))
18884 (substring hd (match-end 1))))
18885 (setq pri org-default-priority))
18886 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
18887 (- org-lowest-priority ?A))))))
18889 (princ (format "BEGIN:VTODO
18891 SUMMARY:%s
18892 CATEGORIES:%s
18893 SEQUENCE:1
18894 PRIORITY:%d
18895 STATUS:%s
18896 END:VTODO\n"
18897 dts hd category pri status))))))))
18899 (defun org-start-icalendar-file (name)
18900 "Start an iCalendar file by inserting the header."
18901 (let ((user user-full-name)
18902 (name (or name "unknown"))
18903 (timezone (cadr (current-time-zone))))
18904 (princ
18905 (format "BEGIN:VCALENDAR
18906 VERSION:2.0
18907 X-WR-CALNAME:%s
18908 PRODID:-//%s//Emacs with Org-mode//EN
18909 X-WR-TIMEZONE:%s
18910 CALSCALE:GREGORIAN\n" name user timezone))))
18912 (defun org-finish-icalendar-file ()
18913 "Finish an iCalendar file by inserting the END statement."
18914 (princ "END:VCALENDAR\n"))
18916 (defun org-ical-ts-to-string (s keyword &optional inc)
18917 "Take a time string S and convert it to iCalendar format.
18918 KEYWORD is added in front, to make a complete line like DTSTART....
18919 When INC is non-nil, increase the hour by two (if time string contains
18920 a time), or the day by one (if it does not contain a time)."
18921 (let ((t1 (org-parse-time-string s 'nodefault))
18922 t2 fmt have-time time)
18923 (if (and (car t1) (nth 1 t1) (nth 2 t1))
18924 (setq t2 t1 have-time t)
18925 (setq t2 (org-parse-time-string s)))
18926 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
18927 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
18928 (when inc
18929 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
18930 (setq time (encode-time s mi h d m y)))
18931 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
18932 (concat keyword (format-time-string fmt time))))
18934 ;;; XOXO export
18936 (defun org-export-as-xoxo-insert-into (buffer &rest output)
18937 (with-current-buffer buffer
18938 (apply 'insert output)))
18939 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
18941 (defun org-export-as-xoxo (&optional buffer)
18942 "Export the org buffer as XOXO.
18943 The XOXO buffer is named *xoxo-<source buffer name>*"
18944 (interactive (list (current-buffer)))
18945 ;; A quickie abstraction
18947 ;; Output everything as XOXO
18948 (with-current-buffer (get-buffer buffer)
18949 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
18950 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18951 (org-infile-export-plist)))
18952 (filename (concat (file-name-as-directory
18953 (org-export-directory :xoxo opt-plist))
18954 (file-name-sans-extension
18955 (file-name-nondirectory buffer-file-name))
18956 ".html"))
18957 (out (find-file-noselect filename))
18958 (last-level 1)
18959 (hanging-li nil))
18960 ;; Check the output buffer is empty.
18961 (with-current-buffer out (erase-buffer))
18962 ;; Kick off the output
18963 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
18964 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
18965 (let* ((hd (match-string-no-properties 1))
18966 (level (length hd))
18967 (text (concat
18968 (match-string-no-properties 2)
18969 (save-excursion
18970 (goto-char (match-end 0))
18971 (let ((str ""))
18972 (catch 'loop
18973 (while 't
18974 (forward-line)
18975 (if (looking-at "^[ \t]\\(.*\\)")
18976 (setq str (concat str (match-string-no-properties 1)))
18977 (throw 'loop str)))))))))
18979 ;; Handle level rendering
18980 (cond
18981 ((> level last-level)
18982 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
18984 ((< level last-level)
18985 (dotimes (- (- last-level level) 1)
18986 (if hanging-li
18987 (org-export-as-xoxo-insert-into out "</li>\n"))
18988 (org-export-as-xoxo-insert-into out "</ol>\n"))
18989 (when hanging-li
18990 (org-export-as-xoxo-insert-into out "</li>\n")
18991 (setq hanging-li nil)))
18993 ((equal level last-level)
18994 (if hanging-li
18995 (org-export-as-xoxo-insert-into out "</li>\n")))
18998 (setq last-level level)
19000 ;; And output the new li
19001 (setq hanging-li 't)
19002 (if (equal ?+ (elt text 0))
19003 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
19004 (org-export-as-xoxo-insert-into out "<li>" text))))
19006 ;; Finally finish off the ol
19007 (dotimes (- last-level 1)
19008 (if hanging-li
19009 (org-export-as-xoxo-insert-into out "</li>\n"))
19010 (org-export-as-xoxo-insert-into out "</ol>\n"))
19012 ;; Finish the buffer off and clean it up.
19013 (switch-to-buffer-other-window out)
19014 (indent-region (point-min) (point-max) nil)
19015 (save-buffer)
19016 (goto-char (point-min))
19020 ;;;; Key bindings
19022 ;; Make `C-c C-x' a prefix key
19023 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
19025 ;; TAB key with modifiers
19026 (define-key org-mode-map "\C-i" 'org-cycle)
19027 (define-key org-mode-map [(tab)] 'org-cycle)
19028 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
19029 (define-key org-mode-map [(meta tab)] 'org-complete)
19030 (define-key org-mode-map "\M-\t" 'org-complete)
19031 (define-key org-mode-map "\M-\C-i" 'org-complete)
19032 ;; The following line is necessary under Suse GNU/Linux
19033 (unless (featurep 'xemacs)
19034 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
19035 (define-key org-mode-map [(shift tab)] 'org-shifttab)
19037 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
19038 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19039 (define-key org-mode-map [(meta return)] 'org-meta-return)
19041 ;; Cursor keys with modifiers
19042 (define-key org-mode-map [(meta left)] 'org-metaleft)
19043 (define-key org-mode-map [(meta right)] 'org-metaright)
19044 (define-key org-mode-map [(meta up)] 'org-metaup)
19045 (define-key org-mode-map [(meta down)] 'org-metadown)
19047 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19048 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
19049 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
19050 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
19052 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
19053 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
19054 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
19055 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
19057 (define-key org-mode-map [(control shift right)] 'org-shiftcontrolright)
19058 (define-key org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19060 ;;; Extra keys for tty access.
19061 ;; We only set them when really needed because otherwise the
19062 ;; menus don't show the simple keys
19064 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19065 (not window-system))
19066 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19067 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19068 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
19069 (define-key org-mode-map [?\e (return)] 'org-meta-return)
19070 (define-key org-mode-map [?\e (left)] 'org-metaleft)
19071 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
19072 (define-key org-mode-map [?\e (right)] 'org-metaright)
19073 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
19074 (define-key org-mode-map [?\e (up)] 'org-metaup)
19075 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
19076 (define-key org-mode-map [?\e (down)] 'org-metadown)
19077 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
19078 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19079 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19080 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19081 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19082 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
19083 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
19084 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
19085 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
19087 ;; All the other keys
19089 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19090 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
19091 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
19092 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
19093 (define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19094 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
19095 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19096 (define-key org-mode-map "\C-c\C-j" 'org-goto)
19097 (define-key org-mode-map "\C-c\C-t" 'org-todo)
19098 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
19099 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
19100 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
19101 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
19102 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
19103 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
19104 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
19105 (define-key org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19106 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
19107 (define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19108 (define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19109 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
19110 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
19111 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
19112 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
19113 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
19114 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19115 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19116 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19117 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19118 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
19119 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
19120 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19121 (define-key org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19122 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
19123 (define-key org-mode-map "\C-c]" 'org-remove-file)
19124 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
19125 (define-key org-mode-map "\C-c^" 'org-sort)
19126 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19127 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
19128 (define-key org-mode-map "\C-m" 'org-return)
19129 (define-key org-mode-map "\C-c?" 'org-table-field-info)
19130 (define-key org-mode-map "\C-c " 'org-table-blank-field)
19131 (define-key org-mode-map "\C-c+" 'org-table-sum)
19132 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
19133 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
19134 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
19135 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19136 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
19137 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19138 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
19139 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
19140 (define-key org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19141 (define-key org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19142 (define-key org-mode-map "\C-c\C-e" 'org-export)
19143 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19145 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
19146 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19147 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19148 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19150 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19151 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19152 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19153 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
19154 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19155 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19156 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19157 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19158 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19160 (when (featurep 'xemacs)
19161 (define-key org-mode-map 'button3 'popup-mode-menu))
19163 (defsubst org-table-p () (org-at-table-p))
19165 (defun org-self-insert-command (N)
19166 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19167 If the cursor is in a table looking at whitespace, the whitespace is
19168 overwritten, and the table is not marked as requiring realignment."
19169 (interactive "p")
19170 (if (and (org-table-p)
19171 (progn
19172 ;; check if we blank the field, and if that triggers align
19173 (and org-table-auto-blank-field
19174 (member last-command
19175 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19176 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19177 ;; got extra space, this field does not determine column width
19178 (let (org-table-may-need-update) (org-table-blank-field))
19179 ;; no extra space, this field may determine column width
19180 (org-table-blank-field)))
19182 (eq N 1)
19183 (looking-at "[^|\n]* |"))
19184 (let (org-table-may-need-update)
19185 (goto-char (1- (match-end 0)))
19186 (delete-backward-char 1)
19187 (goto-char (match-beginning 0))
19188 (self-insert-command N))
19189 (setq org-table-may-need-update t)
19190 (self-insert-command N)))
19192 (defun org-delete-backward-char (N)
19193 "Like `delete-backward-char', insert whitespace at field end in tables.
19194 When deleting backwards, in tables this function will insert whitespace in
19195 front of the next \"|\" separator, to keep the table aligned. The table will
19196 still be marked for re-alignment if the field did fill the entire column,
19197 because, in this case the deletion might narrow the column."
19198 (interactive "p")
19199 (if (and (org-table-p)
19200 (eq N 1)
19201 (string-match "|" (buffer-substring (point-at-bol) (point)))
19202 (looking-at ".*?|"))
19203 (let ((pos (point))
19204 (noalign (looking-at "[^|\n\r]* |"))
19205 (c org-table-may-need-update))
19206 (backward-delete-char N)
19207 (skip-chars-forward "^|")
19208 (insert " ")
19209 (goto-char (1- pos))
19210 ;; noalign: if there were two spaces at the end, this field
19211 ;; does not determine the width of the column.
19212 (if noalign (setq org-table-may-need-update c)))
19213 (backward-delete-char N)))
19215 (defun org-delete-char (N)
19216 "Like `delete-char', but insert whitespace at field end in tables.
19217 When deleting characters, in tables this function will insert whitespace in
19218 front of the next \"|\" separator, to keep the table aligned. The table will
19219 still be marked for re-alignment if the field did fill the entire column,
19220 because, in this case the deletion might narrow the column."
19221 (interactive "p")
19222 (if (and (org-table-p)
19223 (not (bolp))
19224 (not (= (char-after) ?|))
19225 (eq N 1))
19226 (if (looking-at ".*?|")
19227 (let ((pos (point))
19228 (noalign (looking-at "[^|\n\r]* |"))
19229 (c org-table-may-need-update))
19230 (replace-match (concat
19231 (substring (match-string 0) 1 -1)
19232 " |"))
19233 (goto-char pos)
19234 ;; noalign: if there were two spaces at the end, this field
19235 ;; does not determine the width of the column.
19236 (if noalign (setq org-table-may-need-update c)))
19237 (delete-char N))
19238 (delete-char N)))
19240 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19241 (put 'org-self-insert-command 'delete-selection t)
19242 (put 'orgtbl-self-insert-command 'delete-selection t)
19243 (put 'org-delete-char 'delete-selection 'supersede)
19244 (put 'org-delete-backward-char 'delete-selection 'supersede)
19246 ;; Make `flyspell-mode' delay after some commands
19247 (put 'org-self-insert-command 'flyspell-delayed t)
19248 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19249 (put 'org-delete-char 'flyspell-delayed t)
19250 (put 'org-delete-backward-char 'flyspell-delayed t)
19252 ;; How to do this: Measure non-white length of current string
19253 ;; If equal to column width, we should realign.
19255 (defun org-remap (map &rest commands)
19256 "In MAP, remap the functions given in COMMANDS.
19257 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19258 (let (new old)
19259 (while commands
19260 (setq old (pop commands) new (pop commands))
19261 (if (fboundp 'command-remapping)
19262 (define-key map (vector 'remap old) new)
19263 (substitute-key-definition old new map global-map)))))
19265 (when (eq org-enable-table-editor 'optimized)
19266 ;; If the user wants maximum table support, we need to hijack
19267 ;; some standard editing functions
19268 (org-remap org-mode-map
19269 'self-insert-command 'org-self-insert-command
19270 'delete-char 'org-delete-char
19271 'delete-backward-char 'org-delete-backward-char)
19272 (define-key org-mode-map "|" 'org-force-self-insert))
19274 (defun org-shiftcursor-error ()
19275 "Throw an error because Shift-Cursor command was applied in wrong context."
19276 (error "This command is active in special context like tables, headlines or timestamps"))
19278 (defun org-shifttab (&optional arg)
19279 "Global visibility cycling or move to previous table field.
19280 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19281 on context.
19282 See the individual commands for more information."
19283 (interactive "P")
19284 (cond
19285 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19286 (arg (message "Content view to level: ")
19287 (org-content (prefix-numeric-value arg))
19288 (setq org-cycle-global-status 'overview))
19289 (t (call-interactively 'org-global-cycle))))
19291 (defun org-shiftmetaleft ()
19292 "Promote subtree or delete table column.
19293 Calls `org-promote-subtree', `org-outdent-item',
19294 or `org-table-delete-column', depending on context.
19295 See the individual commands for more information."
19296 (interactive)
19297 (cond
19298 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19299 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
19300 ((org-at-item-p) (call-interactively 'org-outdent-item))
19301 (t (org-shiftcursor-error))))
19303 (defun org-shiftmetaright ()
19304 "Demote subtree or insert table column.
19305 Calls `org-demote-subtree', `org-indent-item',
19306 or `org-table-insert-column', depending on context.
19307 See the individual commands for more information."
19308 (interactive)
19309 (cond
19310 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19311 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
19312 ((org-at-item-p) (call-interactively 'org-indent-item))
19313 (t (org-shiftcursor-error))))
19315 (defun org-shiftmetaup (&optional arg)
19316 "Move subtree up or kill table row.
19317 Calls `org-move-subtree-up' or `org-table-kill-row' or
19318 `org-move-item-up' depending on context. See the individual commands
19319 for more information."
19320 (interactive "P")
19321 (cond
19322 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19323 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19324 ((org-at-item-p) (call-interactively 'org-move-item-up))
19325 (t (org-shiftcursor-error))))
19326 (defun org-shiftmetadown (&optional arg)
19327 "Move subtree down or insert table row.
19328 Calls `org-move-subtree-down' or `org-table-insert-row' or
19329 `org-move-item-down', depending on context. See the individual
19330 commands for more information."
19331 (interactive "P")
19332 (cond
19333 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19334 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19335 ((org-at-item-p) (call-interactively 'org-move-item-down))
19336 (t (org-shiftcursor-error))))
19338 (defun org-metaleft (&optional arg)
19339 "Promote heading or move table column to left.
19340 Calls `org-do-promote' or `org-table-move-column', depending on context.
19341 With no specific context, calls the Emacs default `backward-word'.
19342 See the individual commands for more information."
19343 (interactive "P")
19344 (cond
19345 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19346 ((or (org-on-heading-p) (org-region-active-p))
19347 (call-interactively 'org-do-promote))
19348 ((org-at-item-p) (call-interactively 'org-outdent-item))
19349 (t (call-interactively 'backward-word))))
19351 (defun org-metaright (&optional arg)
19352 "Demote subtree or move table column to right.
19353 Calls `org-do-demote' or `org-table-move-column', depending on context.
19354 With no specific context, calls the Emacs default `forward-word'.
19355 See the individual commands for more information."
19356 (interactive "P")
19357 (cond
19358 ((org-at-table-p) (call-interactively 'org-table-move-column))
19359 ((or (org-on-heading-p) (org-region-active-p))
19360 (call-interactively 'org-do-demote))
19361 ((org-at-item-p) (call-interactively 'org-indent-item))
19362 (t (call-interactively 'forward-word))))
19364 (defun org-metaup (&optional arg)
19365 "Move subtree up or move table row up.
19366 Calls `org-move-subtree-up' or `org-table-move-row' or
19367 `org-move-item-up', depending on context. See the individual commands
19368 for more information."
19369 (interactive "P")
19370 (cond
19371 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19372 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19373 ((org-at-item-p) (call-interactively 'org-move-item-up))
19374 (t (org-shiftcursor-error))))
19376 (defun org-metadown (&optional arg)
19377 "Move subtree down or move table row down.
19378 Calls `org-move-subtree-down' or `org-table-move-row' or
19379 `org-move-item-down', depending on context. See the individual
19380 commands for more information."
19381 (interactive "P")
19382 (cond
19383 ((org-at-table-p) (call-interactively 'org-table-move-row))
19384 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19385 ((org-at-item-p) (call-interactively 'org-move-item-down))
19386 (t (org-shiftcursor-error))))
19388 (defun org-shiftup (&optional arg)
19389 "Increase item in timestamp or increase priority of current headline.
19390 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19391 depending on context. See the individual commands for more information."
19392 (interactive "P")
19393 (cond
19394 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
19395 ((org-on-heading-p) (call-interactively 'org-priority-up))
19396 ((org-at-item-p) (call-interactively 'org-previous-item))
19397 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
19399 (defun org-shiftdown (&optional arg)
19400 "Decrease item in timestamp or decrease priority of current headline.
19401 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19402 depending on context. See the individual commands for more information."
19403 (interactive "P")
19404 (cond
19405 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
19406 ((org-on-heading-p) (call-interactively 'org-priority-down))
19407 (t (call-interactively 'org-next-item))))
19409 (defun org-shiftright ()
19410 "Next TODO keyword or timestamp one day later, depending on context."
19411 (interactive)
19412 (cond
19413 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19414 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
19415 (t (org-shiftcursor-error))))
19417 (defun org-shiftleft ()
19418 "Previous TODO keyword or timestamp one day earlier, depending on context."
19419 (interactive)
19420 (cond
19421 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19422 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
19423 (t (org-shiftcursor-error))))
19425 (defun org-shiftcontrolright ()
19426 "Switch to next TODO set."
19427 (interactive)
19428 (cond
19429 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
19430 (t (org-shiftcursor-error))))
19432 (defun org-shiftcontrolleft ()
19433 "Switch to previous TODO set."
19434 (interactive)
19435 (cond
19436 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
19437 (t (org-shiftcursor-error))))
19439 (defun org-ctrl-c-ret ()
19440 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19441 (interactive)
19442 (cond
19443 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19444 (t (call-interactively 'org-insert-heading))))
19446 (defun org-copy-special ()
19447 "Copy region in table or copy current subtree.
19448 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19449 See the individual commands for more information."
19450 (interactive)
19451 (call-interactively
19452 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19454 (defun org-cut-special ()
19455 "Cut region in table or cut current subtree.
19456 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19457 See the individual commands for more information."
19458 (interactive)
19459 (call-interactively
19460 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19462 (defun org-paste-special (arg)
19463 "Paste rectangular region into table, or past subtree relative to level.
19464 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19465 See the individual commands for more information."
19466 (interactive "P")
19467 (if (org-at-table-p)
19468 (org-table-paste-rectangle)
19469 (org-paste-subtree arg)))
19471 (defun org-ctrl-c-ctrl-c (&optional arg)
19472 "Set tags in headline, or update according to changed information at point.
19474 This command does many different things, depending on context:
19476 - If the cursor is in a headline, prompt for tags and insert them
19477 into the current line, aligned to `org-tags-column'. When called
19478 with prefix arg, realign all tags in the current buffer.
19480 - If the cursor is in one of the special #+KEYWORD lines, this
19481 triggers scanning the buffer for these lines and updating the
19482 information.
19484 - If the cursor is inside a table, realign the table. This command
19485 works even if the automatic table editor has been turned off.
19487 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19488 the entire table.
19490 - If the cursor is inside a table created by the table.el package,
19491 activate that table.
19493 - If the current buffer is a remember buffer, close note and file it.
19494 with a prefix argument, file it without further interaction to the default
19495 location.
19497 - If the cursor is on a <<<target>>>, update radio targets and corresponding
19498 links in this buffer.
19500 - If the cursor is on a numbered item in a plain list, renumber the
19501 ordered list."
19502 (interactive "P")
19503 (let ((org-enable-table-editor t))
19504 (cond
19505 ((or org-clock-overlays
19506 org-occur-highlights
19507 org-latex-fragment-image-overlays)
19508 (org-remove-clock-overlays)
19509 (org-remove-occur-highlights)
19510 (org-remove-latex-fragment-image-overlays)
19511 (message "Temporary highlights/overlays removed from current buffer"))
19512 ((and (local-variable-p 'org-finish-function (current-buffer))
19513 (fboundp org-finish-function))
19514 (funcall org-finish-function))
19515 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19516 ((org-on-heading-p) (call-interactively 'org-set-tags))
19517 ((org-at-table.el-p)
19518 (require 'table)
19519 (beginning-of-line 1)
19520 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19521 (call-interactively 'table-recognize-table))
19522 ((org-at-table-p)
19523 (org-table-maybe-eval-formula)
19524 (if arg
19525 (call-interactively 'org-table-recalculate)
19526 (org-table-maybe-recalculate-line))
19527 (call-interactively 'org-table-align))
19528 ((org-at-item-checkbox-p)
19529 (call-interactively 'org-toggle-checkbox))
19530 ((org-at-item-p)
19531 (call-interactively 'org-renumber-ordered-list))
19532 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19533 (cond
19534 ((equal (match-string 1) "TBLFM")
19535 ;; Recalculate the table before this line
19536 (save-excursion
19537 (beginning-of-line 1)
19538 (skip-chars-backward " \r\n\t")
19539 (if (org-at-table-p)
19540 (org-call-with-arg 'org-table-recalculate t))))
19542 (call-interactively 'org-mode-restart))))
19543 (t (error "C-c C-c can do nothing useful at this location.")))))
19545 (defun org-mode-restart ()
19546 "Restart Org-mode, to scan again for special lines.
19547 Also updates the keyword regular expressions."
19548 (interactive)
19549 (let ((org-inhibit-startup t)) (org-mode))
19550 (message "Org-mode restarted to refresh keyword and special line setup"))
19552 (defun org-return ()
19553 "Goto next table row or insert a newline.
19554 Calls `org-table-next-row' or `newline', depending on context.
19555 See the individual commands for more information."
19556 (interactive)
19557 (cond
19558 ((org-at-table-p)
19559 (org-table-justify-field-maybe)
19560 (call-interactively 'org-table-next-row))
19561 (t (newline))))
19563 (defun org-meta-return (&optional arg)
19564 "Insert a new heading or wrap a region in a table.
19565 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19566 See the individual commands for more information."
19567 (interactive "P")
19568 (cond
19569 ((org-at-table-p)
19570 (call-interactively 'org-table-wrap-region))
19571 (t (call-interactively 'org-insert-heading))))
19573 ;;; Menu entries
19575 ;; Define the Org-mode menus
19576 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19577 '("Tbl"
19578 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19579 ["Next Field" org-cycle (org-at-table-p)]
19580 ["Previous Field" org-shifttab (org-at-table-p)]
19581 ["Next Row" org-return (org-at-table-p)]
19582 "--"
19583 ["Blank Field" org-table-blank-field (org-at-table-p)]
19584 ["Edit Field" org-table-edit-field (org-at-table-p)]
19585 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19586 "--"
19587 ("Column"
19588 ["Move Column Left" org-metaleft (org-at-table-p)]
19589 ["Move Column Right" org-metaright (org-at-table-p)]
19590 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19591 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19592 ("Row"
19593 ["Move Row Up" org-metaup (org-at-table-p)]
19594 ["Move Row Down" org-metadown (org-at-table-p)]
19595 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19596 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19597 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19598 "--"
19599 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19600 ("Rectangle"
19601 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19602 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19603 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19604 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19605 "--"
19606 ("Calculate"
19607 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19608 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19609 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19610 "--"
19611 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19612 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19613 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19614 "--"
19615 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19616 "--"
19617 ["Sum Column/Rectangle" org-table-sum
19618 (or (org-at-table-p) (org-region-active-p))]
19619 ["Which Column?" org-table-current-column (org-at-table-p)])
19620 ["Debug Formulas"
19621 org-table-toggle-formula-debugger
19622 :style toggle :selected org-table-formula-debug]
19623 ["Show Col/Row Numbers"
19624 org-table-toggle-coordinate-overlays
19625 :style toggle :selected org-table-overlay-coordinates]
19626 "--"
19627 ["Create" org-table-create (and (not (org-at-table-p))
19628 org-enable-table-editor)]
19629 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19630 ["Import from File" org-table-import (not (org-at-table-p))]
19631 ["Export to File" org-table-export (org-at-table-p)]
19632 "--"
19633 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19635 (easy-menu-define org-org-menu org-mode-map "Org menu"
19636 '("Org"
19637 ("Show/Hide"
19638 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19639 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19640 ["Sparse Tree" org-occur t]
19641 ["Reveal Context" org-reveal t]
19642 ["Show All" show-all t]
19643 "--"
19644 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19645 "--"
19646 ["New Heading" org-insert-heading t]
19647 ("Navigate Headings"
19648 ["Up" outline-up-heading t]
19649 ["Next" outline-next-visible-heading t]
19650 ["Previous" outline-previous-visible-heading t]
19651 ["Next Same Level" outline-forward-same-level t]
19652 ["Previous Same Level" outline-backward-same-level t]
19653 "--"
19654 ["Jump" org-goto t])
19655 ("Edit Structure"
19656 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19657 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19658 "--"
19659 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19660 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19661 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19662 "--"
19663 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19664 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19665 ["Demote Heading" org-metaright (not (org-at-table-p))]
19666 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19667 "--"
19668 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19669 "--"
19670 ["Convert to odd levels" org-convert-to-odd-levels t]
19671 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19672 ("Archive"
19673 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19674 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
19675 ; :active t :keys "C-u C-c C-x C-a"]
19676 ["Sparse trees open ARCHIVE trees"
19677 (setq org-sparse-tree-open-archived-trees
19678 (not org-sparse-tree-open-archived-trees))
19679 :style toggle :selected org-sparse-tree-open-archived-trees]
19680 ["Cycling opens ARCHIVE trees"
19681 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
19682 :style toggle :selected org-cycle-open-archived-trees]
19683 ["Agenda includes ARCHIVE trees"
19684 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
19685 :style toggle :selected (not org-agenda-skip-archived-trees)]
19686 "--"
19687 ["Move Subtree to Archive" org-advertized-archive-subtree t]
19688 ; ["Check and Move Children" (org-archive-subtree '(4))
19689 ; :active t :keys "C-u C-c C-x C-s"]
19691 "--"
19692 ("TODO Lists"
19693 ["TODO/DONE/-" org-todo t]
19694 ("Select keyword"
19695 ["Next keyword" org-shiftright (org-on-heading-p)]
19696 ["Previous keyword" org-shiftleft (org-on-heading-p)]
19697 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
19698 ["Show TODO Tree" org-show-todo-tree t]
19699 ["Global TODO list" org-todo-list t]
19700 "--"
19701 ["Set Priority" org-priority t]
19702 ["Priority Up" org-shiftup t]
19703 ["Priority Down" org-shiftdown t]
19704 "--"
19705 ;; FIXME: why is this still here????
19706 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
19707 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
19708 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
19709 ; (or (org-on-heading-p) (org-at-item-p))]
19710 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
19711 ; (or (org-on-heading-p) (org-at-item-p))]
19712 ; ["Update Statistics" org-update-checkbox-count t]
19714 ("Dates and Scheduling"
19715 ["Timestamp" org-time-stamp t]
19716 ["Timestamp (inactive)" org-time-stamp-inactive t]
19717 ("Change Date"
19718 ["1 Day Later" org-shiftright t]
19719 ["1 Day Earlier" org-shiftleft t]
19720 ["1 ... Later" org-shiftup t]
19721 ["1 ... Earlier" org-shiftdown t])
19722 ["Compute Time Range" org-evaluate-time-range t]
19723 ["Schedule Item" org-schedule t]
19724 ["Deadline" org-deadline t]
19725 "--"
19726 ["Custom time format" org-toggle-time-stamp-overlays
19727 :style radio :selected org-display-custom-times]
19728 "--"
19729 ["Goto Calendar" org-goto-calendar t]
19730 ["Date from Calendar" org-date-from-calendar t])
19731 ("Logging work"
19732 ["Clock in" org-clock-in t]
19733 ["Clock out" org-clock-out t]
19734 ["Clock cancel" org-clock-cancel t]
19735 ["Display times" org-clock-display t]
19736 ["Create clock table" org-clock-report t]
19737 "--"
19738 ["Record DONE time"
19739 (progn (setq org-log-done (not org-log-done))
19740 (message "Switching to %s will %s record a timestamp"
19741 (car org-done-keywords)
19742 (if org-log-done "automatically" "not")))
19743 :style toggle :selected org-log-done])
19744 "--"
19745 ["Agenda Command..." org-agenda t]
19746 ("File List for Agenda")
19747 ("Special views current file"
19748 ["TODO Tree" org-show-todo-tree t]
19749 ["Check Deadlines" org-check-deadlines t]
19750 ["Timeline" org-timeline t]
19751 ["Tags Tree" org-tags-sparse-tree t])
19752 "--"
19753 ("Hyperlinks"
19754 ["Store Link (Global)" org-store-link t]
19755 ["Insert Link" org-insert-link t]
19756 ["Follow Link" org-open-at-point t]
19757 "--"
19758 ["Next link" org-next-link t]
19759 ["Previous link" org-previous-link t]
19760 "--"
19761 ["Descriptive Links"
19762 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
19763 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
19764 ["Literal Links"
19765 (progn
19766 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
19767 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
19768 "--"
19769 ["Export/Publish..." org-export t]
19770 ("LaTeX"
19771 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19772 :selected org-cdlatex-mode]
19773 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19774 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19775 ["Modify math symbol" org-cdlatex-math-modify
19776 (org-inside-LaTeX-fragment-p)]
19777 ["Export LaTeX fragments as images"
19778 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
19779 :style toggle :selected org-export-with-LaTeX-fragments])
19780 "--"
19781 ("Documentation"
19782 ["Show Version" org-version t]
19783 ["Info Documentation" org-info t])
19784 ("Customize"
19785 ["Browse Org Group" org-customize t]
19786 "--"
19787 ["Expand This Menu" org-create-customize-menu
19788 (fboundp 'customize-menu-create)])
19789 "--"
19790 ["Refresh setup" org-mode-restart t]
19793 (defun org-info (&optional node)
19794 "Read documentation for Org-mode in the info system.
19795 With optional NODE, go directly to that node."
19796 (interactive)
19797 (require 'info)
19798 (Info-goto-node (format "(org)%s" (or node ""))))
19800 (defun org-install-agenda-files-menu ()
19801 (let ((bl (buffer-list)))
19802 (save-excursion
19803 (while bl
19804 (set-buffer (pop bl))
19805 (if (org-mode-p) (setq bl nil)))
19806 (when (org-mode-p)
19807 (easy-menu-change
19808 '("Org") "File List for Agenda"
19809 (append
19810 (list
19811 ["Edit File List" (org-edit-agenda-file-list) t]
19812 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19813 ["Remove Current File from List" org-remove-file t]
19814 ["Cycle through agenda files" org-cycle-agenda-files t]
19815 "--")
19816 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19818 ;;;; Documentation
19820 (defun org-customize ()
19821 "Call the customize function with org as argument."
19822 (interactive)
19823 (customize-browse 'org))
19825 (defun org-create-customize-menu ()
19826 "Create a full customization menu for Org-mode, insert it into the menu."
19827 (interactive)
19828 (if (fboundp 'customize-menu-create)
19829 (progn
19830 (easy-menu-change
19831 '("Org") "Customize"
19832 `(["Browse Org group" org-customize t]
19833 "--"
19834 ,(customize-menu-create 'org)
19835 ["Set" Custom-set t]
19836 ["Save" Custom-save t]
19837 ["Reset to Current" Custom-reset-current t]
19838 ["Reset to Saved" Custom-reset-saved t]
19839 ["Reset to Standard Settings" Custom-reset-standard t]))
19840 (message "\"Org\"-menu now contains full customization menu"))
19841 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19843 ;;;; Miscellaneous stuff
19846 ;;; Generally useful functions
19848 (defun org-context ()
19849 "Return a list of contexts of the current cursor position.
19850 If several contexts apply, all are returned.
19851 Each context entry is a list with a symbol naming the context, and
19852 two positions indicating start and end of the context. Possible
19853 contexts are:
19855 :headline anywhere in a headline
19856 :headline-stars on the leading stars in a headline
19857 :todo-keyword on a TODO keyword (including DONE) in a headline
19858 :tags on the TAGS in a headline
19859 :priority on the priority cookie in a headline
19860 :item on the first line of a plain list item
19861 :item-bullet on the bullet/number of a plain list item
19862 :checkbox on the checkbox in a plain list item
19863 :table in an org-mode table
19864 :table-special on a special filed in a table
19865 :table-table in a table.el table
19866 :link on a hyperlink
19867 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19868 :target on a <<target>>
19869 :radio-target on a <<<radio-target>>>
19870 :latex-fragment on a LaTeX fragment
19871 :latex-preview on a LaTeX fragment with overlayed preview image
19873 This function expects the position to be visible because it uses font-lock
19874 faces as a help to recognize the following contexts: :table-special, :link,
19875 and :keyword."
19876 (let* ((f (get-text-property (point) 'face))
19877 (faces (if (listp f) f (list f)))
19878 (p (point)) clist o)
19879 ;; First the large context
19880 (cond
19881 ((org-on-heading-p t)
19882 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19883 (when (progn
19884 (beginning-of-line 1)
19885 (looking-at org-todo-line-tags-regexp))
19886 (push (org-point-in-group p 1 :headline-stars) clist)
19887 (push (org-point-in-group p 2 :todo-keyword) clist)
19888 (push (org-point-in-group p 4 :tags) clist))
19889 (goto-char p)
19890 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
19891 (if (looking-at "\\[#[A-Z]\\]")
19892 (push (org-point-in-group p 0 :priority) clist)))
19894 ((org-at-item-p)
19895 (push (org-point-in-group p 2 :item-bullet) clist)
19896 (push (list :item (point-at-bol)
19897 (save-excursion (org-end-of-item) (point)))
19898 clist)
19899 (and (org-at-item-checkbox-p)
19900 (push (org-point-in-group p 0 :checkbox) clist)))
19902 ((org-at-table-p)
19903 (push (list :table (org-table-begin) (org-table-end)) clist)
19904 (if (memq 'org-formula faces)
19905 (push (list :table-special
19906 (previous-single-property-change p 'face)
19907 (next-single-property-change p 'face)) clist)))
19908 ((org-at-table-p 'any)
19909 (push (list :table-table) clist)))
19910 (goto-char p)
19912 ;; Now the small context
19913 (cond
19914 ((org-at-timestamp-p)
19915 (push (org-point-in-group p 0 :timestamp) clist))
19916 ((memq 'org-link faces)
19917 (push (list :link
19918 (previous-single-property-change p 'face)
19919 (next-single-property-change p 'face)) clist))
19920 ((memq 'org-special-keyword faces)
19921 (push (list :keyword
19922 (previous-single-property-change p 'face)
19923 (next-single-property-change p 'face)) clist))
19924 ((org-on-target-p)
19925 (push (org-point-in-group p 0 :target) clist)
19926 (goto-char (1- (match-beginning 0)))
19927 (if (looking-at org-radio-target-regexp)
19928 (push (org-point-in-group p 0 :radio-target) clist))
19929 (goto-char p))
19930 ((setq o (car (delq nil
19931 (mapcar
19932 (lambda (x)
19933 (if (memq x org-latex-fragment-image-overlays) x))
19934 (org-overlays-at (point))))))
19935 (push (list :latex-fragment
19936 (org-overlay-start o) (org-overlay-end o)) clist)
19937 (push (list :latex-preview
19938 (org-overlay-start o) (org-overlay-end o)) clist))
19939 ((org-inside-LaTeX-fragment-p)
19940 ;; FIXME: positions wrong.
19941 (push (list :latex-fragment (point) (point)) clist)))
19943 (setq clist (nreverse (delq nil clist)))
19944 clist))
19946 ;; FIXME Compare with at-regexp-p
19947 (defun org-in-regexp (re &optional nlines visually)
19948 "Check if point is inside a match of regexp.
19949 Normally only the current line is checked, but you can include NLINES extra
19950 lines both before and after point into the search.
19951 If VISUALLY is set, require that the cursor is not after the match but
19952 really on, so that the block visually is on the match."
19953 (catch 'exit
19954 (let ((pos (point))
19955 (eol (point-at-eol (+ 1 (or nlines 0))))
19956 (inc (if visually 1 0)))
19957 (save-excursion
19958 (beginning-of-line (- 1 (or nlines 0)))
19959 (while (re-search-forward re eol t)
19960 (if (and (<= (match-beginning 0) pos)
19961 (>= (+ inc (match-end 0)) pos))
19962 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19964 (defun org-at-regexp-p (regexp)
19965 "Is point inside a match of REGEXP in the current line?"
19966 (catch 'exit
19967 (save-excursion
19968 (let ((pos (point)) (end (point-at-eol)))
19969 (beginning-of-line 1)
19970 (while (re-search-forward regexp end t)
19971 (if (and (<= (match-beginning 0) pos)
19972 (>= (match-end 0) pos))
19973 (throw 'exit t)))
19974 nil))))
19976 (defun org-delete-all (elts list)
19977 "Remove all elements in ELTS from LIST."
19978 (while elts
19979 (setq list (delete (pop elts) list)))
19980 list)
19982 (defun org-point-in-group (point group &optional context)
19983 "Check if POINT is in match-group GROUP.
19984 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19985 match. If the match group does ot exist or point is not inside it,
19986 return nil."
19987 (and (match-beginning group)
19988 (>= point (match-beginning group))
19989 (<= point (match-end group))
19990 (if context
19991 (list context (match-beginning group) (match-end group))
19992 t)))
19994 (defun org-combine-plists (&rest plists)
19995 "Create a single property list from all plists in PLISTS.
19996 The process starts by copying the first list, and then setting properties
19997 from the other lists. Settings in the last list are the most significant
19998 ones and overrule settings in the other lists."
19999 (let ((rtn (copy-sequence (pop plists)))
20000 p v ls)
20001 (while plists
20002 (setq ls (pop plists))
20003 (while ls
20004 (setq p (pop ls) v (pop ls))
20005 (setq rtn (plist-put rtn p v))))
20006 rtn))
20008 (defun org-move-line-down (arg)
20009 "Move the current line down. With prefix argument, move it past ARG lines."
20010 (interactive "p")
20011 (let ((col (current-column))
20012 beg end pos)
20013 (beginning-of-line 1) (setq beg (point))
20014 (beginning-of-line 2) (setq end (point))
20015 (beginning-of-line (+ 1 arg))
20016 (setq pos (move-marker (make-marker) (point)))
20017 (insert (delete-and-extract-region beg end))
20018 (goto-char pos)
20019 (move-to-column col)))
20021 (defun org-move-line-up (arg)
20022 "Move the current line up. With prefix argument, move it past ARG lines."
20023 (interactive "p")
20024 (let ((col (current-column))
20025 beg end pos)
20026 (beginning-of-line 1) (setq beg (point))
20027 (beginning-of-line 2) (setq end (point))
20028 (beginning-of-line (- arg))
20029 (setq pos (move-marker (make-marker) (point)))
20030 (insert (delete-and-extract-region beg end))
20031 (goto-char pos)
20032 (move-to-column col)))
20034 (defun org-replace-escapes (string table)
20035 "Replace %-escapes in STRING with values in TABLE.
20036 TABLE is an association list with keys line \"%a\" and string values.
20037 The sequences in STRING may contain normal field width and padding information,
20038 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20039 so values can contain further %-escapes if they are define later in TABLE."
20040 (let ((case-fold-search nil)
20041 e re rpl)
20042 (while (setq e (pop table))
20043 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20044 (while (string-match re string)
20045 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20046 (cdr e)))
20047 (setq string (replace-match rpl t t string))))
20048 string))
20051 (defun org-sublist (list start end)
20052 "Return a section of LIST, from START to END.
20053 Counting starts at 1."
20054 (let (rtn (c start))
20055 (setq list (nthcdr (1- start) list))
20056 (while (and list (<= c end))
20057 (push (pop list) rtn)
20058 (setq c (1+ c)))
20059 (nreverse rtn)))
20061 (defun org-find-base-buffer-visiting (file)
20062 "Like `find-buffer-visiting' but alway return the base buffer and
20063 not an indirect buffer"
20064 (let ((buf (find-buffer-visiting file)))
20065 (or (buffer-base-buffer buf) buf)))
20067 (defun org-image-file-name-regexp ()
20068 "Return regexp matching the file names of images."
20069 (if (fboundp 'image-file-name-regexp)
20070 (image-file-name-regexp)
20071 (let ((image-file-name-extensions
20072 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20073 "xbm" "xpm" "pbm" "pgm" "ppm")))
20074 (concat "\\."
20075 (regexp-opt (nconc (mapcar 'upcase
20076 image-file-name-extensions)
20077 image-file-name-extensions)
20079 "\\'"))))
20081 (defun org-file-image-p (file)
20082 "Return non-nil if FILE is an image."
20083 (save-match-data
20084 (string-match (org-image-file-name-regexp) file)))
20086 ;;; Paragraph filling stuff.
20087 ;; We want this to be just right, so use the full arsenal.
20089 (defun org-indent-line-function ()
20090 "Indent line like previous, but further if previous was headline or item."
20091 (interactive)
20092 (let ((column (save-excursion
20093 (beginning-of-line)
20094 (if (looking-at "#") 0
20095 (skip-chars-backward "\n \t")
20096 (beginning-of-line)
20097 (if (or (looking-at "\\*+[ \t]+")
20098 (looking-at "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)"))
20099 (progn (goto-char (match-end 0)) (current-column))
20100 (current-indentation))))))
20101 (if (<= (current-column) (current-indentation))
20102 (indent-line-to column)
20103 (save-excursion (indent-line-to column)))))
20105 (defun org-set-autofill-regexps ()
20106 (interactive)
20107 ;; In the paragraph separator we include headlines, because filling
20108 ;; text in a line directly attached to a headline would otherwise
20109 ;; fill the headline as well.
20110 (org-set-local 'comment-start-skip "^#+[ \t]*")
20111 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
20112 ;; The paragraph starter includes hand-formatted lists.
20113 (org-set-local 'paragraph-start
20114 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
20115 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20116 ;; But only if the user has not turned off tables or fixed-width regions
20117 (org-set-local
20118 'auto-fill-inhibit-regexp
20119 (concat "\\*\\|#\\+"
20120 "\\|[ \t]*" org-keyword-time-regexp
20121 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20122 (concat
20123 "\\|[ \t]*["
20124 (if org-enable-table-editor "|" "")
20125 (if org-enable-fixed-width-editor ":" "")
20126 "]"))))
20127 ;; We use our own fill-paragraph function, to make sure that tables
20128 ;; and fixed-width regions are not wrapped. That function will pass
20129 ;; through to `fill-paragraph' when appropriate.
20130 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20131 ; Adaptive filling: To get full control, first make sure that
20132 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20133 (org-set-local 'adaptive-fill-regexp "\000")
20134 (org-set-local 'adaptive-fill-function
20135 'org-adaptive-fill-function))
20137 (defun org-fill-paragraph (&optional justify)
20138 "Re-align a table, pass through to fill-paragraph if no table."
20139 (let ((table-p (org-at-table-p))
20140 (table.el-p (org-at-table.el-p)))
20141 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
20142 (table.el-p t) ; skip table.el tables
20143 (table-p (org-table-align) t) ; align org-mode tables
20144 (t nil)))) ; call paragraph-fill
20146 ;; For reference, this is the default value of adaptive-fill-regexp
20147 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20149 (defun org-adaptive-fill-function ()
20150 "Return a fill prefix for org-mode files.
20151 In particular, this makes sure hanging paragraphs for hand-formatted lists
20152 work correctly."
20153 (cond ((looking-at "#[ \t]+")
20154 (match-string 0))
20155 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
20156 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
20157 (t nil)))
20159 ;;;; Functions extending outline functionality
20161 ;; C-a should go to the beginning of a *visible* line, also in the
20162 ;; new outline.el. I guess this should be patched into Emacs?
20163 (defun org-beginning-of-line ()
20164 "Go to the beginning of the current line. If that is invisible, continue
20165 to a visible line beginning. This makes the function of C-a more intuitive."
20166 (interactive)
20167 (beginning-of-line 1)
20168 (if (bobp)
20170 (backward-char 1)
20171 (if (org-invisible-p)
20172 (while (and (not (bobp)) (org-invisible-p))
20173 (backward-char 1)
20174 (beginning-of-line 1))
20175 (forward-char 1))))
20177 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20179 (defun org-invisible-p ()
20180 "Check if point is at a character currently not visible."
20181 ;; Early versions of noutline don't have `outline-invisible-p'.
20182 (if (fboundp 'outline-invisible-p)
20183 (outline-invisible-p)
20184 (get-char-property (point) 'invisible)))
20186 (defun org-invisible-p2 ()
20187 "Check if point is at a character currently not visible."
20188 (save-excursion
20189 (if (and (eolp) (not (bobp))) (backward-char 1))
20190 ;; Early versions of noutline don't have `outline-invisible-p'.
20191 (if (fboundp 'outline-invisible-p)
20192 (outline-invisible-p)
20193 (get-char-property (point) 'invisible))))
20195 (defalias 'org-back-to-heading 'outline-back-to-heading)
20196 (defalias 'org-on-heading-p 'outline-on-heading-p)
20198 (defun org-on-target-p ()
20199 (or (org-in-regexp org-radio-target-regexp)
20200 (org-in-regexp org-target-regexp)))
20202 (defun org-up-heading-all (arg)
20203 "Move to the heading line of which the present line is a subheading.
20204 This function considers both visible and invisible heading lines.
20205 With argument, move up ARG levels."
20206 (if (fboundp 'outline-up-heading-all)
20207 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20208 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20210 (defun org-goto-sibling (&optional previous)
20211 "Goto the next sibling, even if it is invisible.
20212 When PREVIOUS is set, go to the previous sibling instead. Returns t
20213 when a sibling was found. When none is found, return nil and don't
20214 move point."
20215 (let ((fun (if previous 're-search-backward 're-search-forward))
20216 (pos (point))
20217 (re (concat "^" outline-regexp))
20218 level l)
20219 (org-back-to-heading t)
20220 (setq level (funcall outline-level))
20221 (catch 'exit
20222 (or previous (forward-char 1))
20223 (while (funcall fun re nil t)
20224 (setq l (funcall outline-level))
20225 (when (< l level) (goto-char pos) (throw 'exit nil))
20226 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20227 (goto-char pos)
20228 nil)))
20230 (defun org-show-siblings ()
20231 "Show all siblings of the current headline."
20232 (save-excursion
20233 (while (org-goto-sibling) (org-flag-heading nil)))
20234 (save-excursion
20235 (while (org-goto-sibling 'previous)
20236 (org-flag-heading nil))))
20238 (defun org-show-hidden-entry ()
20239 "Show an entry where even the heading is hidden."
20240 (save-excursion
20241 (org-show-entry)))
20243 (defun org-flag-heading (flag &optional entry)
20244 "Flag the current heading. FLAG non-nil means make invisible.
20245 When ENTRY is non-nil, show the entire entry."
20246 (save-excursion
20247 (org-back-to-heading t)
20248 ;; Check if we should show the entire entry
20249 (if entry
20250 (progn
20251 (org-show-entry)
20252 (save-excursion
20253 (and (outline-next-heading)
20254 (org-flag-heading nil))))
20255 (outline-flag-region (max 1 (1- (point)))
20256 (save-excursion (outline-end-of-heading) (point))
20257 flag))))
20259 (defun org-end-of-subtree (&optional invisible-OK)
20260 ;; This is an exact copy of the original function, but it uses
20261 ;; `org-back-to-heading', to make it work also in invisible
20262 ;; trees. And is uses an invisible-OK argument.
20263 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20264 (org-back-to-heading invisible-OK)
20265 (let ((first t)
20266 (level (funcall outline-level)))
20267 (while (and (not (eobp))
20268 (or first (> (funcall outline-level) level)))
20269 (setq first nil)
20270 (outline-next-heading))
20271 (if (memq (preceding-char) '(?\n ?\^M))
20272 (progn
20273 ;; Go to end of line before heading
20274 (forward-char -1)
20275 (if (memq (preceding-char) '(?\n ?\^M))
20276 ;; leave blank line before heading
20277 (forward-char -1)))))
20278 (point))
20280 (defun org-show-subtree ()
20281 "Show everything after this heading at deeper levels."
20282 (outline-flag-region
20283 (point)
20284 (save-excursion
20285 (outline-end-of-subtree) (outline-next-heading) (point))
20286 nil))
20288 (defun org-show-entry ()
20289 "Show the body directly following this heading.
20290 Show the heading too, if it is currently invisible."
20291 (interactive)
20292 (save-excursion
20293 (org-back-to-heading t)
20294 (outline-flag-region
20295 (max 1 (1- (point)))
20296 (save-excursion
20297 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
20298 (or (match-beginning 1) (point-max)))
20299 nil)))
20301 (defun org-make-options-regexp (kwds)
20302 "Make a regular expression for keyword lines."
20303 (concat
20305 "#?[ \t]*\\+\\("
20306 (mapconcat 'regexp-quote kwds "\\|")
20307 "\\):[ \t]*"
20308 "\\(.+\\)"))
20310 ;; Make isearch reveal the necessary context
20311 (defun org-isearch-end ()
20312 "Reveal context after isearch exits."
20313 (when isearch-success ; only if search was successful
20314 (if (featurep 'xemacs)
20315 ;; Under XEmacs, the hook is run in the correct place,
20316 ;; we directly show the context.
20317 (org-show-context 'isearch)
20318 ;; In Emacs the hook runs *before* restoring the overlays.
20319 ;; So we have to use a one-time post-command-hook to do this.
20320 ;; (Emacs 22 has a special variable, see function `org-mode')
20321 (unless (and (boundp 'isearch-mode-end-hook-quit)
20322 isearch-mode-end-hook-quit)
20323 ;; Only when the isearch was not quitted.
20324 (org-add-hook 'post-command-hook 'org-isearch-post-command
20325 'append 'local)))))
20327 (defun org-isearch-post-command ()
20328 "Remove self from hook, and show context."
20329 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20330 (org-show-context 'isearch))
20333 ;;;; Address problems with some other packages
20335 ;; Make flyspell not check words in links, to not mess up our keymap
20336 (defun org-mode-flyspell-verify ()
20337 "Don't let flyspell put overlays at active buttons."
20338 (not (get-text-property (point) 'keymap)))
20340 ;; Make `bookmark-jump' show the jump location if it was hidden.
20341 (eval-after-load "bookmark"
20342 '(if (boundp 'bookmark-after-jump-hook)
20343 ;; We can use the hook
20344 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20345 ;; Hook not available, use advice
20346 (defadvice bookmark-jump (after org-make-visible activate)
20347 "Make the position visible."
20348 (org-bookmark-jump-unhide))))
20350 (defun org-bookmark-jump-unhide ()
20351 "Unhide the current position, to show the bookmark location."
20352 (and (org-mode-p)
20353 (or (org-invisible-p)
20354 (save-excursion (goto-char (max (point-min) (1- (point))))
20355 (org-invisible-p)))
20356 (org-show-context 'bookmark-jump)))
20358 ;; Make session.el ignore our circular variable
20359 (eval-after-load "session"
20360 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20362 ;;;; Experimental code
20365 ;;;; Finish up
20367 (provide 'org)
20369 (run-hooks 'org-load-hook)
20371 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20372 ;;; org.el ends here