]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-agenda-toggle-time-grid): New command.
[gnu-emacs] / lisp / textmodes / org.el
1 ;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005 Free Software Foundation
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 3.09
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
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.
16
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.
21
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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
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.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke.
80 ;;
81 ;; Changes:
82 ;; -------
83 ;; Version 3.09
84 ;; - Time-of-day specifications in agenda are extracted and placed
85 ;; into the prefix. Timed entries can be placed into a time grid for
86 ;; day.
87 ;;
88 ;; Version 3.08
89 ;; - "|" no longer allowed as part of a link, to allow links in tables.
90 ;; - The prefix of items in the agenda buffer can be configured.
91 ;; - Cleanup.
92 ;;
93 ;; Version 3.07
94 ;; - Some folding incinsistencies removed.
95 ;; - BBDB links to company-only entries.
96 ;; - Bug fixes and global cleanup.
97 ;;
98 ;; Version 3.06
99 ;; - M-S-RET inserts a new TODO heading.
100 ;; - New startup option `content'.
101 ;; - Better visual response when TODO items in agenda change status.
102 ;; - Window positioning after visibility state changes optimized and made
103 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
104 ;;
105 ;; Version 3.05
106 ;; - Agenda entries from the diary are linked to the diary file, so
107 ;; adding and editing diary entries can be done directly from the agenda.
108 ;; - Many calendar/diary commands available directly from agenda.
109 ;; - Field copying in tables with S-RET does increment.
110 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
111 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
112 ;;
113 ;; Version 3.04
114 ;; - Table editor optimized to need fewer realignments, and to keep
115 ;; table shape when typing in fields.
116 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
117 ;; into arbitrary major modes.
118 ;; - Fixed bug with realignment in XEmacs.
119 ;; - Startup options can be set with special #+STARTUP line.
120 ;; - Heading following a match in org-occur can be suppressed.
121 ;;
122 ;; Version 3.03
123 ;; - Copyright transfer to the FSF.
124 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
125 ;; - Timeline now always contains today, and `.' jumps to it.
126 ;; - Table editor:
127 ;; - cut and paste of rectangular regions in tables
128 ;; - command to convert org-mode table to table.el table and back
129 ;; - command to treat several cells like a paragraph and fill it
130 ;; - command to convert a buffer region to a table
131 ;; - import/export tables as tab-separated files (exchange with Excel)
132 ;; - Agenda:
133 ;; - Sorting mechanism for agenda items rewritten from scratch.
134 ;; - Sorting fully configurable.
135 ;; - Entries specifying a time are sorted together.
136 ;; - Completion also covers option keywords after `#-'.
137 ;; - Bug fixes.
138 ;;
139 ;; Version 3.01
140 ;; - New reference card, thanks to Philip Rooke for creating it.
141 ;; - Single file agenda renamed to "Timeline". It no longer shows
142 ;; warnings about upcoming deadlines/overdue scheduled items.
143 ;; That functionality is now limited to the (multifile) agenda.
144 ;; - When reading a date, the calendar can be manipulated with keys.
145 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
146 ;; - Minor bug fixes and documentation improvements.
147
148 ;;; Code:
149
150 (eval-when-compile (require 'cl) (require 'calendar))
151 (require 'outline)
152 (require 'time-date)
153 (require 'easymenu)
154
155 ;;; Customization variables
156
157 (defvar org-version "3.09"
158 "The version number of the file org.el.")
159 (defun org-version ()
160 (interactive)
161 (message "Org-mode version %s" org-version))
162
163 ;; The following two constants are for compatibility with different Emacs
164 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
165 ;; The compatibility code in org.el is based on these two constants.
166 (defconst org-xemacs-p (featurep 'xemacs)
167 "Are we running xemacs?")
168 (defconst org-noutline-p (featurep 'noutline)
169 "Are we using the new outline mode?")
170
171 (defgroup org nil
172 "Outline-based notes management and organizer "
173 :tag "Org"
174 :group 'outlines
175 :group 'hypermedia
176 :group 'calendar)
177
178 (defgroup org-startup nil
179 "Options concerning startup of Org-mode."
180 :tag "Org Startup"
181 :group 'org)
182
183 (defcustom org-startup-folded t
184 "Non-nil means, entering Org-mode will switch to OVERVIEW.
185 This can also be configured on a per-file basis by adding one of
186 the following lines anywhere in the buffer:
187
188 #+STARTUP: fold
189 #+STARTUP: nofold
190 #+STARTUP: content"
191 :group 'org-startup
192 :type '(choice
193 (const :tag "nofold: show all" nil)
194 (const :tag "fold: overview" t)
195 (const :tag "content: all headlines" content)))
196
197 (defcustom org-startup-truncated t
198 "Non-nil means, entering Org-mode will set `truncate-lines'.
199 This is useful since some lines containing links can be very long and
200 uninteresting. Also tables look terrible when wrapped."
201 :group 'org-startup
202 :type 'boolean)
203
204 (defcustom org-startup-with-deadline-check nil
205 "Non-nil means, entering Org-mode will run the deadline check.
206 This means, if you start editing an org file, you will get an
207 immediate reminder of any due deadlines.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
210
211 #+STARTUP: dlcheck
212 #+STARTUP: nodlcheck"
213 :group 'org-startup
214 :type 'boolean)
215
216 (defcustom org-insert-mode-line-in-empty-file nil
217 "Non-nil means insert the first line setting Org-mode in empty files.
218 When the function `org-mode' is called interactively in an empty file, this
219 normally means that the file name does not automatically trigger Org-mode.
220 To ensure that the file will always be in Org-mode in the future, a
221 line enforcing Org-mode will be inserted into the buffer, if this option
222 has been set."
223 :group 'org-startup
224 :type 'boolean)
225
226 (defgroup org-keywords nil
227 "Options concerning TODO items in Org-mode."
228 :tag "Org Keywords"
229 :group 'org)
230
231 (defcustom org-todo-keywords '("TODO" "DONE")
232 "List of TODO entry keywords.
233 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
234 considered to mean that the entry is \"done\". All the other mean that
235 action is required, and will make the entry show up in todo lists, diaries
236 etc.
237 The command \\[org-todo] cycles an entry through these states, and an
238 additional state where no keyword is present. For details about this
239 cycling, see also the variable `org-todo-interpretation'
240 Changes become only effective after restarting Emacs."
241 :group 'org-keywords
242 :type '(repeat (string :tag "Keyword")))
243
244 (defcustom org-todo-interpretation 'sequence
245 "Controls how TODO keywords are interpreted.
246 \\<org-mode-map>Possible values are `sequence' and `type'.
247 This variable is only relevant if `org-todo-keywords' contains more than two
248 states. There are two ways how these keywords can be used:
249
250 - As a sequence in the process of working on a TODO item, for example
251 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
252 org-todo-interpretation 'sequence)
253
254 - As different types of TODO items, for example
255 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
256 org-todo-interpretation 'type)
257
258 When the states are interpreted as a sequence, \\[org-todo] always cycles
259 to the next state, in order to walk through all different states. So with
260 \\[org-todo], you turn an empty entry into the state TODO. When you started
261 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
262 later to VERIFY and finally to DONE.
263
264 When the states are interpreted as types, \\[org-todo] still cycles through
265 when it is called several times in direct succession, in order to initially
266 select the type. However, if not called immediately after a previous
267 \\[org-todo], it switches from each type directly to DONE. So with the
268 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
269 RELAXED. If you later return to this entry and press \\[org-todo] again,
270 RELAXED will not be changed REMIND, but directly to DONE.
271
272 You can create a large number of types. To initially select a
273 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
274 type with completion. Of course, you can also type the keyword
275 directly into the buffer. M-TAB completes TODO keywords at the
276 beginning of a headline."
277 :group 'org-keywords
278 :type '(choice (const sequence)
279 (const type)))
280
281 (defcustom org-default-priority ?B
282 "The default priority of TODO items.
283 This is the priority an item get if no explicit priority is given."
284 :group 'org-keywords
285 :type 'character)
286
287 (defcustom org-lowest-priority ?C
288 "The lowest priority of TODO items. A character like ?A, ?B etc."
289 :group 'org-keywords
290 :type 'character)
291
292 (defcustom org-deadline-string "DEADLINE:"
293 "String to mark deadline entries.
294 A deadline is this string, followed by a time stamp. Should be a word,
295 terminated by a colon. You can insert a schedule keyword and
296 a timestamp with \\[org-deadline].
297 Changes become only effective after restarting Emacs."
298 :group 'org-keywords
299 :type 'string)
300
301 (defcustom org-scheduled-string "SCHEDULED:"
302 "String to mark scheduled TODO entries.
303 A schedule is this string, followed by a time stamp. Should be a word,
304 terminated by a colon. You can insert a schedule keyword and
305 a timestamp with \\[org-schedule].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
309
310 (defcustom org-comment-string "COMMENT"
311 "Entries starting with this keyword will never be exported.
312 An entry can be toggled between COMMENT and normal with
313 \\[org-toggle-comment].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
317
318 (defcustom org-after-todo-state-change-hook nil
319 "Hook which is run after the state of a TODO item was changed.
320 The new state (a string with a todo keyword, or nil) is available in the
321 Lisp variable `state'."
322 :group 'org-keywords
323 :type 'hook)
324
325 ;; Variables for pre-computed regular expressions, all buffer local
326 (defvar org-todo-kwd-priority-p nil
327 "Do TODO items have priorities?")
328 (make-variable-buffer-local 'org-todo-kwd-priority-p)
329 (defvar org-todo-kwd-max-priority nil
330 "Maximum priority of TODO items.")
331 (make-variable-buffer-local 'org-todo-kwd-max-priority)
332 (defvar org-ds-keyword-length 12
333 "Maximum length of the Deadline and SCHEDULED keywords.")
334 (make-variable-buffer-local 'org-ds-keyword-length)
335 (defvar org-done-string nil
336 "The last string in `org-todo-keywords', indicating an item is DONE.")
337 (make-variable-buffer-local 'org-done-string)
338 (defvar org-todo-regexp nil
339 "Matches any of the TODO state keywords.")
340 (make-variable-buffer-local 'org-todo-regexp)
341 (defvar org-not-done-regexp nil
342 "Matches any of the TODO state keywords except the last one.")
343 (make-variable-buffer-local 'org-not-done-regexp)
344 (defvar org-todo-line-regexp nil
345 "Matches a headline and puts TODO state into group 2 if present.")
346 (make-variable-buffer-local 'org-todo-line-regexp)
347 (defvar org-nl-done-regexp nil
348 "Matches newline followed by a headline with the DONE keyword.")
349 (make-variable-buffer-local 'org-nl-done-regexp)
350 (defvar org-looking-at-done-regexp nil
351 "Matches the DONE keyword a point.")
352 (make-variable-buffer-local 'org-looking-at-done-regexp)
353 (defvar org-deadline-regexp nil
354 "Matches the DEADLINE keyword.")
355 (make-variable-buffer-local 'org-deadline-regexp)
356 (defvar org-deadline-time-regexp nil
357 "Matches the DEADLINE keyword together with a time stamp.")
358 (make-variable-buffer-local 'org-deadline-time-regexp)
359 (defvar org-deadline-line-regexp nil
360 "Matches the DEADLINE keyword and the rest of the line.")
361 (make-variable-buffer-local 'org-deadline-line-regexp)
362 (defvar org-scheduled-regexp nil
363 "Matches the SCHEDULED keyword.")
364 (make-variable-buffer-local 'org-scheduled-regexp)
365 (defvar org-scheduled-time-regexp nil
366 "Matches the SCHEDULED keyword together with a time stamp.")
367 (make-variable-buffer-local 'org-scheduled-time-regexp)
368
369 (defvar org-category nil
370 "Variable used by org files to set a category for agenda display.
371 Such files should use a file variable to set it, for example
372
373 -*- mode: org; org-category: \"ELisp\"
374
375 If the file does not specify a category, the file's base name
376 is used instead.")
377
378 (defun org-set-regexps-and-options ()
379 "Precompute regular expressions for current buffer."
380 (when (eq major-mode 'org-mode)
381 (let ((re (org-make-options-regexp
382 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP")))
383 (splitre "[ \t]+")
384 kwds int key value cat)
385 (save-excursion
386 (save-restriction
387 (widen)
388 (goto-char (point-min))
389 (while (re-search-forward re nil t)
390 (setq key (match-string 1) value (match-string 2))
391 (cond
392 ((equal key "CATEGORY")
393 (if (string-match "[ \t]+$" value)
394 (setq value (replace-match "" t t value)))
395 (setq cat (intern value)))
396 ((equal key "SEQ_TODO")
397 (setq int 'sequence
398 kwds (append kwds (org-split-string value splitre))))
399 ((equal key "PRI_TODO")
400 (setq int 'priority
401 kwds (append kwds (org-split-string value splitre))))
402 ((equal key "TYP_TODO")
403 (setq int 'type
404 kwds (append kwds (org-split-string value splitre))))
405 ((equal key "STARTUP")
406 (let ((opts (org-split-string value splitre))
407 (set '(("fold" org-startup-folded t)
408 ("nofold" org-startup-folded nil)
409 ("content" org-startup-folded content)
410 ("dlcheck" org-startup-with-deadline-check t)
411 ("nodlcheck" org-startup-with-deadline-check nil)))
412 l var val)
413 (while (setq l (assoc (pop opts) set))
414 (setq var (nth 1 l) val (nth 2 l))
415 (set (make-local-variable var) val)))))
416 )))
417 (and cat (set (make-local-variable 'org-category) cat))
418 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
419 (and int (set (make-local-variable 'org-todo-interpretation) int)))
420 ;; Compute the regular expressions and other local variables
421 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
422 org-todo-kwd-max-priority (1- (length org-todo-keywords))
423 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
424 (length org-scheduled-string)))
425 org-done-string
426 (nth (1- (length org-todo-keywords)) org-todo-keywords)
427 org-todo-regexp
428 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
429 "\\|") "\\)\\>")
430 org-not-done-regexp
431 (concat "\\<\\("
432 (mapconcat 'regexp-quote
433 (nreverse (cdr (reverse org-todo-keywords)))
434 "\\|")
435 "\\)\\>")
436 org-todo-line-regexp
437 (concat "^\\(\\*+\\)[ \t]*\\("
438 (mapconcat 'regexp-quote org-todo-keywords "\\|")
439 "\\)? *\\(.*\\)")
440 org-nl-done-regexp
441 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
442 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
443 org-deadline-regexp (concat "\\<" org-deadline-string)
444 org-deadline-time-regexp
445 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
446 org-deadline-line-regexp
447 (concat "\\<\\(" org-deadline-string "\\).*")
448 org-scheduled-regexp
449 (concat "\\<" org-scheduled-string)
450 org-scheduled-time-regexp
451 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
452 (org-set-font-lock-defaults)))
453
454 (defgroup org-time nil
455 "Options concerning time stamps and deadlines in Org-mode."
456 :tag "Org Time"
457 :group 'org)
458
459 (defcustom org-deadline-warning-days 30
460 "No. of days before expiration during which a deadline becomes active.
461 This variable governs the display in the org file."
462 :group 'org-time
463 :type 'number)
464
465 (defcustom org-popup-calendar-for-date-prompt t
466 "Non-nil means, pop up a calendar when prompting for a date.
467 In the calendar, the date can be selected with mouse-1. However, the
468 minibuffer will also be active, and you can simply enter the date as well.
469 When nil, only the minibuffer will be available."
470 :group 'org-time
471 :type 'number)
472
473 (defcustom org-calendar-follow-timestamp-change t
474 "Non-nil means, make the calendar window follow timestamp changes.
475 When a timestamp is modified and the calendar window is visible, it will be
476 moved to the new date."
477 :group 'org-time
478 :type 'boolean)
479
480 (defgroup org-agenda nil
481 "Options concerning agenda display Org-mode."
482 :tag "Org Agenda"
483 :group 'org)
484
485 (defcustom org-agenda-files nil
486 "A list of org files for agenda/diary display.
487 Entries are added to this list with \\[org-add-file] and removed with
488 \\[org-remove-file]. You can also use customize to edit the list."
489 :group 'org-agenda
490 :type '(repeat file))
491
492 (defcustom org-select-timeline-window t
493 "Non-nil means, after creating a timeline, move cursor into Timeline window.
494 When nil, cursor will remain in the current window."
495 :group 'org-agenda
496 :type 'boolean)
497
498 (defcustom org-select-agenda-window t
499 "Non-nil means, after creating an agenda, move cursor into Agenda window.
500 When nil, cursor will remain in the current window."
501 :group 'org-agenda
502 :type 'boolean)
503
504 (defcustom org-fit-agenda-window t
505 "Non-nil means, change window size of agenda to fit content."
506 :group 'org-agenda
507 :type 'boolean)
508
509 (defcustom org-agenda-show-all-dates t
510 "Non-nil means, `org-agenda' shows every day in the selected range.
511 When nil, only the days which actually have entries are shown."
512 :group 'org-agenda
513 :type 'boolean)
514
515 ;; FIXME: First day of month works only for current month because it would
516 ;; require a variable ndays treatment.
517 (defcustom org-agenda-start-on-weekday 1
518 "Non-nil means, start the overview always on the specified weekday.
519 0 Denotes Sunday, 1 denotes Monday etc.
520 When nil, always start on the current day."
521 :group 'org-agenda
522 :type '(choice (const :tag "Today" nil)
523 (const :tag "First day of month" t)
524 (number :tag "Weekday No.")))
525
526 (defcustom org-agenda-ndays 7
527 "Number of days to include in overview display."
528 :group 'org-agenda
529 :type 'number)
530
531 (defcustom org-agenda-include-all-todo t
532 "Non-nil means, the agenda will always contain all TODO entries.
533 When nil, date-less entries will only be shown if `org-agenda' is called
534 with a prefix argument.
535 When non-nil, the TODO entries will be listed at the top of the agenda, before
536 the entries for specific days."
537 :group 'org-agenda
538 :type 'boolean)
539
540 (defcustom org-agenda-include-diary nil
541 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
542 :group 'org-agenda
543 :type 'boolean)
544
545 (defcustom org-calendar-to-agenda-key [?c]
546 "The key to be installed in `calendar-mode-map' for switching to the agenda.
547 The command `org-calendar-goto-agenda' will be bound to this key. The
548 default is the character `c' because then`c' can be used to switch back and
549 force between agenda and calendar."
550 :group 'org-agenda
551 :type 'sexp)
552
553 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
554 "Sorting structure for the agenda items of a single day.
555 This is a list of symbols which will be used in sequence to determine
556 if an entry should be listed before another entry. The following
557 symbols are recognized.
558
559 time-up Put entries with time-of-day indications first, early first
560 time-down Put entries with time-of-day indications first, late first
561 category-keep Keep the default order of categories, corresponding to the
562 sequence in `org-agenda-files'.
563 category-up Sort alphabetically by category, A-Z.
564 category-down Sort alphabetically by category, Z-A.
565 priority-up Sort numerically by priority, high priority last.
566 priority-down Sort numerically by priority, high priority first.
567
568 The different possibilities will be tried in sequence, and testing stops
569 if one comparison returns a \"not-equal\". For example, the default
570 '(time-up category-keep priority-down)
571 means: Pull out all entries having a specified time of day and sort them,
572 in order to make a time schedule for the current day the first thing in the
573 agenda listing for the day. Of the entries without a time indication, keep
574 the grouped in categories, don't sort the categories, but keep them in
575 the sequence given in `org-agenda-files'. Within each category sort by
576 priority.
577
578 Leaving out `category-keep' would mean that items will be sorted across
579 categories by priority."
580 :group 'org-agenda
581 :type '(repeat
582 (choice
583 (const time-up)
584 (const time-down)
585 (const category-keep)
586 (const category-up)
587 (const category-down)
588 (const priority-up)
589 (const priority-down))))
590
591 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
592 "Format specification for the prefix of items in the agenda buffer.
593 This format works similar to a printf format, with the following meaning:
594
595 %c the category of the item, \"Diary\" for entries from the diary, or
596 as given by the CATEGORY keyword or derived from the file name.
597 %t the time-of-day specification if one applies to the entry, in the
598 format HH:MM
599 %s Scheduling/Deadline information, a short string
600
601 All specifiers work basically like the standard `%s' of printf, but may
602 contain two additional characters: A question mark just after the `%' and
603 a whitespace/punctuation character just before the final letter.
604
605 If the first character after `%' is a question mark, the entire field
606 will only be included if the corresponding value applies to the
607 current entry. This is useful for fields which should have fixed
608 width when present, but zero width when absent. For example,
609 \"%?-12t\" will result in a 12 character time field if a time of the
610 day is specified, but will completely disappear in entries which do
611 not contain a time.
612
613 If there is punctuation or whitespace character just before the final
614 format letter, this character will be appended to the field value if
615 the value is not empty. For example, the format \"%-12:c\" leads to
616 \"Diary: \" if the category is \"Diary\". If the category were be
617 empty, no additional colon would be interted.
618
619 The default value of this option is \" %-12:c%?-12t% s\", meaning:
620 - Indent the line with two space characters
621 - Give the category in a 12 chars wide field, padded with whitespace on
622 the right (because of `-'). Append a colon if there is a category
623 (because of `:').
624 - If there is a time-of-day, put it into a 12 chars wide field. If no
625 time, don't put in an empty field, just skip it (because of '?').
626 - Finally, put the scheduling information and append a whitespace.
627
628 As another example, if you don't want the time-of-day of entries in
629 the prefix, you could use:
630
631 (setq org-agenda-prefix-format \" %-11:c% s\")
632
633 See also the variable `org-agenda-remove-times-when-in-prefix'."
634 :type 'string
635 :group 'org-agenda)
636
637 (defcustom org-timeline-prefix-format " % s"
638 "Like `org-agenda-prefix-format', but for the timeline of a single file."
639 :type 'string
640 :group 'org-agenda)
641
642 (defvar org-prefix-format-compiled nil
643 "The compiled version of the most recently used prefix format.
644 Depending on which command was used last, this may be the compiled version
645 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
646
647 (defcustom org-agenda-use-time-grid t
648 "Non-nil means, show a time grid in the agenda schedule.
649 A time grid is a set of lines for specific times (like every two hours between
650 8:00 and 20:00. The items scheduled for a day at specific times are
651 sorted in between these lines.
652 For deails about when the grid will be shown, and what it will look like, see
653 the variable `org-agenda-time-grid'."
654 :group 'org-agenda
655 :type 'boolean)
656
657 (defcustom org-agenda-time-grid
658 '((daily today require-timed)
659 "----------------"
660 (800 1000 1200 1400 1600 1800 2000))
661
662 "FIXME: document"
663 :group 'org-agenda
664 :type
665 '(list
666 (set :greedy t :tag "Grid Display Options"
667 (const :tag "Show grid in single day agenda display" daily)
668 (const :tag "Show grid in weekly agenda display" weekly)
669 (const :tag "Always show grid for today" today)
670 (const :tag "Show grid only if any timed entries are present"
671 require-timed)
672 (const :tag "Skip grid times already present in an entry"
673 remove-match))
674 (string :tag "Grid String")
675 (repeat :tag "Grid Times" (integer :tag "Time"))))
676
677 (defcustom org-agenda-remove-times-when-in-prefix t
678 "Non-nil means, remove duplicate time specifications in agenda items.
679 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
680 time-of-day specification in a headline or diary entry is extracted and
681 placed into the prefix. If this option is non-nil, the original specification
682 \(a timestamp or -range, or just a plain time(range) specification like
683 11:30-4pm) will be removed for agenda display. This makes the agenda less
684 cluttered.
685 The option can be t or nil. It may also be the symbol `beg', indicating
686 that the time should only be removed what it is located at the beginning of
687 the headline/diary entry."
688 :group 'org-agenda
689 :type '(choice
690 (const :tag "Always" t)
691 (const :tag "Never" nil)
692 (const :tag "When at beginning of entry" beg)))
693
694 (defcustom org-sort-agenda-notime-is-late t
695 "Non-nil means, items without time are considered late.
696 This is only relevant for sorting. When t, items which have no explicit
697 time like 15:30 will be considered as 24:01, i.e. later than any items which
698 do have a time. When nil, the default time is before 0:00. You can use this
699 option to decide if the schedule for today should come before or after timeless
700 agenda entries."
701 :group 'org-agenda
702 :type 'boolean)
703
704 (defgroup org-structure nil
705 "Options concerning structure editing in Org-mode."
706 :tag "Org Structure"
707 :group 'org)
708
709 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
710 "Hook that is run after `org-cycle' has changed the buffer visibility.
711 The function(s) in this hook must accept a single argument which indicates
712 the new state that was set by the most recent `org-cycle' command. The
713 argument is a symbol. After a global state change, it can have the values
714 `overview', `content', or `all'. After a local state change, it can have
715 the values `folded', `children', or `subtree'."
716 :group 'org-structure
717 :type 'hook)
718
719 (defcustom org-occur-hook '(org-first-headline-recenter)
720 "Hook that is run after `org-occur' has constructed a sparse tree.
721 This can be used to recenter the window to show as much of the structure
722 as possible."
723 :group 'org-structure
724 :type 'hook)
725
726 (defcustom org-adapt-indentation t
727 "Non-nil means, adapt indentation when promoting and demoting.
728 When this is set and the *entire* text in an entry is indented, the
729 indentation is increased by one space in a demotion command, and
730 decreased by one in a promotion command. If any line in the entry
731 body starts at column 0, indentation is not changed at all."
732 :group 'org-structure
733 :type 'boolean)
734
735 (defcustom org-cycle-emulate-tab t
736 "Where should `org-cycle' emulate TAB.
737 nil Never
738 white Only in completely white lines
739 t Everywhere except in headlines"
740 :group 'org-structure
741 :type '(choice (const :tag "Never" nil)
742 (const :tag "Only in completely white lines" white)
743 (const :tag "Everywhere except in headlines" t)
744 ))
745
746 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
747 "Formats for `format-time-string' which are used for time stamps.
748 It is not recommended to change this constant.")
749
750 (defcustom org-show-following-heading t
751 "Non-nil means, show heading following match in `org-occur'.
752 When doing an `org-occur' it is useful to show the headline which
753 follows the match, even if they do not match the regexp. This makes it
754 easier to edit directly inside the sparse tree. However, if you use
755 org-occur mainly as an overview, the following headlines are
756 unnecessary clutter."
757 :group 'org-structure
758 :type 'boolean)
759
760
761 (defgroup org-link nil
762 "Options concerning links in Org-mode."
763 :tag "Org Link"
764 :group 'org)
765
766 (defcustom org-allow-space-in-links t
767 "Non-nil means, file names in links may contain space characters.
768 When nil, it becomes possible to put several links into a line.
769 Note that in tables, a link never extends accross fields, so in a table
770 it is always possible to put several links into a line.
771 Changing this varable requires a re-launch of Emacs of become effective."
772 :group 'org-link
773 :type 'boolean)
774
775 (defcustom org-line-numbers-in-file-links t
776 "Non-nil means, file links from `org-store-link' contain line numbers.
777 The line number will be added to the file name with :NNN and interpreted
778 by the command `org-open-at-point'.
779 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
780 negates this setting for the duration of the command."
781 :group 'org-link
782 :type 'boolean)
783
784 (defcustom org-keep-stored-link-after-insertion nil
785 "Non-nil means, keep link in list for entire session.
786
787 The command `org-store-link' adds a link pointing to the current
788 location to an internal list. These links accumulate during a session.
789 The command `org-insert-link' can be used to insert links into any
790 Org-mode file (offering completion for all stored links). When this
791 option is nil, every link which has been inserted once using \\[org-insert-link]
792 will be removed from the list, to make completing the unused links
793 more efficient."
794 :group 'org-link
795 :type 'boolean)
796
797 (defcustom org-link-frame-setup
798 '((vm . vm-visit-folder-other-frame)
799 (gnus . gnus-other-frame)
800 (file . find-file-other-window))
801 "Setup the frame configuration for following links.
802 When following a link with Emacs, it may often be useful to display
803 this link in another window or frame. This variable can be used to
804 set this up for the different types of links.
805 For VM, use any of
806 `vm-visit-folder'
807 `vm-visit-folder-other-frame'
808 For Gnus, use any of
809 `gnus'
810 `gnus-other-frame'
811 For FILE, use any of
812 `find-file'
813 `find-file-other-window'
814 `find-file-other-frame'
815 For the calendar, use the variable `calendar-setup'.
816 For BBDB, it is currently only possible to display the matches in
817 another window."
818 :group 'org-link
819 :type '(list
820 (cons (const vm)
821 (choice
822 (const vm-visit-folder)
823 (const vm-visit-folder-other-window)
824 (const vm-visit-folder-other-frame)))
825 (cons (const gnus)
826 (choice
827 (const gnus)
828 (const gnus-other-frame)))
829 (cons (const file)
830 (choice
831 (const find-file)
832 (const find-file-other-window)
833 (const find-file-other-frame)))))
834
835 (defcustom org-usenet-links-prefer-google nil
836 "Non-nil means, `org-store-link' will create web links to google groups.
837 When nil, Gnus will be used for such links.
838 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
839 negates this setting for the duration of the command."
840 :group 'org-link
841 :type 'boolean)
842
843 (defcustom org-open-non-existing-files nil
844 "Non-nil means, `org-open-file' will open non-existing file.
845 When nil, an error will be generated."
846 :group 'org-link
847 :type 'boolean)
848
849 (defcustom org-confirm-shell-links t
850 "Non-nil means, ask for confirmation before executing shell links.
851 The default is true, to keep new users from shooting into their own foot."
852 :group 'org-link
853 :type 'boolean)
854
855 (defconst org-file-apps-defaults-linux
856 '((t . emacs)
857 ("jpg" . "xv %s")
858 ("gif" . "xv %s")
859 ("ppm" . "xv %s")
860 ("pgm" . "xv %s")
861 ("pbm" . "xv %s")
862 ("tif" . "xv %s")
863 ("png" . "xv %s")
864 ("ps" . "gv %s")
865 ("ps.gz" . "gv %s")
866 ("eps" . "gv %s")
867 ("eps.gz" . "gv %s")
868 ("dvi" . "xdvi %s")
869 ("mpeg" . "plaympeg %s")
870 ("mp3" . "plaympeg %s")
871 ("fig" . "xfig %s")
872 ("pdf" . "acroread %s")
873 ("doc" . "soffice %s")
874 ("ppt" . "soffice %s")
875 ("pps" . "soffice %s")
876 ("html" . "netscape -remote openURL(%s,new-window)")
877 ("htm" . "netscape -remote openURL(%s,new-window)")
878 ("xs" . "soffice %s"))
879 "Default file applications on a UNIX/LINUX system.
880 See `org-file-apps'.")
881
882 (defconst org-file-apps-defaults-macosx
883 '((t . "open %s")
884 ("ps" . "gv %s")
885 ("ps.gz" . "gv %s")
886 ("eps" . "gv %s")
887 ("eps.gz" . "gv %s")
888 ("dvi" . "xdvi %s")
889 ("fig" . "xfig %s"))
890 "Default file applications on a MacOS X system.
891 The system \"open\" is known as a default, but we use X11 applications
892 for some files for which the OS does not have a good default.
893 See `org-file-apps'.")
894
895 (defconst org-file-apps-defaults-windowsnt
896 '((t . (w32-shell-execute "open" file)))
897 "Default file applications on a Windows NT system.
898 The system \"open\" is used for most files.
899 See `org-file-apps'.")
900
901 (defcustom org-file-apps
902 '(
903 ("txt" . emacs)
904 ("tex" . emacs)
905 ("ltx" . emacs)
906 ("org" . emacs)
907 ("el" . emacs)
908 )
909 "External applications for opening `file:path' items in a document.
910 Org-mode uses system defaults for different file types, but
911 you can use this variable to set the application for a given file
912 extension. The entries in this list are cons cells with a file extension
913 and the corresponding command. Possible values for the command are:
914 `emacs' The file will be visited by the current Emacs process.
915 `default' Use the default application for this file type.
916 string A command to be executed by a shell; %s will be replaced
917 by the path to the file.
918 sexp A Lisp form which will be evaluated. The file path will
919 be available in the Lisp variable `file'.
920 For more examples, see the system specific constants
921 `org-file-apps-defaults-macosx'
922 `org-file-apps-defaults-windowsnt'
923 `org-file-apps-defaults-linux'."
924 :group 'org-link
925 :type '(repeat
926 (cons (string :tag "Extension")
927 (choice :value ""
928 (const :tag "Visit with Emacs" 'emacs)
929 (const :tag "Use system default" 'default)
930 (string :tag "Command")
931 (sexp :tag "Lisp form")))))
932
933
934 (defgroup org-remember nil
935 "Options concerning interaction with remember.el."
936 :tag "Org Remember"
937 :group 'org)
938
939 (defcustom org-directory "~/org"
940 "Directory with org files.
941 This directory will be used as default to prompt for org files.
942 Used by the hooks for remember.el."
943 :group 'org-remember
944 :type 'directory)
945
946 (defcustom org-default-notes-file "~/.notes"
947 "Default target for storing notes.
948 Used by the hooks for remember.el. This can be a string, or nil to mean
949 the value of `remember-data-file'."
950 :group 'org-remember
951 :type '(choice
952 (const :tag "Default from remember-data-file" nil)
953 file))
954
955 (defcustom org-reverse-note-order nil
956 "Non-nil means, store new notes at the beginning of a file or entry.
957 When nil, new notes will be filed to the end of a file or entry."
958 :group 'org-remember
959 :type '(choice
960 (const :tag "Reverse always" t)
961 (const :tag "Reverse never" nil)
962 (repeat :tag "By file name regexp"
963 (cons regexp boolean))))
964
965 (defgroup org-table nil
966 "Options concerning tables in Org-mode."
967 :tag "Org Table"
968 :group 'org)
969
970 (defcustom org-enable-table-editor 'optimized
971 "Non-nil means, lines starting with \"|\" are handled by the table editor.
972 When nil, such lines will be treated like ordinary lines.
973
974 When equal to the symbol `optimized', the table editor will be optimized to
975 do the following
976 - Use automatic overwrite mode in front of whitespace in table fields.
977 This make the structure of the table stay in tact as long as the edited
978 field does not exceed the column width.
979 - Minimize the number of realigns. Normally, the table is aligned each time
980 TAB or RET are pressed to move to another field. With optimization this
981 happens only if changes to a field might have changed the column width.
982 Optimization requires replacing the functions `self-insert-command',
983 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
984 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
985 very good at guessing when a re-align will be necessary, but you can always
986 force one with `C-c C-c'.
987
988 If you would like to use the optimized version in Org-mode, but the
989 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
990
991 This variable can be used to turn on and off the table editor during a session,
992 but in order to toggle optimization, a restart is required."
993 :group 'org-table
994 :type '(choice
995 (const :tag "off" nil)
996 (const :tag "on" t)
997 (const :tag "on, optimized" optimized)))
998
999 (defcustom org-table-default-size "5x2"
1000 "The default size for newly created tables, Columns x Rows."
1001 :group 'org-table
1002 :type 'string)
1003
1004 (defcustom org-table-automatic-realign t
1005 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1006 When nil, aligning is only done with \\[org-table-align], or after column
1007 removal/insertion."
1008 :group 'org-table
1009 :type 'boolean)
1010
1011 (defcustom org-table-spaces-around-separators '(1 . 1)
1012 "The number of spaces to be placed before and after separators."
1013 :group 'org-table
1014 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1015
1016 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1017 "The number of spaces to be placed before and after separators.
1018 This option applies when the column separators have been made invisible."
1019 :group 'org-table
1020 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1021
1022 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1023 "Regular expression for recognizing numbers in table columns.
1024 If a table column contains mostly numbers, it will be aligned to the
1025 right. If not, it will be aligned to the left.
1026
1027 The default value of this option is a regular expression which allows
1028 anything which looks remotely like a number as used in scientific
1029 context. For example, all of the following will be considered a
1030 number:
1031 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1032
1033 Other options offered by the customize interface are more restrictive."
1034 :group 'org-table
1035 :type '(choice
1036 (const :tag "Positive Integers"
1037 "^[0-9]+$")
1038 (const :tag "Integers"
1039 "^[-+]?[0-9]+$")
1040 (const :tag "Floating Point Numbers"
1041 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1042 (const :tag "Floating Point Number or Integer"
1043 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1044 (const :tag "Exponential, Floating point, Integer"
1045 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1046 (const :tag "Very General Number-Like"
1047 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1048 (string :tag "Regexp:")))
1049
1050 (defcustom org-table-number-fraction 0.5
1051 "Fraction of numbers in a column required to make the column align right.
1052 In a column all non-white fields are considered. If at least this
1053 fraction of fields is matched by `org-table-number-fraction',
1054 alignment to the right border applies."
1055 :group 'org-table
1056 :type 'number)
1057
1058 (defcustom org-export-highlight-first-table-line t
1059 "Non-nil means, highlight the first table line.
1060 In HTML export, this means use <th> instead of <td>.
1061 In tables created with table.el, this applies to the first table line.
1062 In Org-mode tables, all lines before the first horizontal separator
1063 line will be formatted with <th> tags."
1064 :group 'org-table
1065 :type 'boolean)
1066
1067 (defcustom org-table-copy-increment t
1068 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1069 :group 'org-table
1070 :type 'boolean)
1071
1072 (defcustom org-table-tab-recognizes-table.el t
1073 "Non-nil means, TAB will automatically notice a table.el table.
1074 When it sees such a table, it moves point into it and - if necessary -
1075 calls `table-recognize-table'."
1076 :group 'org-table
1077 :type 'boolean)
1078
1079 (defcustom org-export-prefer-native-exporter-for-tables nil
1080 "Non-nil means, always export tables created with table.el natively.
1081 Natively means, use the HTML code generator in table.el.
1082 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1083 the table does not use row- or column-spanning). This has the
1084 advantage, that the automatic HTML conversions for math symbols and
1085 sub/superscripts can be applied. Org-mode's HTML generator is also
1086 much faster."
1087 :group 'org-table
1088 :type 'boolean)
1089
1090 (defcustom org-enable-fixed-width-editor t
1091 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1092 This currently only means, they are never auto-wrapped.
1093 When nil, such lines will be treated like ordinary lines."
1094 :group 'org-table
1095 :type 'boolean)
1096
1097 (defgroup org-export nil
1098 "Options for exporting org-listings."
1099 :tag "Org Export"
1100 :group 'org)
1101
1102 (defcustom org-export-language-setup
1103 '(("en" "Author" "Date" "Table of Contents")
1104 ("da" "Ophavsmand" "Dato" "Indhold")
1105 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1106 ("es" "Autor" "Fecha" "\xccndice")
1107 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1108 ("it" "Autore" "Data" "Indice")
1109 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1110 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1111 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1112 "Terms used in export text, translated to different languages.
1113 Use the variable `org-export-default-language' to set the language,
1114 or use the +OPTION lines for a per-file setting."
1115 :group 'org-export
1116 :type '(repeat
1117 (list
1118 (string :tag "HTML language tag")
1119 (string :tag "Author")
1120 (string :tag "Date")
1121 (string :tag "Table of Contents"))))
1122
1123 (defcustom org-export-default-language "en"
1124 "The default language of HTML export, as a string.
1125 This should have an association in `org-export-language-setup'"
1126 :group 'org-export
1127 :type 'string)
1128
1129 (defcustom org-export-headline-levels 3
1130 "The last level which is still exported as a headline.
1131 Inferior levels will produce itemize lists when exported.
1132 Note that a numeric prefix argument to an exporter function overrides
1133 this setting.
1134
1135 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1136 :group 'org-export
1137 :type 'number)
1138
1139 (defcustom org-export-with-section-numbers t
1140 "Non-nil means, add section numbers to headlines when exporting.
1141
1142 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1143 :group 'org-export
1144 :type 'boolean)
1145
1146 (defcustom org-export-with-toc t
1147 "Non-nil means, create a table of contents in exported files.
1148 The TOC contains headlines with levels up to`org-export-headline-levels'.
1149
1150 Headlines which contain any TODO items will be marked with \"(*)\" in
1151 ASCII export, and with red color in HTML output.
1152
1153 In HTML output, the TOC will be clickable.
1154
1155 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1156 :group 'org-export
1157 :type 'boolean)
1158
1159 (defcustom org-export-preserve-breaks nil
1160 "Non-nil means, preserve all line breaks when exporting.
1161 Normally, in HTML output paragraphs will be reformatted. In ASCII
1162 export, line breaks will always be preserved, regardless of this variable.
1163
1164 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1165 :group 'org-export
1166 :type 'boolean)
1167
1168 (defcustom org-export-html-inline-images t
1169 "Non-nil means, inline images into exported HTML pages.
1170 The link will still be to the original location of the image file.
1171 So if you are moving the page, lets say to your public HTML site,
1172 you will have to move the image and maybe change the link."
1173 :group 'org-export
1174 :type 'boolean)
1175
1176 (defcustom org-export-html-expand t
1177 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1178 When nil, these tags will be exported as plain text and therefore
1179 not be interpreted by a browser.
1180
1181 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1182 :group 'org-export
1183 :type 'boolean)
1184
1185 (defcustom org-export-with-fixed-width t
1186 "Non-nil means, lines starting with \":\" will be in fixed width font.
1187 This can be used to have pre-formatted text, fragments of code etc. For
1188 example
1189 : ;; Some Lisp examples
1190 : (while (defc cnt)
1191 : (ding))
1192 will be looking just like this in also HTML. In ASCII export, this option
1193 has no effect.
1194
1195 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1196 :group 'org-export
1197 :type 'boolean)
1198
1199 (defcustom org-export-with-tables t
1200 "If non-nil, lines starting with \"|\" define a table.
1201 For example:
1202
1203 | Name | Address | Birthday |
1204 |-------------+----------+-----------|
1205 | Arthur Dent | England | 29.2.2100 |
1206
1207 In ASCII export, this option has no effect.
1208
1209 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1210 :group 'org-export
1211 :type 'boolean)
1212
1213 (defcustom org-export-html-table-tag
1214 "<table border=1 cellspacing=0 cellpadding=6>"
1215 "The HTML tag used to start a table.
1216 This must be a <table> tag, but you may change the options like
1217 borders and spacing."
1218 :group 'org-export
1219 :type 'string)
1220
1221 (defcustom org-export-with-emphasize t
1222 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1223 If the export target supports emphasizing text, the word will be
1224 typeset in bold, italic, or underlined, respectively. Works only for
1225 single words, but you can say: I *really* *mean* *this*.
1226 In ASCII export, this option has no effect.
1227
1228 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1229 :group 'org-export
1230 :type 'boolean)
1231
1232 (defcustom org-match-sexp-depth 3
1233 "Number of stacked braces for sub/superscript matching.
1234 This has to be set before loading org.el to be effective."
1235 :group 'org-export
1236 :type 'integer)
1237
1238 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1239 (defcustom org-export-with-sub-superscripts t
1240 "Non-nil means, interpret \"_\" and \"^\" for export.
1241 When this option is turned on, you can use TeX-like syntax for sub- and
1242 superscripts. Several characters after \"_\" or \"^\" will be
1243 considered as a single item - so grouping with {} is normally not
1244 needed. For example, the following things will be parsed as single
1245 sub- or superscripts.
1246
1247 10^24 or 10^tau several digits will be considered 1 item
1248 10^-12 or 10^-tau a leading sign with digits or a word
1249 x^2-y^3 will be read as x^2 - y^3, because items are
1250 terminated by almost any nonword/nondigit char.
1251 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1252
1253 Still, ambiguity is possible - so when in doubt use {} to enclose the
1254 sub/superscript.
1255 In ASCII export, this option has no effect.
1256
1257 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1258 :group 'org-export
1259 :type 'boolean)
1260
1261 (defcustom org-export-with-TeX-macros t
1262 "Non-nil means, interpret simple TeX-like macros when exporting.
1263 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1264 No only real TeX macros will work here, but the standard HTML entities
1265 for math can be used as macro names as well. For a list of supported
1266 names in HTML export, see the constant `org-html-entities'.
1267 In ASCII export, this option has no effect.
1268
1269 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1270 :group 'org-export
1271 :type 'boolean)
1272
1273 (defcustom org-export-html-with-timestamp nil
1274 "If non-nil, write `org-export-html-html-helper-timestamp'
1275 into the exported html text. Otherwise, the buffer will just be saved
1276 to a file."
1277 :group 'org-export
1278 :type 'boolean)
1279
1280 (defcustom org-export-html-html-helper-timestamp
1281 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1282 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1283 :group 'org-export
1284 :type 'string)
1285
1286 (defcustom org-export-ascii-show-new-buffer t
1287 "Non-nil means, popup buffer containing the exported ASCII text.
1288 Otherwise the buffer will just be saved to a file and stay hidden."
1289 :group 'org-export
1290 :type 'boolean)
1291
1292 (defcustom org-export-html-show-new-buffer nil
1293 "Non-nil means, popup buffer containing the exported html text.
1294 Otherwise, the buffer will just be saved to a file and stay hidden."
1295 :group 'org-export
1296 :type 'boolean)
1297
1298
1299 (defgroup org-faces nil
1300 "Faces for highlighting in Org-mode."
1301 :tag "Org Faces"
1302 :group 'org)
1303
1304 (defface org-level-1-face ;; font-lock-function-name-face
1305 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1306 (((class color) (background light)) (:foreground "Blue"))
1307 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1308 (t (:inverse-video t :bold t)))
1309 "Face used for level 1 headlines."
1310 :group 'org-faces)
1311
1312 (defface org-level-2-face ;; font-lock-variable-name-face
1313 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1314 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1315 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1316 (t (:bold t :italic t)))
1317 "Face used for level 2 headlines."
1318 :group 'org-faces)
1319
1320 (defface org-level-3-face ;; font-lock-keyword-face
1321 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1322 (((class color) (background light)) (:foreground "Purple"))
1323 (((class color) (background dark)) (:foreground "Cyan"))
1324 (t (:bold t)))
1325 "Face used for level 3 headlines."
1326 :group 'org-faces)
1327
1328 (defface org-level-4-face ;; font-lock-comment-face
1329 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1330 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1331 (((class color) (background light)) (:foreground "Firebrick"))
1332 (((class color) (background dark)) (:foreground "chocolate1"))
1333 (t (:bold t :italic t)))
1334 "Face used for level 4 headlines."
1335 :group 'org-faces)
1336
1337 (defface org-level-5-face ;; font-lock-type-face
1338 '((((type tty) (class color)) (:foreground "green"))
1339 (((class color) (background light)) (:foreground "ForestGreen"))
1340 (((class color) (background dark)) (:foreground "PaleGreen"))
1341 (t (:bold t :underline t)))
1342 "Face used for level 5 headlines."
1343 :group 'org-faces)
1344
1345 (defface org-level-6-face ;; font-lock-constant-face
1346 '((((type tty) (class color)) (:foreground "magenta"))
1347 (((class color) (background light)) (:foreground "CadetBlue"))
1348 (((class color) (background dark)) (:foreground "Aquamarine"))
1349 (t (:bold t :underline t)))
1350 "Face used for level 6 headlines."
1351 :group 'org-faces)
1352
1353 (defface org-level-7-face ;; font-lock-builtin-face
1354 '((((type tty) (class color)) (:foreground "blue" :weight light))
1355 (((class color) (background light)) (:foreground "Orchid"))
1356 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1357 (t (:bold t)))
1358 "Face used for level 7 headlines."
1359 :group 'org-faces)
1360
1361 (defface org-level-8-face ;; font-lock-string-face
1362 '((((type tty) (class color)) (:foreground "green"))
1363 (((class color) (background light)) (:foreground "RosyBrown"))
1364 (((class color) (background dark)) (:foreground "LightSalmon"))
1365 (t (:italic t)))
1366 "Face used for level 8 headlines."
1367 :group 'org-faces)
1368
1369 (defface org-warning-face ;; font-lock-warning-face
1370 '((((type tty) (class color)) (:foreground "red"))
1371 (((class color) (background light)) (:foreground "Red" :bold t))
1372 (((class color) (background dark)) (:foreground "Red1" :bold t))
1373 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1374 (t (:inverse-video t :bold t)))
1375 "Face for deadlines and TODO keywords."
1376 :group 'org-faces)
1377
1378 (defcustom org-fontify-done-headline nil
1379 "Non-nil means, change the face of a headline if it is marked DONE.
1380 Normally, only the TODO/DONE keyword indicates the state of a headline.
1381 When this is non-nil, the headline after the keyword is set to the
1382 `org-headline-done-face' as an additional indication."
1383 :group 'org-faces
1384 :type 'boolean)
1385
1386 (defface org-headline-done-face ;; font-lock-string-face
1387 '((((type tty) (class color)) (:foreground "green"))
1388 (((class color) (background light)) (:foreground "RosyBrown"))
1389 (((class color) (background dark)) (:foreground "LightSalmon"))
1390 (t (:italic t)))
1391 "Face used to indicate that a headline is DONE. See also the variable
1392 `org-fontify-done-headline'."
1393 :group 'org-faces)
1394
1395 ;; Inheritance does not yet work for xemacs. So we just copy...
1396
1397 (defface org-deadline-announce-face
1398 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1399 (((class color) (background light)) (:foreground "Blue"))
1400 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1401 (t (:inverse-video t :bold t)))
1402 "Face for upcoming deadlines."
1403 :group 'org-faces)
1404
1405 (defface org-scheduled-today-face
1406 '((((type tty) (class color)) (:foreground "green"))
1407 (((class color) (background light)) (:foreground "DarkGreen"))
1408 (((class color) (background dark)) (:foreground "PaleGreen"))
1409 (t (:bold t :underline t)))
1410 "Face for items scheduled for a certain day."
1411 :group 'org-faces)
1412
1413 (defface org-scheduled-previously-face
1414 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1415 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1416 (((class color) (background light)) (:foreground "Firebrick"))
1417 (((class color) (background dark)) (:foreground "chocolate1"))
1418 (t (:bold t :italic t)))
1419 "Face for items scheduled previously, and not yet done."
1420 :group 'org-faces)
1421
1422 (defface org-link-face
1423 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1424 (((class color) (background light)) (:foreground "Purple"))
1425 (((class color) (background dark)) (:foreground "Cyan"))
1426 (t (:bold t)))
1427 "Face for links."
1428 :group 'org-faces)
1429
1430 (defface org-done-face ;; font-lock-type-face
1431 '((((type tty) (class color)) (:foreground "green"))
1432 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1433 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1434 (t (:bold t :underline t)))
1435 "Face used for DONE."
1436 :group 'org-faces)
1437
1438 (defface org-table-face ;; font-lock-function-name-face
1439 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1440 (((class color) (background light)) (:foreground "Blue"))
1441 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1442 (t (:inverse-video t :bold t)))
1443 "Face used for tables."
1444 :group 'org-faces)
1445
1446 (defface org-time-grid-face ;; font-lock-variable-name-face
1447 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1448 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1449 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1450 (t (:bold t :italic t)))
1451 "Face used for level 2 headlines."
1452 :group 'org-faces)
1453
1454 (defvar org-level-faces
1455 '(
1456 org-level-1-face
1457 org-level-2-face
1458 org-level-3-face
1459 org-level-4-face
1460 org-level-5-face
1461 org-level-6-face
1462 org-level-7-face
1463 org-level-8-face
1464 ))
1465 (defvar org-n-levels (length org-level-faces))
1466
1467 ;; Tell the compiler about dynamically scoped variables,
1468 ;; and variables from other packages
1469 (eval-when-compile
1470 (defvar zmacs-regions)
1471 (defvar original-date)
1472 (defvar org-transient-mark-mode)
1473 (defvar org-old-auto-fill-inhibit-regexp)
1474 (defvar orgtbl-mode-menu)
1475 (defvar org-html-entities)
1476 (defvar org-goto-start-pos)
1477 (defvar org-cursor-color)
1478 (defvar org-time-was-given)
1479 (defvar org-ts-what)
1480 (defvar mark-active)
1481 (defvar timecnt)
1482 (defvar levels-open)
1483 (defvar title)
1484 (defvar author)
1485 (defvar email)
1486 (defvar text)
1487 (defvar entry)
1488 (defvar date)
1489 (defvar language)
1490 (defvar options)
1491 (defvar ans1)
1492 (defvar ans2)
1493 (defvar starting-day)
1494 (defvar include-all-loc)
1495 (defvar vm-message-pointer)
1496 (defvar vm-folder-directory)
1497 (defvar wl-summary-buffer-elmo-folder)
1498 (defvar wl-summary-buffer-folder-name)
1499 (defvar gnus-group-name)
1500 (defvar gnus-article-current)
1501 (defvar w3m-current-url)
1502 (defvar org-selected-point)
1503 (defvar calendar-mode-map)
1504 (defvar remember-save-after-remembering)
1505 (defvar remember-data-file))
1506
1507
1508 ;;; Define the mode
1509
1510 (defvar org-mode-map (copy-keymap outline-mode-map)
1511 "Keymap for Org-mode.")
1512
1513 (defvar org-struct-menu)
1514 (defvar org-org-menu)
1515
1516 ;; We use a before-change function to check if a table might need
1517 ;; an update.
1518 (defvar org-table-may-need-update t
1519 "Indicates of a table might need an update.
1520 This variable is set by `org-before-change-function'. `org-table-align'
1521 sets it back to nil.")
1522
1523 (defvar org-mode-hook nil)
1524 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1525
1526
1527 ;;;###autoload
1528 (defun org-mode (&optional arg)
1529 "Outline-based notes management and organizer, alias
1530 \"Carstens outline-mode for keeping track of everything.\"
1531
1532 Org-mode develops organizational tasks around a NOTES file which
1533 contains information about projects as plain text. Org-mode is
1534 implemented on top of outline-mode, which is ideal to keep the content
1535 of large files well structured. It supports ToDo items, deadlines and
1536 time stamps, which magically appear in the diary listing of the Emacs
1537 calendar. Tables are easily created with a built-in table editor.
1538 Plain text URL-like links connect to websites, emails (VM), Usenet
1539 messages (Gnus), BBDB entries, and any files related to the project.
1540 For printing and sharing of notes, an Org-mode file (or a part of it)
1541 can be exported as a well-structured ASCII or HTML file.
1542
1543 The following commands are available:
1544
1545 \\{org-mode-map}"
1546 (interactive "P")
1547 (outline-mode)
1548 (setq major-mode 'org-mode)
1549 (setq mode-name "Org")
1550 (use-local-map org-mode-map)
1551 (easy-menu-add org-org-menu)
1552 (org-install-agenda-files-menu)
1553 (setq outline-regexp "\\*+")
1554 (if org-startup-truncated (setq truncate-lines t))
1555 (org-set-regexps-and-options)
1556 (set (make-local-variable 'font-lock-unfontify-region-function)
1557 'org-unfontify-region)
1558 ;; Activate before-change-function
1559 (set (make-local-variable 'org-table-may-need-update) t)
1560 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1561 (add-hook 'before-change-functions 'org-before-change-function nil
1562 'local)
1563 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1564 (set (make-local-variable 'auto-fill-inhibit-regexp)
1565 (concat "\\*"
1566 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1567 (concat
1568 "\\|[ \t]*["
1569 (if org-enable-table-editor "|" "")
1570 (if org-enable-fixed-width-editor ":" "")
1571 "]"))))
1572 ;; Hook, and startup actions
1573 (if (or arg
1574 (and org-insert-mode-line-in-empty-file
1575 (interactive-p)
1576 (= (point-min) (point-max))))
1577 (save-excursion
1578 (goto-char (point-min))
1579 (insert " -*- mode: org -*-\n\n")))
1580 (run-hooks 'org-mode-hook)
1581 (unless org-inhibit-startup
1582 (if org-startup-with-deadline-check
1583 (call-interactively 'org-check-deadlines)
1584 (cond
1585 ((eq org-startup-folded t)
1586 (org-cycle '(4)))
1587 ((eq org-startup-folded 'content)
1588 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1589 (org-cycle '(4)) (org-cycle '(4))))))))
1590
1591 ;;; Font-Lock stuff
1592
1593 (defvar org-mouse-map (make-sparse-keymap))
1594 (define-key org-mouse-map
1595 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1596 (define-key org-mouse-map
1597 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1598
1599 (require 'font-lock)
1600
1601 (defconst org-non-link-chars "\t\n\r|")
1602 (defconst org-link-regexp
1603 (if org-allow-space-in-links
1604 (concat
1605 "\\(https?\\|ftp\\|mailto|\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1606 (concat
1607 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1608 )
1609 "Regular expression for matching links.")
1610 (defconst org-ts-lengths
1611 (cons (length (format-time-string (car org-time-stamp-formats)))
1612 (length (format-time-string (cdr org-time-stamp-formats))))
1613 "This holds the lengths of the two different time formats.")
1614 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1615 "Regular expression for fast time stamp matching.")
1616 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1617 "Regular expression matching time strings for analysis.")
1618 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1619 "Regular expression matching time stamps, with groups.")
1620 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1621 "Regular expression matching a time stamp range.")
1622 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1623 org-ts-regexp "\\)?")
1624 "Regular expression matching a time stamp or time stamp range.")
1625
1626 (defun org-activate-links (limit)
1627 "Run through the buffer and add overlays to links."
1628 (if (re-search-forward org-link-regexp limit t)
1629 (progn
1630 (add-text-properties (match-beginning 0) (match-end 0)
1631 (list 'mouse-face 'highlight
1632 'keymap org-mouse-map))
1633 t)))
1634
1635 (defun org-activate-dates (limit)
1636 "Run through the buffer and add overlays to dates."
1637 (if (re-search-forward org-tsr-regexp limit t)
1638 (progn
1639 (add-text-properties (match-beginning 0) (match-end 0)
1640 (list 'mouse-face 'highlight
1641 'keymap org-mouse-map))
1642 t)))
1643
1644
1645 (defun org-font-lock-level ()
1646 (save-excursion
1647 (org-back-to-heading t)
1648 (- (match-end 0) (match-beginning 0))))
1649
1650 (defvar org-font-lock-keywords nil)
1651
1652 (defun org-set-font-lock-defaults ()
1653 (let ((org-font-lock-extra-keywords
1654 (list
1655 '(org-activate-links (0 'org-link-face))
1656 '(org-activate-dates (0 'org-link-face))
1657 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1658 '(1 'org-warning-face t))
1659 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning-face t))
1660 (list (concat "\\<" org-deadline-string) '(0 'org-warning-face t))
1661 (list (concat "\\<" org-scheduled-string) '(0 'org-warning-face t))
1662 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1663 ;; (3 'bold))
1664 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1665 ;; (3 'italic))
1666 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1667 ;; (3 'underline))
1668 '("\\<FIXME\\>" (0 'org-warning-face t))
1669 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1670 '(1 'org-warning-face t))
1671 '("^#.*" (0 'font-lock-comment-face t))
1672 (if org-fontify-done-headline
1673 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1674 '(1 'org-done-face t) '(2 'org-headline-done-face t))
1675 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1676 '(1 'org-done-face t)))
1677 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1678 (1 'org-table-face t))
1679 '("^[ \t]*\\(:.*\\)" (1 'org-table-face t)))))
1680 (set (make-local-variable 'org-font-lock-keywords)
1681 (append
1682 (if org-noutline-p ; FIXME: I am not sure if eval will work
1683 ; on XEmacs if noutline is ever ported
1684 '((eval . (list "^\\(\\*+\\).*"
1685 0 '(nth
1686 (% (- (match-end 1) (match-beginning 1) 1)
1687 org-n-levels)
1688 org-level-faces)
1689 nil t)))
1690 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1691 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1692 org-n-levels)
1693 org-level-faces)
1694 nil t))))
1695 org-font-lock-extra-keywords))
1696 (set (make-local-variable 'font-lock-defaults)
1697 '(org-font-lock-keywords t nil nil backward-paragraph))
1698 (kill-local-variable 'font-lock-keywords) nil))
1699
1700 (defun org-unfontify-region (beg end &optional maybe_loudly)
1701 "Remove fontification and activation overlays from links."
1702 (font-lock-default-unfontify-region beg end)
1703 (let* ((buffer-undo-list t)
1704 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1705 (inhibit-modification-hooks t)
1706 deactivate-mark buffer-file-name buffer-file-truename)
1707 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1708
1709 ;;; Visibility cycling
1710
1711 (defvar org-cycle-global-status nil)
1712 (defvar org-cycle-subtree-status nil)
1713 (defun org-cycle (&optional arg)
1714 "Visibility cycling for Org-mode.
1715
1716 - When this function is called with a prefix argument, rotate the entire
1717 buffer through 3 states (global cycling)
1718 1. OVERVIEW: Show only top-level headlines.
1719 2. CONTENTS: Show all headlines of all levels, but no body text.
1720 3. SHOW ALL: Show everything.
1721
1722 - When point is at the beginning of a headline, rotate the subtree started
1723 by this line through 3 different states (local cycling)
1724 1. FOLDED: Only the main headline is shown.
1725 2. CHILDREN: The main headline and the direct children are shown. From
1726 this state, you can move to one of the children and
1727 zoom in further.
1728 3. SUBTREE: Show the entire subtree, including body text.
1729
1730 - When there is a numeric prefix, go ARG levels up and do a `show-subtree',
1731 keeping cursor position.
1732
1733 - When point is not at the beginning of a headline, execute
1734 `indent-relative', like TAB normally does. See the option
1735 `org-cycle-emulate-tab' for details.
1736
1737 - Special case: if point is the the beginning of the buffer and there is
1738 no headline in line 1, this function will act as if called with prefix arg."
1739 (interactive "P")
1740
1741 (if (or (and (bobp) (not (looking-at outline-regexp)))
1742 (equal arg '(4)))
1743 ;; special case: use global cycling
1744 (setq arg t))
1745
1746 (cond
1747
1748 ((org-at-table-p 'any)
1749 ;; Enter the table or move to the next field in the table
1750 (or (org-table-recognize-table.el)
1751 (progn
1752 (org-table-justify-field-maybe)
1753 (org-table-next-field))))
1754
1755 ((eq arg t) ;; Global cycling
1756
1757 (cond
1758 ((and (eq last-command this-command)
1759 (eq org-cycle-global-status 'overview))
1760 ;; We just created the overview - now do table of contents
1761 ;; This can be slow in very large buffers, so indicate action
1762 (message "CONTENTS...")
1763 (save-excursion
1764 ;; Visit all headings and show their offspring
1765 (goto-char (point-max))
1766 (catch 'exit
1767 (while (and (progn (condition-case nil
1768 (outline-previous-visible-heading 1)
1769 (error (goto-char (point-min))))
1770 t)
1771 (looking-at outline-regexp))
1772 (show-branches)
1773 (if (bobp) (throw 'exit nil))))
1774 (message "CONTENTS...done"))
1775 (setq org-cycle-global-status 'contents)
1776 (run-hook-with-args 'org-cycle-hook 'contents))
1777
1778 ((and (eq last-command this-command)
1779 (eq org-cycle-global-status 'contents))
1780 ;; We just showed the table of contents - now show everything
1781 (show-all)
1782 (message "SHOW ALL")
1783 (setq org-cycle-global-status 'all)
1784 (run-hook-with-args 'org-cycle-hook 'all))
1785
1786 (t
1787 ;; Default action: go to overview
1788 (hide-sublevels 1)
1789 (message "OVERVIEW")
1790 (setq org-cycle-global-status 'overview)
1791 (run-hook-with-args 'org-cycle-hook 'overview))))
1792
1793 ((integerp arg)
1794 ;; Show-subtree, ARG levels up from here.
1795 (save-excursion
1796 (org-back-to-heading)
1797 (outline-up-heading arg)
1798 (org-show-subtree)))
1799
1800 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1801 ;; At a heading: rotate between three different views
1802 (org-back-to-heading)
1803 (let ((goal-column 0) eoh eol eos)
1804 ;; First, some boundaries
1805 (save-excursion
1806 (org-back-to-heading)
1807 (save-excursion
1808 (beginning-of-line 2)
1809 (while (and (not (eobp)) ;; this is like `next-line'
1810 (get-char-property (1- (point)) 'invisible))
1811 (beginning-of-line 2)) (setq eol (point)))
1812 (outline-end-of-heading) (setq eoh (point))
1813 (outline-end-of-subtree) (setq eos (point))
1814 (outline-next-heading))
1815 ;; Find out what to do next and set `this-command'
1816 (cond
1817 ((= eos eoh)
1818 ;; Nothing is hidden behind this heading
1819 (message "EMPTY ENTRY")
1820 (setq org-cycle-subtree-status nil))
1821 ((>= eol eos)
1822 ;; Entire subtree is hidden in one line: open it
1823 (org-show-entry)
1824 (show-children)
1825 (message "CHILDREN")
1826 (setq org-cycle-subtree-status 'children)
1827 (run-hook-with-args 'org-cycle-hook 'children))
1828 ((and (eq last-command this-command)
1829 (eq org-cycle-subtree-status 'children))
1830 ;; We just showed the children, now show everything.
1831 (org-show-subtree)
1832 (message "SUBTREE")
1833 (setq org-cycle-subtree-status 'subtree)
1834 (run-hook-with-args 'org-cycle-hook 'subtree))
1835 (t
1836 ;; Default action: hide the subtree.
1837 (hide-subtree)
1838 (message "FOLDED")
1839 (setq org-cycle-subtree-status 'folded)
1840 (run-hook-with-args 'org-cycle-hook 'folded)))))
1841
1842 ;; TAB emulation
1843 (buffer-read-only (org-back-to-heading))
1844 ((if (and (eq org-cycle-emulate-tab 'white)
1845 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
1846 t
1847 (eq org-cycle-emulate-tab t))
1848 (if (and (looking-at "[ \n\r\t]")
1849 (string-match "^[ \t]*$" (buffer-substring
1850 (point-at-bol) (point))))
1851 (progn
1852 (beginning-of-line 1)
1853 (and (looking-at "[ \t]+") (replace-match ""))))
1854 (indent-relative))
1855
1856 (t (save-excursion
1857 (org-back-to-heading)
1858 (org-cycle)))))
1859
1860 (defun org-optimize-window-after-visibility-change (state)
1861 "Adjust the window after a change in outline visibility.
1862 This function is the default value of the hook `org-cycle-hook'."
1863 (cond
1864 ((eq state 'overview) (org-first-headline-recenter 1))
1865 ((eq state 'content) nil)
1866 ((eq state 'all) nil)
1867 ((eq state 'folded) nil)
1868 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
1869 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
1870
1871 (defun org-subtree-end-visible-p ()
1872 "Is the end of the current subtree visible?"
1873 (pos-visible-in-window-p
1874 (save-excursion (outline-end-of-subtree) (point))))
1875
1876 (defun org-first-headline-recenter (&optional N)
1877 "Move cursor to the first headline and recenter the headline.
1878 Optional argument N means, put the headline into the Nth line of the window."
1879 (goto-char (point-min))
1880 (when (re-search-forward (concat "^" outline-regexp) nil t)
1881 (beginning-of-line)
1882 (recenter (prefix-numeric-value N))))
1883
1884 (defvar org-goto-window-configuration nil)
1885 (defvar org-goto-marker nil)
1886 (defvar org-goto-map (make-sparse-keymap))
1887 (let ((cmds '(isearch-forward isearch-backward)) cmd)
1888 (while (setq cmd (pop cmds))
1889 (substitute-key-definition cmd cmd org-goto-map global-map)))
1890 (define-key org-goto-map [(return)] 'org-goto-ret)
1891 (define-key org-goto-map [(left)] 'org-goto-left)
1892 (define-key org-goto-map [(right)] 'org-goto-right)
1893 (define-key org-goto-map [(?q)] 'org-goto-quit)
1894 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
1895 (define-key org-goto-map [(tab)] 'org-cycle)
1896 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
1897 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
1898 (define-key org-goto-map "n" 'outline-next-visible-heading)
1899 (define-key org-goto-map "p" 'outline-previous-visible-heading)
1900 (define-key org-goto-map "f" 'outline-forward-same-level)
1901 (define-key org-goto-map "b" 'outline-backward-same-level)
1902 (define-key org-goto-map "u" 'outline-up-heading)
1903 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
1904 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
1905 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
1906 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
1907 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
1908 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
1909 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
1910
1911 (defconst org-goto-help
1912 "Select a location to jump to, press RET
1913 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
1914
1915 (defun org-goto ()
1916 "Go to a different location of the document, keeping current visibility.
1917
1918 When you want to go to a different location in a document, the fastest way
1919 is often to fold the entire buffer and then dive into the tree. This
1920 method has the disadvantage, that the previous location will be folded,
1921 which may not be what you want.
1922
1923 This command works around this by showing a copy of the current buffer in
1924 overview mode. You can dive into the tree in that copy, to find the
1925 location you want to reach. When pressing RET, the command returns to the
1926 original buffer in which the visibility is still unchanged. It then jumps
1927 to the new location, making it and the headline hierarchy above it visible."
1928 (interactive)
1929 (let* ((org-goto-start-pos (point))
1930 (selected-point
1931 (org-get-location (current-buffer) org-goto-help)))
1932 (if selected-point
1933 (progn
1934 (goto-char selected-point)
1935 (if (org-invisible-p) (org-show-hierarchy-above)))
1936 (error "Quit"))))
1937
1938 (defun org-get-location (buf help)
1939 "Let the user select a location in the Org-mode buffer BUF.
1940 This function uses a recursive edit. It returns the selected position
1941 or nil."
1942 (let (org-selected-point)
1943 (save-excursion
1944 (save-window-excursion
1945 (delete-other-windows)
1946 (switch-to-buffer (get-buffer-create "*org-goto*"))
1947 (with-output-to-temp-buffer "*Help*"
1948 (princ help))
1949 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
1950 (setq buffer-read-only nil)
1951 (erase-buffer)
1952 (insert-buffer buf)
1953 (let ((org-startup-truncated t)
1954 (org-startup-folded t)
1955 (org-startup-with-deadline-check nil))
1956 (org-mode))
1957 (setq buffer-read-only t)
1958 (if (boundp 'org-goto-start-pos)
1959 (goto-char org-goto-start-pos)
1960 (goto-char (point-min)))
1961 (org-beginning-of-line)
1962 (message "Select location and press RET")
1963 ;; now we make sure that during selection, ony very few keys work
1964 ;; and that it is impossible to switch to another window.
1965 (let ((gm (current-global-map))
1966 (overriding-local-map org-goto-map))
1967 (unwind-protect
1968 (progn
1969 (use-global-map org-goto-map)
1970 (recursive-edit))
1971 (use-global-map gm)))))
1972 (kill-buffer "*org-goto*")
1973 org-selected-point))
1974
1975 ;; FIXME: It may not be a good idea to temper with the prefix argument...
1976 (defun org-goto-ret (&optional arg)
1977 "Finish org-goto by going to the new location."
1978 (interactive "P")
1979 (setq org-selected-point (point)
1980 current-prefix-arg arg)
1981 (throw 'exit nil))
1982
1983 (defun org-goto-left ()
1984 "Finish org-goto by going to the new location."
1985 (interactive)
1986 (if (org-on-heading-p)
1987 (progn
1988 (beginning-of-line 1)
1989 (setq org-selected-point (point)
1990 current-prefix-arg (- (match-end 0) (match-beginning 0)))
1991 (throw 'exit nil))
1992 (error "Not on a heading")))
1993
1994 (defun org-goto-right ()
1995 "Finish org-goto by going to the new location."
1996 (interactive)
1997 (if (org-on-heading-p)
1998 (progn
1999 (outline-end-of-subtree)
2000 (or (eobp) (forward-char 1))
2001 (setq org-selected-point (point)
2002 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2003 (throw 'exit nil))
2004 (error "Not on a heading")))
2005
2006 (defun org-goto-quit ()
2007 "Finish org-goto without cursor motion."
2008 (interactive)
2009 (setq org-selected-point nil)
2010 (throw 'exit nil))
2011
2012 ;;; Promotion, Demotion, Inserting new headlines
2013
2014 (defvar org-ignore-region nil
2015 "To temporarily disable the active region.")
2016
2017 (defun org-insert-heading ()
2018 "Insert a new heading with same depth at point."
2019 (interactive)
2020 (let* ((head (save-excursion
2021 (condition-case nil
2022 (org-back-to-heading)
2023 (error (outline-next-heading)))
2024 (prog1 (match-string 0)
2025 (funcall outline-level)))))
2026 (unless (bolp) (newline))
2027 (insert head)
2028 (unless (eolp)
2029 (save-excursion (newline-and-indent)))
2030 (unless (equal (char-before) ?\ )
2031 (insert " "))
2032 (run-hooks 'org-insert-heading-hook)))
2033
2034 (defun org-insert-todo-heading (arg)
2035 "Insert a new heading with the same level and TODO state as current heading.
2036 If the heading has no TODO state, or if the state is DONE, use the first
2037 state (TODO by default). Also with prefix arg, force first state."
2038 (interactive "P")
2039 (org-insert-heading)
2040 (save-excursion
2041 (org-back-to-heading)
2042 (outline-previous-heading)
2043 (looking-at org-todo-line-regexp))
2044 (if (or arg
2045 (not (match-beginning 2))
2046 (equal (match-string 2) org-done-string))
2047 (insert (car org-todo-keywords) " ")
2048 (insert (match-string 2) " ")))
2049
2050 (defun org-promote-subtree ()
2051 "Promote the entire subtree.
2052 See also `org-promote'."
2053 (interactive)
2054 (save-excursion
2055 (org-map-tree 'org-promote)))
2056
2057 (defun org-demote-subtree ()
2058 "Demote the entire subtree. See `org-demote'.
2059 See also `org-promote'."
2060 (interactive)
2061 (save-excursion
2062 (org-map-tree 'org-demote)))
2063
2064 (defun org-do-promote ()
2065 "Promote the current heading higher up the tree.
2066 If the region is active in `transient-mark-mode', promote all headings
2067 in the region."
2068 (interactive)
2069 (save-excursion
2070 (if (org-region-active-p)
2071 (org-map-region 'org-promote (region-beginning) (region-end))
2072 (org-promote)))
2073 (org-fix-position-after-promote))
2074
2075 (defun org-do-demote ()
2076 "Demote the current heading lower down the tree.
2077 If the region is active in `transient-mark-mode', demote all headings
2078 in the region."
2079 (interactive)
2080 (save-excursion
2081 (if (org-region-active-p)
2082 (org-map-region 'org-demote (region-beginning) (region-end))
2083 (org-demote)))
2084 (org-fix-position-after-promote))
2085
2086 (defun org-fix-position-after-promote ()
2087 "Make sure that after pro/demotion cursor position is right."
2088 (and (equal (char-after) ?\ )
2089 (equal (char-before) ?*)
2090 (forward-char 1)))
2091
2092 (defun org-promote ()
2093 "Promote the current heading higher up the tree.
2094 If the region is active in `transient-mark-mode', promote all headings
2095 in the region."
2096 (org-back-to-heading t)
2097 (let* ((level (save-match-data (funcall outline-level)))
2098 (up-head (make-string (1- level) ?*)))
2099 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover."))
2100 (replace-match up-head nil t)
2101 (if org-adapt-indentation
2102 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2103
2104 (defun org-demote ()
2105 "Demote the current heading lower down the tree.
2106 If the region is active in `transient-mark-mode', demote all headings
2107 in the region."
2108 (org-back-to-heading t)
2109 (let* ((level (save-match-data (funcall outline-level)))
2110 (down-head (make-string (1+ level) ?*)))
2111 (replace-match down-head nil t)
2112 (if org-adapt-indentation
2113 (org-fixup-indentation "^ " " " "^\\S-"))))
2114
2115 (defun org-map-tree (fun)
2116 "Call FUN for every heading underneath the current one."
2117 (org-back-to-heading)
2118 (let ((level (outline-level)))
2119 (save-excursion
2120 (funcall fun)
2121 (while (and (progn
2122 (outline-next-heading)
2123 (> (funcall outline-level) level))
2124 (not (eobp)))
2125 (funcall fun)))))
2126
2127 (defun org-map-region (fun beg end)
2128 "Call FUN for every heading between BEG and END."
2129 (let ((org-ignore-region t))
2130 (save-excursion
2131 (setq end (copy-marker end))
2132 (goto-char beg)
2133 ;; (if (fboundp 'deactivate-mark) (deactivate-mark))
2134 ;; (if (fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region))
2135 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2136 (< (point) end))
2137 (funcall fun))
2138 (while (and (progn
2139 (outline-next-heading)
2140 (< (point) end))
2141 (not (eobp)))
2142 (funcall fun)))))
2143
2144 (defun org-fixup-indentation (from to prohibit)
2145 "Change the indentation in the current entry by re-replacing FROM with TO.
2146 However, if the regexp PROHIBIT matches at all, don't do anything.
2147 This is being used to change indentation along with the length of the
2148 heading marker. But if there are any lines which are not indented, nothing
2149 is changed at all."
2150 (save-excursion
2151 (let ((end (save-excursion (outline-next-heading)
2152 (point-marker))))
2153 (unless (save-excursion (re-search-forward prohibit end t))
2154 (while (re-search-forward from end t)
2155 (replace-match to)
2156 (beginning-of-line 2)))
2157 (move-marker end nil))))
2158
2159 ;;; Vertical tree motion, cutting and pasting of subtrees
2160
2161 (defun org-move-subtree-up (&optional arg)
2162 "Move the current subtree up past ARG headlines of the same level."
2163 (interactive "p")
2164 (org-move-subtree-down (- (prefix-numeric-value arg))))
2165
2166 (defun org-move-subtree-down (&optional arg)
2167 "Move the current subtree down past ARG headlines of the same level."
2168 (interactive "p")
2169 (setq arg (prefix-numeric-value arg))
2170 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2171 'outline-get-last-sibling))
2172 (ins-point (make-marker))
2173 (cnt (abs arg))
2174 beg end txt folded)
2175 ;; Select the tree
2176 (org-back-to-heading)
2177 (setq beg (point))
2178 (save-match-data
2179 (save-excursion (outline-end-of-heading)
2180 (setq folded (org-invisible-p)))
2181 (outline-end-of-subtree))
2182 (outline-next-heading)
2183 (setq end (point))
2184 ;; Find insertion point, with error handling
2185 (goto-char beg)
2186 (while (> cnt 0)
2187 (or (and (funcall movfunc) (looking-at outline-regexp))
2188 (progn (goto-char beg)
2189 (error "Cannot move past superior level or buffer limit")))
2190 (setq cnt (1- cnt)))
2191 (if (> arg 0)
2192 ;; Moving forward - still need to move over subtree
2193 (progn (outline-end-of-subtree)
2194 (outline-next-heading)
2195 (if (not (or (looking-at (concat "^" outline-regexp))
2196 (bolp)))
2197 (newline))))
2198 (move-marker ins-point (point))
2199 (setq txt (buffer-substring beg end))
2200 (delete-region beg end)
2201 (insert txt)
2202 (goto-char ins-point)
2203 (if folded (hide-subtree))
2204 (move-marker ins-point nil)))
2205
2206 (defvar org-subtree-clip ""
2207 "Clipboard for cut and paste of subtrees.
2208 This is actually only a copy of the kill, because we use the normal kill
2209 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2210
2211 (defvar org-subtree-clip-folded nil
2212 "Was the last copied subtree folded?
2213 This is used to fold the tree back after pasting.")
2214
2215 (defun org-cut-subtree ()
2216 "Cut the current subtree into the clipboard.
2217 This is a short-hand for marking the subtree and then cutting it."
2218 (interactive)
2219 (org-copy-subtree 'cut))
2220
2221 (defun org-copy-subtree (&optional cut)
2222 "Cut the current subtree into the clipboard.
2223 This is a short-hand for marking the subtree and then copying it.
2224 If CUT is non nil, actually cut the subtree."
2225 (interactive)
2226 (let (beg end folded)
2227 (org-back-to-heading)
2228 (setq beg (point))
2229 (save-match-data
2230 (save-excursion (outline-end-of-heading)
2231 (setq folded (org-invisible-p)))
2232 (outline-end-of-subtree))
2233 (if (equal (char-after) ?\n) (forward-char 1))
2234 (setq end (point))
2235 (goto-char beg)
2236 (when (> end beg)
2237 (setq org-subtree-clip-folded folded)
2238 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2239 (setq org-subtree-clip (current-kill 0))
2240 (message "%s: Subtree with %d characters"
2241 (if cut "Cut" "Copied")
2242 (length org-subtree-clip)))))
2243
2244 (defun org-paste-subtree (&optional level tree)
2245 "Paste the clipboard as a subtree, with modification of headline level.
2246 The entire subtree is promoted or demoted in order to match a new headline
2247 level. By default, the new level is derived from the visible headings
2248 before and after the insertion point, and taken to be the inferior headline
2249 level of the two. So if the previous visible heading is level 3 and the
2250 next is level 4 (or vice versa), level 4 will be used for insertion.
2251 This makes sure that the subtree remains an independent subtree and does
2252 not swallow low level entries.
2253
2254 You can also force a different level, either by using a numeric prefix
2255 argument, or by inserting the heading marker by hand. For example, if the
2256 cursor is after \"*****\", then the tree will be shifted to level 5.
2257
2258 If you want to insert the tree as is, just use \\[yank].
2259
2260 If optional TREE is given, use this text instead of the kill ring."
2261 (interactive "P")
2262 (unless (org-kill-is-subtree-p tree)
2263 (error
2264 (substitute-command-keys
2265 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2266 (let* ((txt (or tree (current-kill 0)))
2267 (^re (concat "^\\(" outline-regexp "\\)"))
2268 (re (concat "\\(" outline-regexp "\\)"))
2269 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2270
2271 (old-level (if (string-match ^re txt)
2272 (- (match-end 0) (match-beginning 0))
2273 -1))
2274 (force-level (cond (level (prefix-numeric-value level))
2275 ((string-match
2276 ^re_ (buffer-substring (point-at-bol) (point)))
2277 (- (match-end 0) (match-beginning 0)))
2278 (t nil)))
2279 (previous-level (save-excursion
2280 (outline-previous-visible-heading 1)
2281 (if (looking-at re)
2282 (- (match-end 0) (match-beginning 0))
2283 1)))
2284 (next-level (save-excursion
2285 (outline-next-visible-heading 1)
2286 (if (looking-at re)
2287 (- (match-end 0) (match-beginning 0))
2288 1)))
2289 (new-level (or force-level (max previous-level next-level)))
2290 (shift (if (or (= old-level -1)
2291 (= new-level -1)
2292 (= old-level new-level))
2293 0
2294 (- new-level old-level)))
2295 (shift1 shift)
2296 (delta (if (> shift 0) -1 1))
2297 (func (if (> shift 0) 'org-demote 'org-promote))
2298 beg end)
2299 ;; Remove the forces level indicator
2300 (if force-level
2301 (delete-region (point-at-bol) (point)))
2302 ;; Make sure we start at the beginning of an empty line
2303 (if (not (bolp)) (insert "\n"))
2304 (if (not (looking-at "[ \t]*$"))
2305 (progn (insert "\n") (backward-char 1)))
2306 ;; Paste
2307 (setq beg (point))
2308 (insert txt)
2309 (setq end (point))
2310 (goto-char beg)
2311 ;; Shift if necessary
2312 (if (= shift 0)
2313 (message "Pasted at level %d, without shift" new-level)
2314 (save-restriction
2315 (narrow-to-region beg end)
2316 (while (not (= shift 0))
2317 (org-map-region func (point-min) (point-max))
2318 (setq shift (+ delta shift)))
2319 (goto-char (point-min))
2320 (message "Pasted at level %d, with shift by %d levels"
2321 new-level shift1)))
2322 (if (and (eq org-subtree-clip (current-kill 0))
2323 org-subtree-clip-folded)
2324 ;; The tree was folded before it was killed/copied
2325 (hide-subtree))))
2326
2327 (defun org-kill-is-subtree-p (&optional txt)
2328 "Check if the current kill is an outline subtree, or a set of trees.
2329 Returns nil if kill does not start with a headline, or if the first
2330 headline level is not the largest headline level in the tree.
2331 So this will actually accept several entries of equal levels as well,
2332 which is OK for `org-paste-subtree'.
2333 If optional TXT is given, check this string instead of the current kill."
2334 (let* ((kill (or txt (current-kill 0) ""))
2335 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2336 (- (match-end 0) (match-beginning 0))))
2337 (re (concat "^" outline-regexp))
2338 (start 1))
2339 (if (not start-level)
2340 nil ;; does not even start with a heading
2341 (catch 'exit
2342 (while (setq start (string-match re kill (1+ start)))
2343 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2344 (throw 'exit nil)))
2345 t))))
2346
2347 ;;; Completion
2348
2349 (defun org-complete (&optional arg)
2350 "Perform completion on word at point.
2351 At the beginning of a headline, this completes TODO keywords as given in
2352 `org-todo-keywords'.
2353 If the current word is preceded by a backslash, completes the TeX symbols
2354 that are supported for HTML support.
2355 If the current word is preceded by \"#+\", completes special words for
2356 setting file options.
2357 At all other locations, this simply calls `ispell-complete-word'."
2358 (interactive "P")
2359 (catch 'exit
2360 (let* ((end (point))
2361 (beg (save-excursion
2362 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2363 (skip-chars-backward "a-zA-Z0-9_:")
2364 (point)))
2365 (texp (equal (char-before beg) ?\\))
2366 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2367 beg)
2368 "#+"))
2369 (pattern (buffer-substring-no-properties beg end))
2370 (completion-ignore-case opt)
2371 (type nil)
2372 (table (cond
2373 (opt
2374 (setq type :opt)
2375 (mapcar (lambda (x)
2376 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2377 (cons (match-string 2 x) (match-string 1 x)))
2378 (org-split-string (org-get-current-options) "\n")))
2379 (texp
2380 (setq type :tex)
2381 org-html-entities)
2382 ((string-match "\\`\\*+[ \t]*\\'"
2383 (buffer-substring (point-at-bol) beg))
2384 (setq type :todo)
2385 (mapcar 'list org-todo-keywords))
2386 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2387 (completion (try-completion pattern table)))
2388 (cond ((eq completion t)
2389 (if (equal type :opt)
2390 (insert (substring (cdr (assoc (upcase pattern) table))
2391 (length pattern)))))
2392 ((null completion)
2393 (message "Can't find completion for \"%s\"" pattern)
2394 (ding))
2395 ((not (string= pattern completion))
2396 (delete-region beg end)
2397 (if (string-match " +$" completion)
2398 (setq completion (replace-match "" t t completion)))
2399 (insert completion)
2400 (if (get-buffer-window "*Completions*")
2401 (delete-window (get-buffer-window "*Completions*")))
2402 (if (and (eq type :todo)
2403 (assoc completion table))
2404 (insert " "))
2405 (if (and (equal type :opt) (assoc completion table))
2406 (message (substitute-command-keys
2407 "Press \\[org-complete] again to insert example settings"))))
2408 (t
2409 (message "Making completion list...")
2410 (let ((list (sort (all-completions pattern table) 'string<)))
2411 (with-output-to-temp-buffer "*Completions*"
2412 (display-completion-list list)))
2413 (message "Making completion list...%s" "done"))))))
2414
2415 ;;; Comments, TODO and DEADLINE
2416
2417 (defun org-toggle-comment ()
2418 "Change the COMMENT state of an entry."
2419 (interactive)
2420 (save-excursion
2421 (org-back-to-heading)
2422 (if (looking-at (concat outline-regexp
2423 "\\( +\\<" org-comment-string "\\>\\)"))
2424 (replace-match "" t t nil 1)
2425 (if (looking-at outline-regexp)
2426 (progn
2427 (goto-char (match-end 0))
2428 (insert " " org-comment-string))))))
2429
2430 (defvar org-last-todo-state-is-todo nil
2431 "This is non-nil when the last TODO state change led to a TODO state.
2432 If the last change removed the TODO tag or switched to DONE, then
2433 this is nil.")
2434
2435 (defun org-todo (&optional arg)
2436 "Change the TODO state of an item.
2437 The state of an item is given by a keyword at the start of the heading,
2438 like
2439 *** TODO Write paper
2440 *** DONE Call mom
2441
2442 The different keywords are specified in the variable `org-todo-keywords'. By
2443 default the available states are \"TODO\" and \"DONE\".
2444 So for this example: when the item starts with TODO, it is changed to DONE.
2445 When it starts with DONE, the DONE is removed. And when neither TODO nor
2446 DONE are present, add TODO at the beginning of the heading.
2447
2448 With prefix arg, use completion to determined the new state. With numeric
2449 prefix arg, switch to that state."
2450 (interactive "P")
2451 (save-excursion
2452 (org-back-to-heading)
2453 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2454 (or (looking-at (concat " +" org-todo-regexp " *"))
2455 (looking-at " *"))
2456 (let* ((this (match-string 1))
2457 (completion-ignore-case t)
2458 (member (member this org-todo-keywords))
2459 (tail (cdr member))
2460 (state (cond
2461 ((equal arg '(4))
2462 ;; Read a state with completion
2463 (completing-read "State: " (mapcar (lambda(x) (list x))
2464 org-todo-keywords)
2465 nil t))
2466 (arg
2467 ;; user requests a specific state
2468 (nth (1- (prefix-numeric-value arg))
2469 org-todo-keywords))
2470 ((null member) (car org-todo-keywords))
2471 ((null tail) nil) ;; -> first entry
2472 ((eq org-todo-interpretation 'sequence)
2473 (car tail))
2474 ((memq org-todo-interpretation '(type priority))
2475 (if (eq this-command last-command)
2476 (car tail)
2477 (if (> (length tail) 0) org-done-string nil)))
2478 (t nil)))
2479 (next (if state (concat " " state " ") " ")))
2480 (replace-match next t t)
2481 (setq org-last-todo-state-is-todo
2482 (not (equal state org-done-string)))
2483 (run-hooks 'org-after-todo-state-change-hook)))
2484 ;; Fixup cursor location if close to the keyword
2485 (if (and (outline-on-heading-p)
2486 (not (bolp))
2487 (save-excursion (beginning-of-line 1)
2488 (looking-at org-todo-line-regexp))
2489 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2490 (progn
2491 (goto-char (or (match-end 2) (match-end 1)))
2492 (just-one-space))))
2493
2494 (defun org-show-todo-tree (arg)
2495 "Make a compact tree which shows all headlines marked with TODO.
2496 The tree will show the lines where the regexp matches, and all higher
2497 headlines above the match."
2498 (interactive "P")
2499 (let ((case-fold-search nil)
2500 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2501 (message "%d TODO entries found"
2502 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2503
2504 (defun org-deadline ()
2505 "Insert the DEADLINE: string to make a deadline.
2506 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2507 to modify it to the correct date."
2508 (interactive)
2509 (insert
2510 org-deadline-string " "
2511 (format-time-string (car org-time-stamp-formats)
2512 (org-read-date nil 'to-time)))
2513 (message (substitute-command-keys
2514 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2515
2516 (defun org-schedule ()
2517 "Insert the SCHEDULED: string to schedule a TODO item.
2518 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2519 to modify it to the correct date."
2520 (interactive)
2521 (insert
2522 org-scheduled-string " "
2523 (format-time-string (car org-time-stamp-formats)
2524 (org-read-date nil 'to-time)))
2525 (message (substitute-command-keys
2526 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2527
2528
2529 (defun org-occur (regexp &optional callback)
2530 "Make a compact tree which shows all matches of REGEXP.
2531 The tree will show the lines where the regexp matches, and all higher
2532 headlines above the match. It will also show the heading after the match,
2533 to make sure editing the matching entry is easy.
2534 if CALLBACK is non-nil, it is a function which is called to confirm
2535 that the match should indeed be shown."
2536 (interactive "sRegexp: ")
2537 (setq regexp (org-check-occur-regexp regexp))
2538 (let ((cnt 0))
2539 (save-excursion
2540 (goto-char (point-min))
2541 (hide-sublevels 1)
2542 (while (re-search-forward regexp nil t)
2543 (when (or (not callback)
2544 (funcall callback))
2545 (setq cnt (1+ cnt))
2546 (org-show-hierarchy-above))))
2547 (run-hooks 'org-occur-hook)
2548 (if (interactive-p)
2549 (message "%d match(es) for regexp %s" cnt regexp))
2550 cnt))
2551
2552 (defun org-show-hierarchy-above ()
2553 "Make sure point and the headings hierarchy above is visible."
2554 (if (org-on-heading-p t)
2555 (org-flag-heading nil) ; only show the heading
2556 (org-show-hidden-entry)) ; show entire entry
2557 (save-excursion
2558 (and org-show-following-heading
2559 (outline-next-heading)
2560 (org-flag-heading nil))) ; show the next heading
2561 (save-excursion ; show all higher headings
2562 (while (condition-case nil
2563 (progn (org-up-heading-all 1) t)
2564 (error nil))
2565 (org-flag-heading nil))))
2566
2567 ;;; Priorities
2568
2569 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2570 "Regular expression matching the priority indicator.")
2571
2572 (defvar org-remove-priority-next-time nil)
2573
2574 (defun org-priority-up ()
2575 "Increase the priority of the current item."
2576 (interactive)
2577 (org-priority 'up))
2578
2579 (defun org-priority-down ()
2580 "Decrease the priority of the current item."
2581 (interactive)
2582 (org-priority 'down))
2583
2584 (defun org-priority (&optional action)
2585 "Change the priority of an item by ARG.
2586 ACTION can be set, up, or down."
2587 (interactive)
2588 (setq action (or action 'set))
2589 (let (current new news have remove)
2590 (save-excursion
2591 (org-back-to-heading)
2592 (if (looking-at org-priority-regexp)
2593 (setq current (string-to-char (match-string 2))
2594 have t)
2595 (setq current org-default-priority))
2596 (cond
2597 ((eq action 'set)
2598 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2599 (setq new (read-char-exclusive))
2600 (cond ((equal new ?\ ) (setq remove t))
2601 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2602 (error "Priority must be between `%c' and `%c'"
2603 ?A org-lowest-priority))))
2604 ((eq action 'up)
2605 (setq new (1- current)))
2606 ((eq action 'down)
2607 (setq new (1+ current)))
2608 (t (error "Invalid action")))
2609 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2610 (setq news (format "%c" new))
2611 (if have
2612 (if remove
2613 (replace-match "" t t nil 1)
2614 (replace-match news t t nil 2))
2615 (if remove
2616 (error "No priority cookie found in line")
2617 (looking-at org-todo-line-regexp)
2618 (if (match-end 2)
2619 (progn
2620 (goto-char (match-end 2))
2621 (insert " [#" news "]"))
2622 (goto-char (match-beginning 3))
2623 (insert "[#" news "] ")))))
2624 (if remove
2625 (message "Priority removed")
2626 (message "Priority of current item set to %s" news))))
2627
2628
2629 (defun org-get-priority (s)
2630 "Find priority cookie and return priority."
2631 (save-match-data
2632 (if (not (string-match org-priority-regexp s))
2633 (* 1000 (- org-lowest-priority org-default-priority))
2634 (* 1000 (- org-lowest-priority
2635 (string-to-char (match-string 2 s)))))))
2636
2637 ;;; Timestamps
2638
2639 (defvar org-last-changed-timestamp nil)
2640
2641 (defun org-time-stamp (arg)
2642 "Prompt for a date/time and insert a time stamp.
2643 If the user specifies a time like HH:MM, or if this command is called
2644 with a prefix argument, the time stamp will contain date and time.
2645 Otherwise, only the date will be included. All parts of a date not
2646 specified by the user will be filled in from the current date/time.
2647 So if you press just return without typing anything, the time stamp
2648 will represent the current date/time. If there is already a timestamp
2649 at the cursor, it will be modified."
2650 (interactive "P")
2651 (let ((fmt (if arg (cdr org-time-stamp-formats)
2652 (car org-time-stamp-formats)))
2653 (org-time-was-given nil)
2654 time)
2655 (cond
2656 ((and (org-at-timestamp-p)
2657 (eq last-command 'org-time-stamp)
2658 (eq this-command 'org-time-stamp))
2659 (insert "--")
2660 (setq time (let ((this-command this-command))
2661 (org-read-date arg 'totime)))
2662 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2663 (insert (format-time-string fmt time)))
2664 ((org-at-timestamp-p)
2665 (setq time (let ((this-command this-command))
2666 (org-read-date arg 'totime)))
2667 (and (org-at-timestamp-p) (replace-match
2668 (setq org-last-changed-timestamp
2669 (format-time-string fmt time))
2670 t t))
2671 (message "Timestamp updated"))
2672 (t
2673 (setq time (let ((this-command this-command))
2674 (org-read-date arg 'totime)))
2675 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2676 (insert (format-time-string fmt time))))))
2677
2678 ;;; FIXME: Make the function take "Fri" as "next friday"
2679 (defun org-read-date (&optional with-time to-time)
2680 "Read a date and make things smooth for the user.
2681 The prompt will suggest to enter an ISO date, but you can also enter anything
2682 which will at least partially be understood by `parse-time-string'.
2683 Unrecognized parts of the date will default to the current day, month ,year,
2684 hour and minute. For example,
2685 3-2-5 --> 2003-02-05
2686 feb 15 --> currentyear-02-15
2687 sep 12 9 --> 2009-09-12
2688 12:45 --> today 12:45
2689 22 sept 0:34 --> currentyear-09-22 0:34
2690 12 --> currentyear-currentmonth-12
2691 etc.
2692 The function understands only English month and weekday abbreviations,
2693 but this can be configured with the variables `parse-time-months' and
2694 `parse-time-weekdays'.
2695
2696 While prompting, a calendar is popped up - you can also select the
2697 date with the mouse (button 1). The calendar shows a period of three
2698 month. To scroll it to other months, use the keys `>' and `<'.
2699 If you don't like the calendar, turn it off with
2700 \(setq org-popup-calendar-for-date-prompt nil).
2701
2702 With optional argument TO-TIME, the date will immediately be converted
2703 to an internal time.
2704 With an optional argument WITH-TIME, the prompt will suggest to also
2705 insert a time. Note that when WITH-TIME is not set, you can still
2706 enter a time, and this function will inform the calling routine about
2707 this change. The calling routine may then choose to change the format
2708 used to insert the time stamp into the buffer to include the time."
2709 (let* ((default-time
2710 ;; Default time is either today, or, when entering a range,
2711 ;; the range start.
2712 (if (save-excursion
2713 (re-search-backward
2714 (concat org-ts-regexp "--\\=")
2715 (- (point) 20) t))
2716 (apply
2717 'encode-time
2718 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
2719 (parse-time-string (match-string 1))))
2720 (current-time)))
2721 (timestr (format-time-string
2722 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
2723 (prompt (format "YYYY-MM-DD [%s]: " timestr))
2724 ans ans1 ans2
2725 second minute hour day month year tl)
2726
2727 (if org-popup-calendar-for-date-prompt
2728 ;; Also show a calendar for date selection
2729 ;; Copied (with modifications) from planner.el by John Wiegley
2730 (save-excursion
2731 (save-window-excursion
2732 (calendar)
2733 (calendar-forward-day (- (time-to-days default-time)
2734 (calendar-absolute-from-gregorian
2735 (calendar-current-date))))
2736 (let* ((old-map (current-local-map))
2737 (map (copy-keymap calendar-mode-map))
2738 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
2739 (define-key map (kbd "RET") 'org-calendar-select)
2740 (define-key map (if org-xemacs-p [button1] [mouse-1])
2741 'org-calendar-select)
2742 (define-key minibuffer-local-map [(meta shift left)]
2743 (lambda () (interactive)
2744 (org-eval-in-calendar '(calendar-backward-month 1))))
2745 (define-key minibuffer-local-map [(meta shift right)]
2746 (lambda () (interactive)
2747 (org-eval-in-calendar '(calendar-forward-month 1))))
2748 (define-key minibuffer-local-map [(shift up)]
2749 (lambda () (interactive)
2750 (org-eval-in-calendar '(calendar-backward-week 1))))
2751 (define-key minibuffer-local-map [(shift down)]
2752 (lambda () (interactive)
2753 (org-eval-in-calendar '(calendar-forward-week 1))))
2754 (define-key minibuffer-local-map [(shift left)]
2755 (lambda () (interactive)
2756 (org-eval-in-calendar '(calendar-backward-day 1))))
2757 (define-key minibuffer-local-map [(shift right)]
2758 (lambda () (interactive)
2759 (org-eval-in-calendar '(calendar-forward-day 1))))
2760 (define-key minibuffer-local-map ">"
2761 (lambda () (interactive)
2762 (org-eval-in-calendar '(scroll-calendar-left 1))))
2763 (define-key minibuffer-local-map "<"
2764 (lambda () (interactive)
2765 (org-eval-in-calendar '(scroll-calendar-right 1))))
2766 (unwind-protect
2767 (progn
2768 (use-local-map map)
2769 (setq ans (read-string prompt "" nil nil))
2770 (setq ans (or ans1 ans2 ans)))
2771 (use-local-map old-map)))))
2772 ;; Naked prompt only
2773 (setq ans (read-string prompt "" nil timestr)))
2774
2775 (if (string-match
2776 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
2777 (progn
2778 (setq year (if (match-end 2)
2779 (string-to-number (match-string 2 ans))
2780 (string-to-number (format-time-string "%Y")))
2781 month (string-to-number (match-string 3 ans))
2782 day (string-to-number (match-string 4 ans)))
2783 (if (< year 100) (setq year (+ 2000 year)))
2784 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
2785 t t ans))))
2786 (setq tl (parse-time-string ans)
2787 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
2788 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
2789 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
2790 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
2791 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
2792 second (or (nth 0 tl) 0))
2793 (if (and (boundp 'org-time-was-given)
2794 (nth 2 tl))
2795 (setq org-time-was-given t))
2796 (if (< year 100) (setq year (+ 2000 year)))
2797 (if to-time
2798 (encode-time second minute hour day month year)
2799 (if (or (nth 1 tl) (nth 2 tl))
2800 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
2801 (format "%04d-%02d-%02d" year month day)))))
2802
2803 (defun org-eval-in-calendar (form)
2804 "Eval FORM in the calendar window and return to current window.
2805 Also, store the cursor date in variable ans2."
2806 (let ((sw (selected-window)))
2807 (select-window (get-buffer-window "*Calendar*"))
2808 (eval form)
2809 (when (calendar-cursor-to-date)
2810 (let* ((date (calendar-cursor-to-date))
2811 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2812 (setq ans2 (format-time-string "%Y-%m-%d" time))))
2813 (select-window sw)))
2814
2815 (defun org-calendar-select ()
2816 "Return to `org-read-date' with the date currently selected.
2817 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
2818 (interactive)
2819 (when (calendar-cursor-to-date)
2820 (let* ((date (calendar-cursor-to-date))
2821 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2822 (setq ans1 (format-time-string "%Y-%m-%d" time)))
2823 (if (active-minibuffer-window) (exit-minibuffer))))
2824
2825 (defun org-check-deadlines (ndays)
2826 "Check if there are any deadlines due or past due.
2827 A deadline is considered due if it happens within `org-deadline-warning-days'
2828 days from today's date. If the deadline appears in an entry marked DONE,
2829 it is not shown. The prefix arg NDAYS can be used to test that many
2830 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
2831 (interactive "P")
2832 (let* ((org-warn-days
2833 (cond
2834 ((equal ndays '(4)) 100000)
2835 (ndays (prefix-numeric-value ndays))
2836 (t org-deadline-warning-days)))
2837 (case-fold-search nil)
2838 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
2839 (callback
2840 (lambda ()
2841 (and (let ((d1 (time-to-days (current-time)))
2842 (d2 (time-to-days
2843 (org-time-string-to-time (match-string 1)))))
2844 (< (- d2 d1) org-warn-days))
2845 (not (org-entry-is-done-p))))))
2846 (message "%d deadlines past-due or due within %d days"
2847 (org-occur regexp callback)
2848 org-warn-days)))
2849
2850 (defun org-evaluate-time-range (&optional to-buffer)
2851 "Evaluate a time range by computing the difference between start and end.
2852 Normally the result is just printed in the echo area, but with prefix arg
2853 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
2854 If the time range is actually in a table, the result is inserted into the
2855 next column.
2856 For time difference computation, a year is assumed to be exactly 365
2857 days in order to avoid rounding problems."
2858 (interactive "P")
2859 (save-excursion
2860 (unless (org-at-date-range-p)
2861 (goto-char (point-at-bol))
2862 (re-search-forward org-tr-regexp (point-at-eol) t))
2863 (if (not (org-at-date-range-p))
2864 (error "Not at a time-stamp range, and none found in current line.")))
2865 (let* ((ts1 (match-string 1))
2866 (ts2 (match-string 2))
2867 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
2868 (match-end (match-end 0))
2869 (time1 (org-time-string-to-time ts1))
2870 (time2 (org-time-string-to-time ts2))
2871 (t1 (time-to-seconds time1))
2872 (t2 (time-to-seconds time2))
2873 (diff (abs (- t2 t1)))
2874 (negative (< (- t2 t1) 0))
2875 ;; (ys (floor (* 365 24 60 60)))
2876 (ds (* 24 60 60))
2877 (hs (* 60 60))
2878 (fy "%dy %dd %02d:%02d")
2879 (fy1 "%dy %dd")
2880 (fd "%dd %02d:%02d")
2881 (fd1 "%dd")
2882 (fh "%02d:%02d")
2883 y d h m align)
2884 ;; FIXME: Should I re-introduce years, make year refer to same date?
2885 ;; This would be the only useful way to have years, actually.
2886 (if havetime
2887 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
2888 y 0
2889 d (floor (/ diff ds)) diff (mod diff ds)
2890 h (floor (/ diff hs)) diff (mod diff hs)
2891 m (floor (/ diff 60)))
2892 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
2893 y 0
2894 d (floor (+ (/ diff ds) 0.5))
2895 h 0 m 0))
2896 (if (not to-buffer)
2897 (message (org-make-tdiff-string y d h m))
2898 (when (org-at-table-p)
2899 (goto-char match-end)
2900 (setq align t)
2901 (and (looking-at " *|") (goto-char (match-end 0))))
2902 (if (looking-at
2903 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
2904 (replace-match ""))
2905 (if negative (insert " -"))
2906 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
2907 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
2908 (insert " " (format fh h m))))
2909 (if align (org-table-align))
2910 (message "Time difference inserted"))))
2911
2912 (defun org-make-tdiff-string (y d h m)
2913 (let ((fmt "")
2914 (l nil))
2915 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
2916 l (push y l)))
2917 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
2918 l (push d l)))
2919 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
2920 l (push h l)))
2921 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
2922 l (push m l)))
2923 (apply 'format fmt (nreverse l))))
2924
2925 (defun org-time-string-to-time (s)
2926 (apply 'encode-time (org-parse-time-string s)))
2927
2928 (defun org-parse-time-string (s &optional nodefault)
2929 "Parse the standard Org-mode time string.
2930 This should be a lot faster than the normal `parse-time-string'.
2931 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
2932 hour and minute fields will be nil if not given."
2933 (if (string-match org-ts-regexp1 s)
2934 (list 0
2935 (if (or (match-beginning 8) (not nodefault))
2936 (string-to-number (or (match-string 8 s) "0")))
2937 (if (or (match-beginning 7) (not nodefault))
2938 (string-to-number (or (match-string 7 s) "0")))
2939 (string-to-number (match-string 4 s))
2940 (string-to-number (match-string 3 s))
2941 (string-to-number (match-string 2 s))
2942 nil nil nil)
2943 (make-list 9 0)))
2944
2945 (defun org-timestamp-up (&optional arg)
2946 "Increase the date item at the cursor by one.
2947 If the cursor is on the year, change the year. If it is on the month or
2948 the day, change that.
2949 With prefix ARG, change by that many units."
2950 (interactive "p")
2951 (org-timestamp-change (prefix-numeric-value arg)))
2952
2953 (defun org-timestamp-down (&optional arg)
2954 "Decrease the date item at the cursor by one.
2955 If the cursor is on the year, change the year. If it is on the month or
2956 the day, change that.
2957 With prefix ARG, change by that many units."
2958 (interactive "p")
2959 (org-timestamp-change (- (prefix-numeric-value arg))))
2960
2961 (defun org-timestamp-up-day (&optional arg)
2962 "Increase the date in the time stamp by one day.
2963 With prefix ARG, change that many days."
2964 (interactive "p")
2965 (org-timestamp-change (prefix-numeric-value arg) 'day))
2966
2967 (defun org-timestamp-down-day (&optional arg)
2968 "Decrease the date in the time stamp by one day.
2969 With prefix ARG, change that many days."
2970 (interactive "p")
2971 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
2972
2973 (defsubst org-pos-in-match-range (pos n)
2974 (and (match-beginning n)
2975 (<= (match-beginning n) pos)
2976 (>= (match-end n) pos)))
2977
2978 (defun org-at-timestamp-p ()
2979 "Determine if the cursor is or at a timestamp."
2980 (interactive)
2981 (let* ((tsr org-ts-regexp2)
2982 (pos (point))
2983 (ans (or (looking-at tsr)
2984 (save-excursion
2985 (skip-chars-backward "^<\n\r\t")
2986 (if (> (point) 1) (backward-char 1))
2987 (and (looking-at tsr)
2988 (> (- (match-end 0) pos) -1))))))
2989 (and (boundp 'org-ts-what)
2990 (setq org-ts-what
2991 (cond
2992 ((org-pos-in-match-range pos 2) 'year)
2993 ((org-pos-in-match-range pos 3) 'month)
2994 ((org-pos-in-match-range pos 7) 'hour)
2995 ((org-pos-in-match-range pos 8) 'minute)
2996 ((or (org-pos-in-match-range pos 4)
2997 (org-pos-in-match-range pos 5)) 'day)
2998 (t 'day))))
2999 ans))
3000
3001 (defun org-timestamp-change (n &optional what)
3002 "Change the date in the time stamp at point.
3003 The date will be changed by N times WHAT. WHAT can be `day', `month',
3004 `year', `minute', `second'. If WHAT is not given, the cursor position
3005 in the timestamp determines what will be changed."
3006 (let ((fmt (car org-time-stamp-formats))
3007 org-ts-what
3008 (pos (point))
3009 ts time time0)
3010 (if (not (org-at-timestamp-p))
3011 (error "Not at a timestamp"))
3012 (setq org-ts-what (or what org-ts-what))
3013 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3014 (- (match-end 0) (match-beginning 0))))
3015 1)
3016 (cdr org-time-stamp-formats)
3017 (car org-time-stamp-formats)))
3018 (setq ts (match-string 0))
3019 (replace-match "")
3020 (setq time0 (org-parse-time-string ts))
3021 (setq time
3022 (apply 'encode-time
3023 (append
3024 (list (or (car time0) 0))
3025 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3026 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3027 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3028 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3029 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3030 (nthcdr 6 time0))))
3031 (if (eq what 'calendar)
3032 (let ((cal-date
3033 (save-excursion
3034 (save-match-data
3035 (set-buffer "*Calendar*")
3036 (calendar-cursor-to-date)))))
3037 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3038 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3039 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3040 (setcar time0 (or (car time0) 0))
3041 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3042 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3043 (setq time (apply 'encode-time time0))))
3044 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3045 (goto-char pos)
3046 ;; Try to recenter the calendar window, if any
3047 (if (and org-calendar-follow-timestamp-change
3048 (get-buffer-window "*Calendar*" t)
3049 (memq org-ts-what '(day month year)))
3050 (org-recenter-calendar (time-to-days time)))))
3051
3052 (defun org-recenter-calendar (date)
3053 "If the calendar is visible, recenter it to DATE."
3054 (let* ((win (selected-window))
3055 (cwin (get-buffer-window "*Calendar*" t)))
3056 (when cwin
3057 (select-window cwin)
3058 (calendar-goto-date (if (listp date) date
3059 (calendar-gregorian-from-absolute date)))
3060 (select-window win))))
3061
3062 (defun org-goto-calendar (&optional arg)
3063 "Go to the Emacs calendar at the current date.
3064 If there is a time stamp in the current line, go to that date.
3065 A prefix ARG can be used force the current date."
3066 (interactive "P")
3067 (let ((tsr org-ts-regexp) diff)
3068 (if (or (org-at-timestamp-p)
3069 (save-excursion
3070 (beginning-of-line 1)
3071 (looking-at (concat ".*" tsr))))
3072 (let ((d1 (time-to-days (current-time)))
3073 (d2 (time-to-days
3074 (org-time-string-to-time (match-string 1)))))
3075 (setq diff (- d2 d1))))
3076 (calendar)
3077 (calendar-goto-today)
3078 (if (and diff (not arg)) (calendar-forward-day diff))))
3079
3080 (defun org-date-from-calendar ()
3081 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3082 If there is already a time stamp at the cursor position, update it."
3083 (interactive)
3084 (org-timestamp-change 0 'calendar))
3085
3086 ;;; Agenda, and Diary Integration
3087
3088 ;;; Define the mode
3089
3090 (defvar org-agenda-mode-map (make-sparse-keymap)
3091 "Keymap for `org-agenda-mode'.")
3092
3093 (defvar org-agenda-menu)
3094 (defvar org-agenda-follow-mode nil)
3095 (defvar org-agenda-buffer-name "*Org Agenda*")
3096 (defvar org-agenda-redo-command nil)
3097
3098 ;;;###autoload
3099 (defun org-agenda-mode ()
3100 "Mode for time-sorted view on action items in Org-mode files.
3101
3102 The following commands are available:
3103
3104 \\{org-agenda-mode-map}"
3105 (interactive)
3106 (kill-all-local-variables)
3107 (setq major-mode 'org-agenda-mode)
3108 (setq mode-name "Org-Agenda")
3109 (use-local-map org-agenda-mode-map)
3110 (easy-menu-add org-agenda-menu)
3111 (if org-startup-truncated (setq truncate-lines t))
3112 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3113 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3114 (setq org-agenda-follow-mode nil)
3115 (easy-menu-change
3116 '("Agenda") "Agenda Files"
3117 (append
3118 (list
3119 ["Edit File List" (customize-variable 'org-agenda-files) t]
3120 "--")
3121 (mapcar 'org-file-menu-entry org-agenda-files)))
3122 (org-agenda-set-mode-name)
3123 (run-hooks 'org-agenda-mode-hook))
3124
3125 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
3126 (define-key org-agenda-mode-map [(return)] 'org-agenda-switch-to)
3127 (define-key org-agenda-mode-map " " 'org-agenda-show)
3128 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3129 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3130 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3131 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3132 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3133 (define-key org-agenda-mode-map "w" 'org-agenda-toggle-week-view)
3134 (define-key org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
3135 (define-key org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
3136
3137 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3138 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3139 (while l (define-key org-agenda-mode-map
3140 (int-to-string (pop l)) 'digit-argument)))
3141
3142 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3143 (define-key org-agenda-mode-map "d" 'org-agenda-toggle-diary)
3144 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3145 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3146 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3147 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3148 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3149 (define-key org-agenda-mode-map "n" 'next-line)
3150 (define-key org-agenda-mode-map "p" 'previous-line)
3151 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3152 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3153 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3154 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3155 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3156 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3157 (eval-after-load "calendar"
3158 '(define-key calendar-mode-map org-calendar-to-agenda-key
3159 'org-calendar-goto-agenda))
3160 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3161 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3162 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3163 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3164 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3165 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3166 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3167 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3168 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3169 (define-key org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
3170 (define-key org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
3171 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3172 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3173
3174 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3175 "Local keymap for agenda entries from Org-mode.")
3176
3177 (define-key org-agenda-keymap
3178 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3179 (define-key org-agenda-keymap
3180 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3181
3182 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3183 '("Agenda"
3184 ("Agenda Files")
3185 "--"
3186 ["Show" org-agenda-show t]
3187 ["Go To (other window)" org-agenda-goto t]
3188 ["Go To (one window)" org-agenda-switch-to t]
3189 ["Follow Mode" org-agenda-follow-mode
3190 :style toggle :selected org-agenda-follow-mode :active t]
3191 "--"
3192 ["Cycle TODO" org-agenda-todo t]
3193 ("Reschedule"
3194 ["Reschedule +1 day" org-agenda-date-later t]
3195 ["Reschedule -1 day" org-agenda-date-earlier t]
3196 "--"
3197 ["Reschedule to ..." org-agenda-date-prompt t])
3198 ("Priority"
3199 ["Set Priority" org-agenda-priority t]
3200 ["Increase Priority" org-agenda-priority-up t]
3201 ["Decrease Priority" org-agenda-priority-down t]
3202 ["Show Priority" org-agenda-show-priority t])
3203 "--"
3204 ["Rebuild buffer" org-agenda-redo t]
3205 ["Goto Today" org-agenda-goto-today t]
3206 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3207 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3208 "--"
3209 ["Week/Day View" org-agenda-toggle-week-view
3210 (local-variable-p 'starting-day)]
3211 ["Include Diary" org-agenda-toggle-diary
3212 :style toggle :selected org-agenda-include-diary :active t]
3213 ["Use Time Grid" org-agenda-toggle-time-grid
3214 :style toggle :selected org-agenda-use-time-grid :active t]
3215 "--"
3216 ["New Diary Entry" org-agenda-diary-entry t]
3217 ("Calendar Commands"
3218 ["Goto Calendar" org-agenda-goto-calendar t]
3219 ["Phases of the Moon" org-agenda-phases-of-moon t]
3220 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3221 ["Holidays" org-agenda-holidays t]
3222 ["Convert" org-agenda-convert-date t])
3223 "--"
3224 ["Quit" org-agenda-quit t]
3225 ["Exit and Release Buffers" org-agenda-exit t]
3226 ))
3227
3228 (defvar org-agenda-markers nil
3229 "List of all currently active markers created by `org-agenda'.")
3230 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3231 "Creation time of the last agenda marker.")
3232
3233 (defun org-agenda-new-marker (&optional pos)
3234 "Return a new agenda marker.
3235 Org-mode keeps a list of these markers and resets them when they are
3236 no longer in use."
3237 (let ((m (copy-marker (or pos (point)))))
3238 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3239 (push m org-agenda-markers)
3240 m))
3241
3242 (defun org-agenda-maybe-reset-markers (&optional force)
3243 "Reset markers created by `org-agenda'. But only if they are old enough."
3244 (if (or force
3245 (> (- (time-to-seconds (current-time))
3246 org-agenda-last-marker-time)
3247 5))
3248 (while org-agenda-markers
3249 (move-marker (pop org-agenda-markers) nil))))
3250
3251 (defvar org-agenda-new-buffers nil
3252 "Buffers created to visit agenda files.")
3253
3254 (defun org-get-agenda-file-buffer (file)
3255 "Get a buffer visiting FILE. If the buffer needs to be created, add
3256 it to the list of buffers which might be released later."
3257 (let ((buf (find-buffer-visiting file)))
3258 (if buf
3259 buf ; just return it
3260 ;; Make a new buffer and remember it
3261 (setq buf (find-file-noselect file))
3262 (if buf (push buf org-agenda-new-buffers))
3263 buf)))
3264
3265 (defun org-release-buffers (blist)
3266 "Release all buffers in list, asking the user for confirmation when needed.
3267 When a buffer is unmodified, it is just killed. When modified, it is saved
3268 \(if the user agrees) and then killed."
3269 (let (buf file)
3270 (while (setq buf (pop blist))
3271 (setq file (buffer-file-name buf))
3272 (when (and (buffer-modified-p buf)
3273 file
3274 (y-or-n-p (format "Save file %s? " file)))
3275 (with-current-buffer buf (save-buffer)))
3276 (kill-buffer buf))))
3277
3278 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3279
3280 (defun org-timeline (&optional include-all)
3281 "Show a time-sorted view of the entries in the current org file.
3282 Only entries with a time stamp of today or later will be listed. With
3283 one \\[universal-argument] prefix argument, past entries will also be listed.
3284 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3285 under the current date.
3286 If the buffer contains an active region, only check the region for
3287 dates."
3288 (interactive "P")
3289 (require 'calendar)
3290 (org-agenda-maybe-reset-markers 'force)
3291 (org-compile-prefix-format org-timeline-prefix-format)
3292 (let* ((dopast include-all)
3293 (dotodo (equal include-all '(16)))
3294 (entry (buffer-file-name))
3295 (org-agenda-files (list (buffer-file-name)))
3296 (date (calendar-current-date))
3297 (win (selected-window))
3298 (pos1 (point))
3299 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3300 (end (if (org-region-active-p) (region-end) (point-max)))
3301 (day-numbers (org-get-all-dates beg end 'no-ranges
3302 t)) ; always include today
3303 (today (time-to-days (current-time)))
3304 (org-respect-restriction t)
3305 (past t)
3306 s e rtn d)
3307 (setq org-agenda-redo-command
3308 (list 'progn
3309 (list 'switch-to-buffer-other-window (current-buffer))
3310 (list 'org-timeline include-all)))
3311 (if (not dopast)
3312 ;; Remove past dates from the list of dates.
3313 (setq day-numbers (delq nil (mapcar (lambda(x)
3314 (if (>= x today) x nil))
3315 day-numbers))))
3316 (switch-to-buffer-other-window
3317 (get-buffer-create org-agenda-buffer-name))
3318 (setq buffer-read-only nil)
3319 (erase-buffer)
3320 (org-agenda-mode) (setq buffer-read-only nil)
3321 (while (setq d (pop day-numbers))
3322 (if (and (>= d today)
3323 dopast
3324 past)
3325 (progn
3326 (setq past nil)
3327 (insert (make-string 79 ?-) "\n")))
3328 (setq date (calendar-gregorian-from-absolute d))
3329 (setq s (point))
3330 (if dotodo
3331 (setq rtn (org-agenda-get-day-entries
3332 entry date :todo :timestamp))
3333 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3334 (if (or rtn (equal d today))
3335 (progn
3336 (insert (calendar-day-name date) " "
3337 (number-to-string (extract-calendar-day date)) " "
3338 (calendar-month-name (extract-calendar-month date)) " "
3339 (number-to-string (extract-calendar-year date)) "\n")
3340 (put-text-property s (1- (point)) 'face
3341 'org-link-face)
3342 (if (equal d today)
3343 (put-text-property s (1- (point)) 'org-today t))
3344 (insert (org-finalize-agenda-entries rtn) "\n")
3345 (put-text-property s (1- (point)) 'day d))))
3346 (goto-char (point-min))
3347 (setq buffer-read-only t)
3348 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3349 (point-min)))
3350 (when (not org-select-timeline-window)
3351 (select-window win)
3352 (goto-char pos1))))
3353
3354 ;;;###autoload
3355 (defun org-agenda (&optional include-all start-day ndays)
3356 "Produce a weekly view from all files in variable `org-agenda-files'.
3357 The view will be for the current week, but from the overview buffer you
3358 will be able to go to other weeks.
3359 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3360 also be shown, under the current date.
3361 START-DAY defaults to TODAY, or to the most recent match for the weekday
3362 given in `org-agenda-start-on-weekday'.
3363 NDAYS defaults to `org-agenda-ndays'."
3364 (interactive "P")
3365 (org-agenda-maybe-reset-markers 'force)
3366 (org-compile-prefix-format org-agenda-prefix-format)
3367 (require 'calendar)
3368 (let* ((org-agenda-start-on-weekday
3369 (if (or (equal ndays 1)
3370 (and (null ndays) (equal 1 org-agenda-ndays)))
3371 nil org-agenda-start-on-weekday))
3372 (files (copy-sequence org-agenda-files))
3373 (win (selected-window))
3374 (today (time-to-days (current-time)))
3375 (sd (or start-day today))
3376 (start (if (or (null org-agenda-start-on-weekday)
3377 (< org-agenda-ndays 7))
3378 sd
3379 (let* ((nt (calendar-day-of-week
3380 (calendar-gregorian-from-absolute sd)))
3381 (n1 org-agenda-start-on-weekday)
3382 (d (- nt n1)))
3383 (- sd (+ (if (< d 0) 7 0) d)))))
3384 (day-numbers (list start))
3385 (inhibit-redisplay t)
3386 s e rtn rtnall file date d start-pos end-pos todayp nd)
3387 (setq org-agenda-redo-command
3388 (list 'org-agenda include-all start-day ndays))
3389 ;; Make the list of days
3390 (setq ndays (or ndays org-agenda-ndays)
3391 nd ndays)
3392 (while (> ndays 1)
3393 (push (1+ (car day-numbers)) day-numbers)
3394 (setq ndays (1- ndays)))
3395 (setq day-numbers (nreverse day-numbers))
3396 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3397 (progn
3398 (delete-other-windows)
3399 (switch-to-buffer-other-window
3400 (get-buffer-create org-agenda-buffer-name))))
3401 (setq buffer-read-only nil)
3402 (erase-buffer)
3403 (org-agenda-mode) (setq buffer-read-only nil)
3404 (set (make-local-variable 'starting-day) (car day-numbers))
3405 (set (make-local-variable 'include-all-loc) include-all)
3406 (when (and (or include-all org-agenda-include-all-todo)
3407 (member today day-numbers))
3408 (setq files org-agenda-files
3409 rtnall nil)
3410 (while (setq file (pop files))
3411 (catch 'nextfile
3412 (org-check-agenda-file file)
3413 (setq date (calendar-gregorian-from-absolute today)
3414 rtn (org-agenda-get-day-entries
3415 file date :todo))
3416 (setq rtnall (append rtnall rtn))))
3417 (when rtnall
3418 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3419 (add-text-properties (point-min) (1- (point))
3420 (list 'face 'org-link-face))
3421 (insert (org-finalize-agenda-entries rtnall) "\n")))
3422 (while (setq d (pop day-numbers))
3423 (setq date (calendar-gregorian-from-absolute d)
3424 s (point))
3425 (if (or (setq todayp (= d today))
3426 (and (not start-pos) (= d sd)))
3427 (setq start-pos (point))
3428 (if (and start-pos (not end-pos))
3429 (setq end-pos (point))))
3430 (setq files org-agenda-files
3431 rtnall nil)
3432 (while (setq file (pop files))
3433 (catch 'nextfile
3434 (org-check-agenda-file file)
3435 (setq rtn (org-agenda-get-day-entries file date))
3436 (setq rtnall (append rtnall rtn))))
3437 (if org-agenda-include-diary
3438 (progn
3439 (require 'diary-lib)
3440 (setq rtn (org-get-entries-from-diary date))
3441 (setq rtnall (append rtnall rtn))))
3442 (if (or rtnall org-agenda-show-all-dates)
3443 (progn
3444 (insert (format "%-9s %2d %s %4d\n"
3445 (calendar-day-name date)
3446 (extract-calendar-day date)
3447 (calendar-month-name (extract-calendar-month date))
3448 (extract-calendar-year date)))
3449 (put-text-property s (1- (point)) 'face
3450 'org-link-face)
3451 (if rtnall (insert
3452 (org-finalize-agenda-entries ;; FIXME: condition needed
3453 (org-agenda-add-time-grid-maybe
3454 rtnall nd todayp))
3455 "\n"))
3456 (put-text-property s (1- (point)) 'day d))))
3457 (goto-char (point-min))
3458 (setq buffer-read-only t)
3459 (if org-fit-agenda-window
3460 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3461 (/ (frame-height) 2)))
3462 (unless (and (pos-visible-in-window-p (point-min))
3463 (pos-visible-in-window-p (point-max)))
3464 (goto-char (1- (point-max)))
3465 (recenter -1)
3466 (if (not (pos-visible-in-window-p (or start-pos 1)))
3467 (progn
3468 (goto-char (or start-pos 1))
3469 (recenter 1))))
3470 (goto-char (or start-pos 1))
3471 (if (not org-select-agenda-window) (select-window win))
3472 (message "")))
3473
3474 (defun org-check-agenda-file (file)
3475 "Make sure FILE exists. If not, ask user what to do."
3476 ;; FIXME: this does not correctly change the menus
3477 ;; Could probably be fixed by explicitly going to the buffer.
3478 (when (not (file-exists-p file))
3479 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3480 file)
3481 (let ((r (downcase (read-char-exclusive))))
3482 (cond
3483 ((equal r ?r)
3484 (org-remove-file file)
3485 (throw 'nextfile t))
3486 (t (error "Abort"))))))
3487
3488 (defun org-agenda-quit ()
3489 "Exit agenda by removing the window or the buffer."
3490 (interactive)
3491 (let ((buf (current-buffer)))
3492 (if (not (one-window-p)) (delete-window))
3493 (kill-buffer buf)
3494 (org-agenda-maybe-reset-markers 'force)))
3495
3496 (defun org-agenda-exit ()
3497 "Exit agenda by removing the window or the buffer.
3498 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3499 Org-mode buffers visited directly by the user will not be touched."
3500 (interactive)
3501 (org-release-buffers org-agenda-new-buffers)
3502 (setq org-agenda-new-buffers nil)
3503 (org-agenda-quit))
3504
3505 (defun org-agenda-redo ()
3506 "Rebuild Agenda."
3507 (interactive)
3508 (eval org-agenda-redo-command))
3509
3510 (defun org-agenda-goto-today ()
3511 "Go to today."
3512 (interactive)
3513 (if (boundp 'starting-day)
3514 (let ((cmd (car org-agenda-redo-command))
3515 (iall (nth 1 org-agenda-redo-command))
3516 (nday (nth 3 org-agenda-redo-command)))
3517 (eval (list cmd iall nil nday)))
3518 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3519 (point-min)))))
3520
3521 (defun org-agenda-later (arg)
3522 "Go forward in time by `org-agenda-ndays' days.
3523 With prefix ARG, go forward that many times `org-agenda-ndays'."
3524 (interactive "p")
3525 (unless (boundp 'starting-day)
3526 (error "Not allowed"))
3527 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3528 (+ starting-day (* arg org-agenda-ndays))))
3529
3530 (defun org-agenda-earlier (arg)
3531 "Go back in time by `org-agenda-ndays' days.
3532 With prefix ARG, go back that many times `org-agenda-ndays'."
3533 (interactive "p")
3534 (unless (boundp 'starting-day)
3535 (error "Not allowed"))
3536 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3537 (- starting-day (* arg org-agenda-ndays))))
3538
3539 (defun org-agenda-toggle-week-view ()
3540 "Toggle weekly/daily view for aagenda."
3541 (interactive)
3542 (unless (boundp 'starting-day)
3543 (error "Not allowed"))
3544 (setq org-agenda-ndays
3545 (if (equal org-agenda-ndays 1) 7 1))
3546 (org-agenda include-all-loc
3547 (or (get-text-property (point) 'day)
3548 starting-day))
3549 (org-agenda-set-mode-name)
3550 (message "Switched to %s view"
3551 (if (equal org-agenda-ndays 1) "day" "week")))
3552
3553 (defun org-agenda-next-date-line (&optional arg)
3554 "Jump to the next line indicating a date in agenda buffer."
3555 (interactive "p")
3556 (beginning-of-line 1)
3557 (if (looking-at "^\\S-") (forward-char 1))
3558 (if (not (re-search-forward "^\\S-" nil t arg))
3559 (progn
3560 (backward-char 1)
3561 (error "No next date after this line in this buffer.")))
3562 (goto-char (match-beginning 0)))
3563
3564 (defun org-agenda-previous-date-line (&optional arg)
3565 "Jump to the next line indicating a date in agenda buffer."
3566 (interactive "p")
3567 (beginning-of-line 1)
3568 (if (not (re-search-backward "^\\S-" nil t arg))
3569 (error "No previous date before this line in this buffer.")))
3570
3571 ;; Initialize the highlight
3572 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3573 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3574 'face 'highlight)
3575
3576 (defun org-highlight (begin end &optional buffer)
3577 "Highlight a region with overlay."
3578 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3579 org-hl begin end (or buffer (current-buffer))))
3580
3581 (defun org-unhighlight ()
3582 "Detach overlay INDEX."
3583 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3584
3585
3586 (defun org-agenda-follow-mode ()
3587 "Toggle follow mode in an agenda buffer."
3588 (interactive)
3589 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3590 (org-agenda-set-mode-name)
3591 (message "Follow mode is %s"
3592 (if org-agenda-follow-mode "on" "off")))
3593
3594 (defun org-agenda-toggle-diary ()
3595 "Toggle follow mode in an agenda buffer."
3596 (interactive)
3597 (setq org-agenda-include-diary (not org-agenda-include-diary))
3598 (org-agenda-redo)
3599 (org-agenda-set-mode-name)
3600 (message "Diary inclusion turned %s"
3601 (if org-agenda-include-diary "on" "off")))
3602
3603 (defun org-agenda-toggle-time-grid ()
3604 "Toggle follow mode in an agenda buffer."
3605 (interactive)
3606 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3607 (org-agenda-redo)
3608 (org-agenda-set-mode-name)
3609 (message "Time-grid turned %s"
3610 (if org-agenda-use-time-grid "on" "off")))
3611
3612 (defun org-agenda-set-mode-name ()
3613 "Set the mode name to indicate all the small mode settings."
3614 (setq mode-name
3615 (concat "Org-Agenda"
3616 (if (equal org-agenda-ndays 1) " Day" "")
3617 (if (equal org-agenda-ndays 7) " Week" "")
3618 (if org-agenda-follow-mode " Follow" "")
3619 (if org-agenda-include-diary " Diary" "")
3620 (if org-agenda-use-time-grid " Grid" "")))
3621 (force-mode-line-update))
3622
3623 (defun org-agenda-post-command-hook ()
3624 (and (eolp) (not (bolp)) (backward-char 1))
3625 (if (and org-agenda-follow-mode
3626 (get-text-property (point) 'org-marker))
3627 (org-agenda-show)))
3628
3629 (defvar org-disable-diary nil) ;Dynamically-scoped param.
3630
3631 (defun org-get-entries-from-diary (date)
3632 "Get the (Emacs Calendar) diary entries for DATE."
3633 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
3634 (diary-display-hook '(fancy-diary-display))
3635 (list-diary-entries-hook
3636 (cons 'org-diary-default-entry list-diary-entries-hook))
3637 entries
3638 (org-disable-diary t))
3639 (save-excursion
3640 (save-window-excursion
3641 (list-diary-entries date 1)))
3642 (if (not (get-buffer fancy-diary-buffer))
3643 (setq entries nil)
3644 (with-current-buffer fancy-diary-buffer
3645 (setq buffer-read-only nil)
3646 (if (= (point-max) 1)
3647 ;; No entries
3648 (setq entries nil)
3649 ;; Omit the date and other unnecessary stuff
3650 (org-agenda-cleanup-fancy-diary)
3651 ;; Add prefix to each line and extend the text properties
3652 (if (= (point-max) 1)
3653 (setq entries nil)
3654 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
3655 (set-buffer-modified-p nil)
3656 (kill-buffer fancy-diary-buffer)))
3657 (when entries
3658 (setq entries (org-split-string entries "\n"))
3659 (setq entries
3660 (mapcar
3661 (lambda (x)
3662 (setq x (org-format-agenda-item "" x "Diary" 'time))
3663 ;; Extend the text properties to the beginning of the line
3664 (add-text-properties
3665 0 (length x)
3666 (text-properties-at (1- (length x)) x)
3667 x)
3668 x)
3669 entries)))))
3670
3671 (defun org-agenda-cleanup-fancy-diary ()
3672 "Remove unwanted stuff in buffer created by fancy-diary-display.
3673 This gets rid of the date, the underline under the date, and
3674 the dummy entry installed by `org-mode' to ensure non-empty diary for each
3675 date. Itt also removes lines that contain only whitespace."
3676 (goto-char (point-min))
3677 (if (looking-at ".*?:[ \t]*")
3678 (progn
3679 (replace-match "")
3680 (re-search-forward "\n=+$" nil t)
3681 (replace-match "")
3682 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
3683 (re-search-forward "\n=+$" nil t)
3684 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
3685 (goto-char (point-min))
3686 (while (re-search-forward "^ +\n" nil t)
3687 (replace-match ""))
3688 (goto-char (point-min))
3689 (if (re-search-forward "^Org-mode dummy\n?" nil t)
3690 (replace-match "")))
3691
3692 ;; Advise the add-to-diary-list function to allow org to jump to
3693 ;; diary entries. Wrapped into eval-after-load to avoid loading
3694 ;; advice unnecessarily
3695 (eval-after-load "diary-lib"
3696 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
3697 "Make the position visible."
3698 (if (and org-disable-diary ;; called from org-agenda
3699 (stringp string)
3700 (buffer-file-name))
3701 (add-text-properties
3702 0 (length string)
3703 (list 'mouse-face 'highlight
3704 'keymap org-agenda-keymap
3705 'help-echo
3706 (format
3707 "mouse-2 or RET jump to diary file %s"
3708 (abbreviate-file-name (buffer-file-name)))
3709 'org-agenda-diary-link t
3710 'org-marker (org-agenda-new-marker (point-at-bol)))
3711 string))))
3712
3713 (defun org-diary-default-entry ()
3714 "Add a dummy entry to the diary.
3715 Needed to avoid empty dates which mess up holiday display."
3716 ;; Catch the error if dealing with the new add-to-diary-alist
3717 (condition-case nil
3718 (add-to-diary-list original-date "Org-mode dummy" "")
3719 (error
3720 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
3721
3722 (defun org-add-file (&optional file)
3723 "Add current file to the list of files in variable `org-agenda-files'.
3724 These are the files which are being checked for agenda entries.
3725 Optional argument FILE means, use this file instead of the current.
3726 It is possible (but not recommended) to add this function to the
3727 `org-mode-hook'."
3728 (interactive)
3729 (catch 'exit
3730 (let* ((file (or file (buffer-file-name)
3731 (if (interactive-p)
3732 (error "Buffer is not visiting a file")
3733 (throw 'exit nil))))
3734 (true-file (file-truename file))
3735 (afile (abbreviate-file-name file))
3736 (present (delq nil (mapcar
3737 (lambda (x)
3738 (equal true-file (file-truename x)))
3739 org-agenda-files))))
3740 (if (not present)
3741 (progn
3742 (setq org-agenda-files
3743 (cons afile org-agenda-files))
3744 ;; Make sure custom.el does not end up with Org-mode
3745 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
3746 (customize-save-variable 'org-agenda-files org-agenda-files))
3747 (org-install-agenda-files-menu)
3748 (message "Added file: %s" afile))
3749 (message "File was already in list: %s" afile)))))
3750
3751 (defun org-remove-file (&optional file)
3752 "Remove current file from the list of files in variable `org-agenda-files'.
3753 These are the files which are being checked for agenda entries.
3754 Optional argument FILE means, use this file instead of the current."
3755 (interactive)
3756 (let* ((file (or file (buffer-file-name)))
3757 (true-file (file-truename file))
3758 (afile (abbreviate-file-name file))
3759 (files (delq nil (mapcar
3760 (lambda (x)
3761 (if (equal true-file
3762 (file-truename x))
3763 nil x))
3764 org-agenda-files))))
3765 (if (not (= (length files) (length org-agenda-files)))
3766 (progn
3767 (setq org-agenda-files files)
3768 (customize-save-variable 'org-agenda-files org-agenda-files)
3769 (org-install-agenda-files-menu)
3770 (message "Removed file: %s" afile))
3771 (message "File was not in list: %s" afile))))
3772
3773 (defun org-file-menu-entry (file)
3774 (vector file (list 'find-file file) t))
3775
3776 (defun org-get-all-dates (beg end &optional no-ranges force-today)
3777 "Return a list of all relevant day numbers from BEG to END buffer positions.
3778 If NO-RANGES is non-nil, include only the start and end dates of a range,
3779 not every single day in the range. If FORCE-TODAY is non-nil, make
3780 sure that TODAY is included in the list."
3781 (let (dates date day day1 day2 ts1 ts2)
3782 (if force-today
3783 (setq dates (list (time-to-days (current-time)))))
3784 (save-excursion
3785 (goto-char beg)
3786 (while (re-search-forward org-ts-regexp end t)
3787 (setq day (time-to-days (org-time-string-to-time
3788 (substring (match-string 1) 0 10))))
3789 (or (memq day dates) (push day dates)))
3790 (unless no-ranges
3791 (goto-char beg)
3792 (while (re-search-forward org-tr-regexp end t)
3793 (setq ts1 (substring (match-string 1) 0 10)
3794 ts2 (substring (match-string 2) 0 10)
3795 day1 (time-to-days (org-time-string-to-time ts1))
3796 day2 (time-to-days (org-time-string-to-time ts2)))
3797 (while (< (setq day1 (1+ day1)) day2)
3798 (or (memq day1 dates) (push day1 dates)))))
3799 (sort dates '<))))
3800
3801 ;;;###autoload
3802 (defun org-diary (&rest args)
3803 "Return diary information from org-files.
3804 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
3805 It accesses org files and extracts information from those files to be
3806 listed in the diary. The function accepts arguments specifying what
3807 items should be listed. The following arguments are allowed:
3808
3809 :timestamp List the headlines of items containing a date stamp or
3810 date range matching the selected date. Deadlines will
3811 also be listed, on the expiration day.
3812
3813 :deadline List any deadlines past due, or due within
3814 `org-deadline-warning-days'. The listing occurs only
3815 in the diary for *today*, not at any other date. If
3816 an entry is marked DONE, it is no longer listed.
3817
3818 :scheduled List all items which are scheduled for the given date.
3819 The diary for *today* also contains items which were
3820 scheduled earlier and are not yet marked DONE.
3821
3822 :todo List all TODO items from the org-file. This may be a
3823 long list - so this is not turned on by default.
3824 Like deadlines, these entries only show up in the
3825 diary for *today*, not at any other date.
3826
3827 The call in the diary file should look like this:
3828
3829 &%%(org-diary) ~/path/to/some/orgfile.org
3830
3831 Use a separate line for each org file to check. Or, if you omit the file name,
3832 all files listed in `org-agenda-files' will be checked automatically:
3833
3834 &%%(org-diary)
3835
3836 If you don't give any arguments (as in the example above), the default
3837 arguments (:deadline :scheduled :timestamp) are used. So the example above may
3838 also be written as
3839
3840 &%%(org-diary :deadline :timestamp :scheduled)
3841
3842 The function expects the lisp variables `entry' and `date' to be provided
3843 by the caller, because this is how the calendar works. Don't use this
3844 function from a program - use `org-agenda-get-day-entries' instead."
3845 (org-agenda-maybe-reset-markers)
3846 (org-compile-agenda-prefix-format org-agenda-prefix-format)
3847 (setq args (or args '(:deadline :scheduled :timestamp)))
3848 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
3849 (list entry)
3850 org-agenda-files))
3851 file rtn results)
3852 ;; If this is called during org-agenda, don't return any entries to
3853 ;; the calendar. Org Agenda will list these entries itself.
3854 (if org-disable-diary (setq files nil))
3855 (while (setq file (pop files))
3856 (setq rtn (apply 'org-agenda-get-day-entries file date args))
3857 (setq results (append results rtn)))
3858 (concat (org-finalize-agenda-entries results) "\n")))
3859
3860 (defun org-agenda-get-day-entries (file date &rest args)
3861 "Does the work for `org-diary' and `org-agenda'.
3862 FILE is the path to a file to be checked for entries. DATE is date like
3863 the one returned by `calendar-current-date'. ARGS are symbols indicating
3864 which kind of entries should be extracted. For details about these, see
3865 the documentation of `org-diary'."
3866 (setq args (or args '(:deadline :scheduled :timestamp)))
3867 (let* ((org-startup-with-deadline-check nil)
3868 (org-startup-folded nil)
3869 (buffer (if (file-exists-p file)
3870 (org-get-agenda-file-buffer file)
3871 (error "No such file %s" file)))
3872 arg results rtn)
3873 (if (not buffer)
3874 ;; If file does not exist, make sure an error message ends up in diary
3875 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
3876 (with-current-buffer buffer
3877 (unless (eq major-mode 'org-mode)
3878 (error "Agenda file %s is not in `org-mode'" file))
3879 (let ((case-fold-search nil))
3880 (save-excursion
3881 (save-restriction
3882 (if org-respect-restriction
3883 (if (org-region-active-p)
3884 ;; Respect a region to restrict search
3885 (narrow-to-region (region-beginning) (region-end)))
3886 ;; If we work for the calendar or many files,
3887 ;; get rid of any restriction
3888 (widen))
3889 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
3890 (while (setq arg (pop args))
3891 (cond
3892 ((and (eq arg :todo)
3893 (equal date (calendar-current-date)))
3894 (setq rtn (org-agenda-get-todos))
3895 (setq results (append results rtn)))
3896 ((eq arg :timestamp)
3897 (setq rtn (org-agenda-get-blocks))
3898 (setq results (append results rtn))
3899 (setq rtn (org-agenda-get-timestamps))
3900 (setq results (append results rtn)))
3901 ((eq arg :scheduled)
3902 (setq rtn (org-agenda-get-scheduled))
3903 (setq results (append results rtn)))
3904 ((and (eq arg :deadline)
3905 (equal date (calendar-current-date)))
3906 (setq rtn (org-agenda-get-deadlines))
3907 (setq results (append results rtn))))))))
3908 results))))
3909
3910 (defun org-entry-is-done-p ()
3911 "Is the current entry marked DONE?"
3912 (save-excursion
3913 (and (re-search-backward "[\r\n]\\*" nil t)
3914 (looking-at org-nl-done-regexp))))
3915
3916 (defun org-at-date-range-p ()
3917 "Is the cursor inside a date range?"
3918 (interactive)
3919 (save-excursion
3920 (catch 'exit
3921 (let ((pos (point)))
3922 (skip-chars-backward "^<\r\n")
3923 (skip-chars-backward "<")
3924 (and (looking-at org-tr-regexp)
3925 (>= (match-end 0) pos)
3926 (throw 'exit t))
3927 (skip-chars-backward "^<\r\n")
3928 (skip-chars-backward "<")
3929 (and (looking-at org-tr-regexp)
3930 (>= (match-end 0) pos)
3931 (throw 'exit t)))
3932 nil)))
3933
3934 (defun org-agenda-get-todos ()
3935 "Return the TODO information for agenda display."
3936 (let* ((props (list 'face nil
3937 'done-face 'org-done-face
3938 'mouse-face 'highlight
3939 'keymap org-agenda-keymap
3940 'help-echo
3941 (format "mouse-2 or RET jump to org file %s"
3942 (abbreviate-file-name (buffer-file-name)))))
3943 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
3944 "[^\n\r]*\\)"))
3945 marker priority
3946 ee txt)
3947 (goto-char (point-min))
3948 (while (re-search-forward regexp nil t)
3949 (goto-char (match-beginning 1))
3950 (setq marker (org-agenda-new-marker (point-at-bol))
3951 txt (org-format-agenda-item "" (match-string 1))
3952 priority
3953 (+ (org-get-priority txt)
3954 (if org-todo-kwd-priority-p
3955 (- org-todo-kwd-max-priority -2
3956 (length
3957 (member (match-string 2) org-todo-keywords)))
3958 1)))
3959 (add-text-properties
3960 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
3961 'priority priority)
3962 props)
3963 txt)
3964 (push txt ee)
3965 (goto-char (match-end 1)))
3966 (nreverse ee)))
3967
3968 (defconst org-agenda-no-heading-message
3969 "No heading for this item in buffer or region")
3970
3971 (defun org-agenda-get-timestamps ()
3972 "Return the date stamp information for agenda display."
3973 (let* ((props (list 'face nil
3974 'mouse-face 'highlight
3975 'keymap org-agenda-keymap
3976 'help-echo
3977 (format "mouse-2 or RET jump to org file %s"
3978 (abbreviate-file-name (buffer-file-name)))))
3979 (regexp (regexp-quote
3980 (substring
3981 (format-time-string
3982 (car org-time-stamp-formats)
3983 (apply 'encode-time ; DATE bound by calendar
3984 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
3985 0 11)))
3986 marker hdmarker deadlinep scheduledp donep tmp priority
3987 ee txt timestr)
3988 (goto-char (point-min))
3989 (while (re-search-forward regexp nil t)
3990 (if (not (save-match-data (org-at-date-range-p)))
3991 (progn
3992 (setq marker (org-agenda-new-marker (match-beginning 0))
3993 tmp (buffer-substring (max (point-min)
3994 (- (match-beginning 0)
3995 org-ds-keyword-length))
3996 (match-beginning 0))
3997 timestr (buffer-substring (match-beginning 0) (point-at-eol))
3998 deadlinep (string-match org-deadline-regexp tmp)
3999 scheduledp (string-match org-scheduled-regexp tmp)
4000 donep (org-entry-is-done-p))
4001 (if (string-match ">" timestr)
4002 ;; substring should only run to end of time stamp
4003 (setq timestr (substring timestr 0 (match-end 0))))
4004 (save-excursion
4005 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4006 (progn
4007 (goto-char (match-end 1))
4008 (setq hdmarker (org-agenda-new-marker))
4009 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4010 (setq txt (org-format-agenda-item
4011 (format "%s%s"
4012 (if deadlinep "Deadline: " "")
4013 (if scheduledp "Scheduled: " ""))
4014 (match-string 1) nil timestr)))
4015 (setq txt org-agenda-no-heading-message))
4016 (setq priority (org-get-priority txt))
4017 (add-text-properties
4018 0 (length txt) (append (list 'org-marker marker
4019 'org-hd-marker hdmarker) props)
4020 txt)
4021 (if deadlinep
4022 (add-text-properties
4023 0 (length txt)
4024 (list 'face
4025 (if donep 'org-done-face 'org-warning-face)
4026 'undone-face 'org-warning-face
4027 'done-face 'org-done-face
4028 'priority (+ 100 priority))
4029 txt)
4030 (if scheduledp
4031 (add-text-properties
4032 0 (length txt)
4033 (list 'face 'org-scheduled-today-face
4034 'undone-face 'org-scheduled-today-face
4035 'done-face 'org-done-face
4036 priority (+ 99 priority))
4037 txt)
4038 (add-text-properties
4039 0 (length txt)
4040 (list 'priority priority) txt)))
4041 (push txt ee))
4042 (outline-next-heading))))
4043 (nreverse ee)))
4044
4045 (defun org-agenda-get-deadlines ()
4046 "Return the deadline information for agenda display."
4047 (let* ((wdays org-deadline-warning-days)
4048 (props (list 'mouse-face 'highlight
4049 'keymap org-agenda-keymap
4050 'help-echo
4051 (format "mouse-2 or RET jump to org file %s"
4052 (abbreviate-file-name (buffer-file-name)))))
4053 (regexp org-deadline-time-regexp)
4054 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4055 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4056 d2 diff pos pos1
4057 ee txt head)
4058 (goto-char (point-min))
4059 (while (re-search-forward regexp nil t)
4060 (setq pos (1- (match-beginning 1))
4061 d2 (time-to-days
4062 (org-time-string-to-time (match-string 1)))
4063 diff (- d2 d1))
4064 ;; When to show a deadline in the calendar:
4065 ;; If the expiration is within wdays warning time.
4066 ;; Past-due deadlines are only shown on the current date
4067 (if (and (< diff wdays) todayp (not (= diff 0)))
4068 (save-excursion
4069 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4070 (progn
4071 (goto-char (match-end 0))
4072 (setq pos1 (match-end 1))
4073 (setq head (buffer-substring-no-properties
4074 (point)
4075 (progn (skip-chars-forward "^\r\n")
4076 (point))))
4077 (if (string-match org-looking-at-done-regexp head)
4078 (setq txt nil)
4079 (setq txt (org-format-agenda-item
4080 (format "In %3d d.: " diff) head))))
4081 (setq txt org-agenda-no-heading-message))
4082 (when txt
4083 (add-text-properties
4084 0 (length txt)
4085 (append
4086 (list 'org-marker (org-agenda-new-marker pos)
4087 'org-hd-marker (org-agenda-new-marker pos1)
4088 'priority (+ (- 10 diff) (org-get-priority txt))
4089 'face (cond ((<= diff 0) 'org-warning-face)
4090 ((<= diff 5) 'org-scheduled-previously-face)
4091 (t nil))
4092 'undone-face (cond
4093 ((<= diff 0) 'org-warning-face)
4094 ((<= diff 5) 'org-scheduled-previously-face)
4095 (t nil))
4096 'done-face 'org-done-face)
4097 props)
4098 txt)
4099 (push txt ee)))))
4100 ee))
4101
4102 (defun org-agenda-get-scheduled ()
4103 "Return the scheduled information for agenda display."
4104 (let* ((props (list 'face 'org-scheduled-previously-face
4105 'undone-face 'org-scheduled-previously-face
4106 'done-face 'org-done-face
4107 'mouse-face 'highlight
4108 'keymap org-agenda-keymap
4109 'help-echo
4110 (format "mouse-2 or RET jump to org file %s"
4111 (abbreviate-file-name (buffer-file-name)))))
4112 (regexp org-scheduled-time-regexp)
4113 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4114 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4115 d2 diff pos pos1
4116 ee txt head)
4117 (goto-char (point-min))
4118 (while (re-search-forward regexp nil t)
4119 (setq pos (1- (match-beginning 1))
4120 d2 (time-to-days
4121 (org-time-string-to-time (match-string 1)))
4122 diff (- d2 d1))
4123 ;; When to show a scheduled item in the calendar:
4124 ;; If it is on or past the date.
4125 (if (and (< diff 0) todayp)
4126 (save-excursion
4127 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4128 (progn
4129 (goto-char (match-end 0))
4130 (setq pos1 (match-end 1))
4131 (setq head (buffer-substring-no-properties
4132 (point)
4133 (progn (skip-chars-forward "^\r\n") (point))))
4134 (if (string-match org-looking-at-done-regexp head)
4135 (setq txt nil)
4136 (setq txt (org-format-agenda-item
4137 (format "Sched.%2dx: " (- 1 diff)) head))))
4138 (setq txt org-agenda-no-heading-message))
4139 (when txt
4140 (add-text-properties
4141 0 (length txt)
4142 (append (list 'org-marker (org-agenda-new-marker pos)
4143 'org-hd-marker (org-agenda-new-marker pos1)
4144 'priority (+ (- 5 diff) (org-get-priority txt)))
4145 props) txt)
4146 (push txt ee)))))
4147 ee))
4148
4149 (defun org-agenda-get-blocks ()
4150 "Return the date-range information for agenda display."
4151 (let* ((props (list 'face nil
4152 'mouse-face 'highlight
4153 'keymap org-agenda-keymap
4154 'help-echo
4155 (format "mouse-2 or RET jump to org file %s"
4156 (abbreviate-file-name (buffer-file-name)))))
4157 (regexp org-tr-regexp)
4158 (d0 (calendar-absolute-from-gregorian date))
4159 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4160 (goto-char (point-min))
4161 (while (re-search-forward regexp nil t)
4162 (setq timestr (match-string 0)
4163 s1 (match-string 1)
4164 s2 (match-string 2)
4165 d1 (time-to-days (org-time-string-to-time s1))
4166 d2 (time-to-days (org-time-string-to-time s2)))
4167 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4168 ;; Only allow days between the limits, because the normal
4169 ;; date stamps will catch the limits.
4170 (save-excursion
4171 (setq marker (org-agenda-new-marker (point)))
4172 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4173 (progn
4174 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4175 (goto-char (match-end 1))
4176 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4177 (setq txt (org-format-agenda-item
4178 (format (if (= d1 d2) "" "(%d/%d): ")
4179 (1+ (- d0 d1)) (1+ (- d2 d1)))
4180 (match-string 1) nil (if (= d0 d1) timestr))))
4181 (setq txt org-agenda-no-heading-message))
4182 (add-text-properties
4183 0 (length txt) (append (list 'org-marker marker
4184 'org-hd-marker hdmarker
4185 'priority (org-get-priority txt))
4186 props)
4187 txt)
4188 (push txt ee)))
4189 (outline-next-heading))
4190 ;; Sort the entries by expiration date.
4191 (nreverse ee)))
4192
4193
4194
4195 (defconst org-plain-time-of-day-regexp
4196 (concat
4197 "\\(\\<[012]?[0-9]"
4198 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4199 "\\(--?"
4200 "\\(\\<[012]?[0-9]"
4201 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4202 "\\)?")
4203 "Regular expression to match a plain time or time range.
4204 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4205 groups carry important information:
4206 0 the full match
4207 1 the first time, range or not
4208 8 the second time, if it is a range.")
4209
4210 (defconst org-stamp-time-of-day-regexp
4211 (concat
4212 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4213 "\\([012][0-9]:[0-5][0-9]\\)>"
4214 "\\(--?"
4215 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4216 "Regular expression to match a timestamp time or time range.
4217 After a match, the following groups carry important information:
4218 0 the full match
4219 1 date plus weekday, for backreferencing to make sure both times on same day
4220 2 the first time, range or not
4221 4 the second time, if it is a range.")
4222
4223 (defvar org-prefix-has-time nil
4224 "A flag, set by `org-compile-prefix-format'.
4225 The flag is set if the currently compiled format contains a `%t'.")
4226
4227 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4228 "Format TXT to be inserted into the agenda buffer.
4229 In particular, it adds the prefix and corresponding text properties. EXTRA
4230 must be a string and replaces the `%s' specifier in the prefix format.
4231 CATEGORY (string, symbol or nil) may be used to overule the default
4232 category taken from local variable or file name. It will replace the `%c'
4233 specifier in the format. DOTIME, when non-nil, indicates that a
4234 time-of-day should be extracted from TXT for sorting of this entry, and for
4235 the `%t' specifier in the format. When DOTIME is a string, this string is
4236 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4237 only the correctly processes TXT should be returned - this is used by
4238 `org-agenda-change-all-lines'."
4239 (save-match-data
4240 ;; Diary entries sometimes have extra whitespace at the beginning
4241 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4242 (let* ((category (or category
4243 org-category
4244 (if (buffer-file-name)
4245 (file-name-sans-extension
4246 (file-name-nondirectory (buffer-file-name)))
4247 "")))
4248 time ;; needed for the eval of the prefix format
4249 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4250 (time-of-day (and dotime (org-get-time-of-day ts)))
4251 stamp plain s0 s1 s2 rtn)
4252 (when (and dotime time-of-day org-prefix-has-time)
4253 ;; Extract starting and ending time and move them to prefix
4254 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4255 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4256 (setq s0 (match-string 0 ts)
4257 s1 (match-string (if plain 1 2) ts)
4258 s2 (match-string (if plain 8 4) ts))
4259
4260 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4261 ;; them, we might want to remove them there to avoid duplication.
4262 ;; The user can turn this off with a variable.
4263 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4264 (string-match (concat (regexp-quote s0) " *") txt)
4265 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4266 (= (match-beginning 0) 0)
4267 t))
4268 (setq txt (replace-match "" nil nil txt))))
4269 ;; Normalize the time(s) to 24 hour
4270 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4271 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4272
4273 ;; Create the final string
4274 (if noprefix
4275 (setq rtn txt)
4276 ;; Prepare the variables needed in the eval of the compiled format
4277 (setq time (cond (s2 (concat s1 "-" s2))
4278 (s1 (concat s1 "......"))
4279 (t ""))
4280 extra (or extra "")
4281 category (if (symbolp category) (symbol-name category) category))
4282 ;; Evaluate the compiled format
4283 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4284
4285 ;; And finally add the text properties
4286 (add-text-properties
4287 0 (length rtn) (list 'category (downcase category)
4288 'prefix-length (- (length rtn) (length txt))
4289 'time-of-day time-of-day
4290 'dotime dotime)
4291 rtn)
4292 rtn)))
4293
4294 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4295 (catch 'exit
4296 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4297 ((and todayp (member 'today (car org-agenda-time-grid))))
4298 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4299 ((member 'weekly (car org-agenda-time-grid)))
4300 (t (throw 'exit list)))
4301 (let* ((have (delq nil (mapcar
4302 (lambda (x) (get-text-property 1 'time-of-day x))
4303 list)))
4304 (string (nth 1 org-agenda-time-grid))
4305 (gridtimes (nth 2 org-agenda-time-grid))
4306 (req (car org-agenda-time-grid))
4307 (remove (member 'remove-match req))
4308 new time)
4309 (if (and (member 'require-timed req) (not have))
4310 ;; don't show empty grid
4311 (throw 'exit list))
4312 (while (setq time (pop gridtimes))
4313 (unless (and remove (member time have))
4314 (setq time (int-to-string time))
4315 (push (org-format-agenda-item
4316 nil string "" ;; FIXME: put a category?
4317 (concat (substring time 0 -2) ":" (substring time -2)))
4318 new)
4319 (put-text-property
4320 1 (length (car new)) 'face 'org-time-grid-face (car new))))
4321 (if (member 'time-up org-agenda-sorting-strategy)
4322 (append new list)
4323 (append list new)))))
4324
4325 (defun org-compile-prefix-format (format)
4326 "Compile the prefix format into a Lisp form that can be evaluated.
4327 The resulting form is returned and stored in the variable
4328 `org-prefix-format-compiled'."
4329 (setq org-prefix-has-time nil)
4330 (let ((start 0) varform vars var (s format) c f opt)
4331 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4332 s start)
4333 (setq var (cdr (assoc (match-string 4 s)
4334 '(("c" . category) ("t" . time) ("s" . extra))))
4335 c (or (match-string 3 s) "")
4336 opt (match-beginning 1)
4337 start (1+ (match-beginning 0)))
4338 (if (equal var 'time) (setq org-prefix-has-time t))
4339 (setq f (concat "%" (match-string 2 s) "s"))
4340 (if opt
4341 (setq varform
4342 `(if (equal "" ,var)
4343 ""
4344 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4345 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4346 (setq s (replace-match "%s" t nil s))
4347 (push varform vars))
4348 (setq vars (nreverse vars))
4349 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4350
4351 (defun org-get-time-of-day (s &optional string)
4352 "Check string S for a time of day.
4353 If found, return it as a military time number between 0 and 2400.
4354 If not found, return nil.
4355 The optional STRING argument forces conversion into a 5 character wide string
4356 HH:MM."
4357 (save-match-data
4358 (when
4359 (or
4360 (string-match
4361 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4362 (string-match
4363 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4364 (let* ((t0 (+ (* 100
4365 (+ (string-to-number (match-string 1 s))
4366 (if (and (match-beginning 4)
4367 (equal (downcase (match-string 4 s)) "pm"))
4368 12 0)))
4369 (if (match-beginning 3)
4370 (string-to-number (match-string 3 s))
4371 0)))
4372 (t1 (concat " " (int-to-string t0))))
4373 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4374
4375 (defun org-finalize-agenda-entries (list)
4376 "Sort and concatenate the agenda items."
4377 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4378
4379 (defsubst org-cmp-priority (a b)
4380 "Compare the priorities of string a and b."
4381 (let ((pa (or (get-text-property 1 'priority a) 0))
4382 (pb (or (get-text-property 1 'priority b) 0)))
4383 (cond ((> pa pb) +1)
4384 ((< pa pb) -1)
4385 (t nil))))
4386
4387 (defsubst org-cmp-category (a b)
4388 "Compare the string values of categories of strings a and b."
4389 (let ((ca (or (get-text-property 1 'category a) ""))
4390 (cb (or (get-text-property 1 'category b) "")))
4391 (cond ((string-lessp ca cb) -1)
4392 ((string-lessp cb ca) +1)
4393 (t nil))))
4394
4395 (defsubst org-cmp-time (a b)
4396 "Compare the time-of-day values of strings a and b."
4397 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4398 (ta (or (get-text-property 1 'time-of-day a) def))
4399 (tb (or (get-text-property 1 'time-of-day b) def)))
4400 (cond ((< ta tb) -1)
4401 ((< tb ta) +1)
4402 (t nil))))
4403
4404 (defun org-entries-lessp (a b)
4405 "Predicate for sorting agenda entries."
4406 (let* ((time-up (org-cmp-time a b))
4407 (time-down (if time-up (- time-up) nil))
4408 (priority-up (org-cmp-priority a b))
4409 (priority-down (if priority-up (- priority-up) nil))
4410 (category-up (org-cmp-category a b))
4411 (category-down (if category-up (- category-up) nil))
4412 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4413 (cdr (assoc
4414 (eval (cons 'or org-agenda-sorting-strategy))
4415 '((-1 . t) (1 . nil) (nil . nil))))))
4416
4417 (defun org-agenda-show-priority ()
4418 "Show the priority of the current item.
4419 This priority is composed of the main priority given with the [#A] cookies,
4420 and by additional input from the age of a schedules or deadline entry."
4421 (interactive)
4422 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4423 (message "Priority is %d" (if pri pri -1000))))
4424
4425 (defun org-agenda-goto (&optional highlight)
4426 "Go to the Org-mode file which contains the item at point."
4427 (interactive)
4428 (let* ((marker (or (get-text-property (point) 'org-marker)
4429 (org-agenda-error)))
4430 (buffer (marker-buffer marker))
4431 (pos (marker-position marker)))
4432 (switch-to-buffer-other-window buffer)
4433 (widen)
4434 (goto-char pos)
4435 (when (eq major-mode 'org-mode)
4436 (org-show-hidden-entry)
4437 (save-excursion
4438 (and (outline-next-heading)
4439 (org-flag-heading nil)))) ; show the next heading
4440 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4441
4442 (defun org-agenda-switch-to ()
4443 "Go to the Org-mode file which contains the item at point."
4444 (interactive)
4445 (let* ((marker (or (get-text-property (point) 'org-marker)
4446 (org-agenda-error)))
4447 (buffer (marker-buffer marker))
4448 (pos (marker-position marker)))
4449 (switch-to-buffer buffer)
4450 (delete-other-windows)
4451 (widen)
4452 (goto-char pos)
4453 (when (eq major-mode 'org-mode)
4454 (org-show-hidden-entry)
4455 (save-excursion
4456 (and (outline-next-heading)
4457 (org-flag-heading nil)))))) ; show the next heading
4458
4459 (defun org-agenda-goto-mouse (ev)
4460 "Go to the Org-mode file which contains the item at the mouse click."
4461 (interactive "e")
4462 (mouse-set-point ev)
4463 (org-agenda-goto))
4464
4465 (defun org-agenda-show ()
4466 "Display the Org-mode file which contains the item at point."
4467 (interactive)
4468 (let ((win (selected-window)))
4469 (org-agenda-goto t)
4470 (select-window win)))
4471
4472 (defun org-agenda-recenter (arg)
4473 "Display the Org-mode file which contains the item at point and recenter."
4474 (interactive "P")
4475 (let ((win (selected-window)))
4476 (org-agenda-goto t)
4477 (recenter arg)
4478 (select-window win)))
4479
4480 (defun org-agenda-show-mouse (ev)
4481 "Display the Org-mode file which contains the item at the mouse click."
4482 (interactive "e")
4483 (mouse-set-point ev)
4484 (org-agenda-show))
4485
4486 (defun org-agenda-check-no-diary ()
4487 "Check if the entry is a diary link and abort if yes."
4488 (if (get-text-property (point) 'org-agenda-diary-link)
4489 (org-agenda-error)))
4490
4491 (defun org-agenda-error ()
4492 (error "Command not allowed in this line."))
4493
4494 (defvar org-last-heading-marker (make-marker)
4495 "Marker pointing to the headline that last changed its TODO state
4496 by a remote command from the agenda.")
4497
4498 (defun org-agenda-todo ()
4499 "Cycle TODO state of line at point, also in Org-mode file.
4500 This changes the line at point, all other lines in the agenda referring to
4501 the same tree node, and the headline of the tree node in the Org-mode file."
4502 (interactive)
4503 (org-agenda-check-no-diary)
4504 (let* ((col (current-column))
4505 (marker (or (get-text-property (point) 'org-marker)
4506 (org-agenda-error)))
4507 (buffer (marker-buffer marker))
4508 (pos (marker-position marker))
4509 (hdmarker (get-text-property (point) 'org-hd-marker))
4510 (buffer-read-only nil)
4511 newhead)
4512 (with-current-buffer buffer
4513 (widen)
4514 (goto-char pos)
4515 (org-show-hidden-entry)
4516 (save-excursion
4517 (and (outline-next-heading)
4518 (org-flag-heading nil))) ; show the next heading
4519 (org-todo)
4520 (forward-char 1)
4521 (setq newhead (org-get-heading))
4522 (save-excursion
4523 (org-back-to-heading)
4524 (move-marker org-last-heading-marker (point))))
4525 (beginning-of-line 1)
4526 (save-excursion
4527 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4528 (move-to-column col)))
4529
4530 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4531 "Change all lines in the agenda buffer which match hdmarker.
4532 The new content of the line will be NEWHEAD (as modified by
4533 `org-format-agenda-item'). HDMARKER is checked with
4534 `equal' against all `org-hd-marker' text properties in the file.
4535 If FIXFACE is non-nil, the face of each item is modified acording to
4536 the new TODO state."
4537 (let* (props m pl undone-face done-face finish new dotime)
4538 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4539 (save-excursion
4540 (goto-char (point-max))
4541 (beginning-of-line 1)
4542 (while (not finish)
4543 (setq finish (bobp))
4544 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4545 (equal m hdmarker))
4546 (setq props (text-properties-at (point))
4547 dotime (get-text-property (point) 'dotime)
4548 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4549 pl (get-text-property (point) 'prefix-length)
4550 undone-face (get-text-property (point) 'undone-face)
4551 done-face (get-text-property (point) 'done-face))
4552 (move-to-column pl)
4553 (if (looking-at ".*")
4554 (progn
4555 (replace-match new t t)
4556 (beginning-of-line 1)
4557 (add-text-properties (point-at-bol) (point-at-eol) props)
4558 (if fixface
4559 (add-text-properties
4560 (point-at-bol) (point-at-eol)
4561 (list 'face
4562 (if org-last-todo-state-is-todo
4563 undone-face done-face))))
4564 (beginning-of-line 1))
4565 (error "Line update did not work")))
4566 (beginning-of-line 0)))))
4567
4568 (defun org-agenda-priority-up ()
4569 "Increase the priority of line at point, also in Org-mode file."
4570 (interactive)
4571 (org-agenda-priority 'up))
4572
4573 (defun org-agenda-priority-down ()
4574 "Decrease the priority of line at point, also in Org-mode file."
4575 (interactive)
4576 (org-agenda-priority 'down))
4577
4578 (defun org-agenda-priority (&optional force-direction)
4579 "Set the priority of line at point, also in Org-mode file.
4580 This changes the line at point, all other lines in the agenda referring to
4581 the same tree node, and the headline of the tree node in the Org-mode file."
4582 (interactive)
4583 (org-agenda-check-no-diary)
4584 (let* ((marker (or (get-text-property (point) 'org-marker)
4585 (org-agenda-error)))
4586 (buffer (marker-buffer marker))
4587 (pos (marker-position marker))
4588 (hdmarker (get-text-property (point) 'org-hd-marker))
4589 (buffer-read-only nil)
4590 newhead)
4591 (with-current-buffer buffer
4592 (widen)
4593 (goto-char pos)
4594 (org-show-hidden-entry)
4595 (save-excursion
4596 (and (outline-next-heading)
4597 (org-flag-heading nil))) ; show the next heading
4598 (funcall 'org-priority force-direction)
4599 (end-of-line 1)
4600 (setq newhead (org-get-heading)))
4601 (org-agenda-change-all-lines newhead hdmarker)
4602 (beginning-of-line 1)))
4603
4604 (defun org-agenda-date-later (arg &optional what)
4605 "Change the date of this item to one day later."
4606 (interactive "p")
4607 (org-agenda-check-no-diary)
4608 (let* ((marker (or (get-text-property (point) 'org-marker)
4609 (org-agenda-error)))
4610 (buffer (marker-buffer marker))
4611 (pos (marker-position marker)))
4612 (with-current-buffer buffer
4613 (widen)
4614 (goto-char pos)
4615 (if (not (org-at-timestamp-p))
4616 (error "Cannot find time stamp"))
4617 (org-timestamp-change arg (or what 'day))
4618 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4619
4620 (defun org-agenda-date-earlier (arg &optional what)
4621 "Change the date of this item to one day earlier."
4622 (interactive "p")
4623 (org-agenda-date-later (- arg) what))
4624
4625 (defun org-agenda-date-prompt (arg)
4626 "Change the date of this item. Date is prompted for, with default today.
4627 The prefix ARG is passed to the `org-time-stamp' command and can therefore
4628 be used to request time specification in the time stamp."
4629 (interactive "P")
4630 (org-agenda-check-no-diary)
4631 (let* ((marker (or (get-text-property (point) 'org-marker)
4632 (org-agenda-error)))
4633 (buffer (marker-buffer marker))
4634 (pos (marker-position marker)))
4635 (with-current-buffer buffer
4636 (widen)
4637 (goto-char pos)
4638 (if (not (org-at-timestamp-p))
4639 (error "Cannot find time stamp"))
4640 (org-time-stamp arg)
4641 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4642
4643 (defun org-get-heading ()
4644 "Return the heading of the current entry, without the stars."
4645 (save-excursion
4646 (if (and (re-search-backward "[\r\n]\\*" nil t)
4647 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
4648 (match-string 1)
4649 "")))
4650
4651 (defun org-agenda-diary-entry ()
4652 "Make a diary entry, like the `i' command from the calendar.
4653 All the standard commands work: block, weekly etc"
4654 (interactive)
4655 (require 'diary-lib)
4656 (let* ((char (progn
4657 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
4658 (read-char-exclusive)))
4659 (cmd (cdr (assoc char
4660 '((?d . insert-diary-entry)
4661 (?w . insert-weekly-diary-entry)
4662 (?m . insert-monthly-diary-entry)
4663 (?y . insert-yearly-diary-entry)
4664 (?a . insert-anniversary-diary-entry)
4665 (?b . insert-block-diary-entry)
4666 (?c . insert-cyclic-diary-entry)))))
4667 (oldf (symbol-function 'calendar-cursor-to-date))
4668 (point (point))
4669 (mark (or (mark t) (point))))
4670 (unless cmd
4671 (error "No command associated with <%c>" char))
4672 (unless (and (get-text-property point 'day)
4673 (or (not (equal ?b char))
4674 (get-text-property mark 'day)))
4675 (error "Don't know which date to use for diary entry"))
4676 ;; We implement this by hacking the `calendar-cursor-to-date' function
4677 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
4678 (let ((calendar-mark-ring
4679 (list (calendar-gregorian-from-absolute
4680 (or (get-text-property mark 'day)
4681 (get-text-property point 'day))))))
4682 (unwind-protect
4683 (progn
4684 (fset 'calendar-cursor-to-date
4685 (lambda (&optional error)
4686 (calendar-gregorian-from-absolute
4687 (get-text-property point 'day))))
4688 (call-interactively cmd))
4689 (fset 'calendar-cursor-to-date oldf)))))
4690
4691
4692 (defun org-agenda-execute-calendar-command (cmd)
4693 "Execute a calendar command from the agenda, with the date associated to
4694 the cursor position."
4695 (require 'diary-lib)
4696 (unless (get-text-property (point) 'day)
4697 (error "Don't know which date to use for calendar command"))
4698 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
4699 (point (point))
4700 (date (calendar-gregorian-from-absolute
4701 (get-text-property point 'day)))
4702 (displayed-day (extract-calendar-day date))
4703 (displayed-month (extract-calendar-month date))
4704 (displayed-year (extract-calendar-year date)))
4705 (unwind-protect
4706 (progn
4707 (fset 'calendar-cursor-to-date
4708 (lambda (&optional error)
4709 (calendar-gregorian-from-absolute
4710 (get-text-property point 'day))))
4711 (call-interactively cmd))
4712 (fset 'calendar-cursor-to-date oldf))))
4713
4714 (defun org-agenda-phases-of-moon ()
4715 "Display the phases of the moon for the 3 months around the cursor date."
4716 (interactive)
4717 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
4718
4719 (defun org-agenda-holidays ()
4720 "Display the holidays for the 3 months around the cursor date."
4721 (interactive)
4722 (org-agenda-execute-calendar-command 'list-calendar-holidays))
4723
4724 (defun org-agenda-sunrise-sunset (arg)
4725 "Display sunrise and sunset for the cursor date.
4726 Latitude and longitude can be specified with the variables
4727 `calendar-latitude' and `calendar-longitude'. When called with prefix
4728 argument, latitude and longitude will be prompted for."
4729 (interactive "P")
4730 (let ((calendar-longitude (if arg nil calendar-longitude))
4731 (calendar-latitude (if arg nil calendar-latitude))
4732 (calendar-location-name
4733 (if arg "the given coordinates" calendar-location-name)))
4734 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
4735
4736 (defun org-agenda-goto-calendar ()
4737 "Open the Emacs calendar with the date at the cursor."
4738 (interactive)
4739 (let* ((day (or (get-text-property (point) 'day)
4740 (error "Don't know which date to open in calendar")))
4741 (date (calendar-gregorian-from-absolute day)))
4742 (calendar)
4743 (calendar-goto-date date)))
4744
4745 (defun org-calendar-goto-agenda ()
4746 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
4747 This is a command that has to be installed in `calendar-mode-map'."
4748 (interactive)
4749 (org-agenda nil (calendar-absolute-from-gregorian
4750 (calendar-cursor-to-date))))
4751
4752 (defun org-agenda-convert-date ()
4753 (interactive)
4754 (let ((day (get-text-property (point) 'day))
4755 date s)
4756 (unless day
4757 (error "Don't know which date to convert"))
4758 (setq date (calendar-gregorian-from-absolute day))
4759 (setq s (concat
4760 "Gregorian: " (calendar-date-string date) "\n"
4761 "ISO: " (calendar-iso-date-string date) "\n"
4762 "Day of Yr: " (calendar-day-of-year-string date) "\n"
4763 "Julian: " (calendar-julian-date-string date) "\n"
4764 "Astron. JD: " (calendar-astro-date-string date)
4765 " (Julian date number at noon UTC)\n"
4766 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
4767 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
4768 "French: " (calendar-french-date-string date) "\n"
4769 "Mayan: " (calendar-mayan-date-string date) "\n"
4770 "Coptic: " (calendar-coptic-date-string date) "\n"
4771 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
4772 "Persian: " (calendar-persian-date-string date) "\n"
4773 "Chinese: " (calendar-chinese-date-string date) "\n"))
4774 (with-output-to-temp-buffer "*Dates*"
4775 (princ s))
4776 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
4777
4778 ;;; Link Stuff
4779
4780 (defun org-find-file-at-mouse (ev)
4781 "Open file link or URL at mouse."
4782 (interactive "e")
4783 (mouse-set-point ev)
4784 (org-open-at-point 'in-emacs))
4785
4786 (defun org-open-at-mouse (ev)
4787 "Open file link or URL at mouse."
4788 (interactive "e")
4789 (mouse-set-point ev)
4790 (org-open-at-point))
4791
4792 (defun org-open-at-point (&optional in-emacs)
4793 "Open link at or after point.
4794 If there is no link at point, this function will search forward up to
4795 the end of the current subtree.
4796 Normally, files will be opened by an appropriate application. If the
4797 optional argument IN-EMACS is non-nil, Emacs will visit the file."
4798 (interactive "P")
4799 (if (org-at-timestamp-p)
4800 (org-agenda nil (time-to-days (org-time-string-to-time
4801 (substring (match-string 1) 0 10)))
4802 1)
4803 (let (type path line (pos (point)))
4804 (save-excursion
4805 (skip-chars-backward
4806 (if org-allow-space-in-links "^\t\n\r" "^ \t\n\r"))
4807 (if (re-search-forward
4808 org-link-regexp
4809 (save-excursion
4810 (condition-case nil
4811 (progn (outline-end-of-subtree) (max pos (point)))
4812 (error (end-of-line 1) (point))))
4813 t)
4814 (setq type (match-string 1)
4815 path (match-string 2)))
4816 (unless path
4817 (error "No link found."))
4818 ;; Remove any trailing spaces in path
4819 (if (string-match " +\\'" path)
4820 (setq path (replace-match "" t t path)))
4821
4822 (cond
4823
4824 ((string= type "file")
4825 (if (string-match ":\\([0-9]+\\)\\'" path)
4826 (setq line (string-to-number (match-string 1 path))
4827 path (substring path 0 (match-beginning 0))))
4828 (org-open-file path in-emacs line))
4829
4830 ((string= type "news")
4831 (org-follow-gnus-link path))
4832
4833 ((string= type "bbdb")
4834 (org-follow-bbdb-link path))
4835
4836 ((string= type "gnus")
4837 (let (group article)
4838 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4839 (error "Error in Gnus link"))
4840 (setq group (match-string 1 path)
4841 article (match-string 3 path))
4842 (org-follow-gnus-link group article)))
4843
4844 ((string= type "vm")
4845 (let (folder article)
4846 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4847 (error "Error in VM link"))
4848 (setq folder (match-string 1 path)
4849 article (match-string 3 path))
4850 ;; in-emacs is the prefix arg, will be interpreted as read-only
4851 (org-follow-vm-link folder article in-emacs)))
4852
4853 ((string= type "wl")
4854 (let (folder article)
4855 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4856 (error "Error in Wanderlust link"))
4857 (setq folder (match-string 1 path)
4858 article (match-string 3 path))
4859 (org-follow-wl-link folder article)))
4860
4861 ((string= type "rmail")
4862 (let (folder article)
4863 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4864 (error "Error in RMAIL link"))
4865 (setq folder (match-string 1 path)
4866 article (match-string 3 path))
4867 (org-follow-rmail-link folder article)))
4868
4869 ((string= type "shell")
4870 (let ((cmd path))
4871 (if (or (not org-confirm-shell-links)
4872 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
4873 (shell-command cmd)
4874 (error "Abort"))))
4875
4876 (t
4877 (browse-url-at-point)))))))
4878
4879 (defun org-follow-bbdb-link (name)
4880 "Follow a BBDB link to NAME."
4881 (require 'bbdb)
4882 (let ((inhibit-redisplay t))
4883 (catch 'exit
4884 ;; Exact match on name
4885 (bbdb-name (concat "\\`" name "\\'") nil)
4886 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4887 ;; Exact match on name
4888 (bbdb-company (concat "\\`" name "\\'") nil)
4889 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4890 ;; Partial match on name
4891 (bbdb-name name nil)
4892 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4893 ;; Partial match on company
4894 (bbdb-company name nil)
4895 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
4896 ;; General match including network address and notes
4897 (bbdb name nil)
4898 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
4899 (delete-window (get-buffer-window "*BBDB*"))
4900 (error "No matching BBDB record")))))
4901
4902 (defun org-follow-gnus-link (&optional group article)
4903 "Follow a Gnus link to GROUP and ARTICLE."
4904 (require 'gnus)
4905 (funcall (cdr (assq 'gnus org-link-frame-setup)))
4906 (if group (gnus-fetch-group group))
4907 (if article
4908 (or (gnus-summary-goto-article article nil 'force)
4909 (if (fboundp 'gnus-summary-insert-cached-articles)
4910 (progn
4911 (gnus-summary-insert-cached-articles)
4912 (gnus-summary-goto-article article nil 'force))
4913 (message "Message could not be found.")))))
4914
4915 (defun org-follow-vm-link (&optional folder article readonly)
4916 "Follow a VM link to FOLDER and ARTICLE."
4917 (require 'vm)
4918 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
4919 ;; ange-ftp or efs or tramp access
4920 (let ((user (or (match-string 1 folder) (user-login-name)))
4921 (host (match-string 2 folder))
4922 (file (match-string 3 folder)))
4923 (cond
4924 ((featurep 'tramp)
4925 ;; use tramp to access the file
4926 (if org-xemacs-p
4927 (setq folder (format "[%s@%s]%s" user host file))
4928 (setq folder (format "/%s@%s:%s" user host file))))
4929 (t
4930 ;; use ange-ftp or efs
4931 (require (if org-xemacs-p 'efs 'ange-ftp))
4932 (setq folder (format "/%s@%s:%s" user host file))))))
4933 (when folder
4934 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
4935 (sit-for 0.1)
4936 (when article
4937 (vm-select-folder-buffer)
4938 (widen)
4939 (let ((case-fold-search t))
4940 (goto-char (point-min))
4941 (if (not (re-search-forward
4942 (concat "^" "message-id: *" (regexp-quote article))))
4943 (error "Could not find the specified message in this folder"))
4944 (vm-isearch-update)
4945 (vm-isearch-narrow)
4946 (vm-beginning-of-message)
4947 (vm-summarize)))))
4948
4949 (defun org-follow-wl-link (folder article)
4950 "Follow a Wanderlust link to FOLDER and ARTICLE."
4951 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
4952 (if article (wl-summary-jump-to-msg-by-message-id article))
4953 (wl-summary-redisplay))
4954
4955 (defun org-follow-rmail-link (folder article)
4956 "Follow an RMAIL link to FOLDER and ARTICLE."
4957 (let (message-number)
4958 (save-excursion
4959 (save-window-excursion
4960 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4961 (setq message-number
4962 (save-restriction
4963 (widen)
4964 (goto-char (point-max))
4965 (if (re-search-backward
4966 (concat "^Message-ID:\\s-+" (regexp-quote
4967 (or article "")))
4968 nil t)
4969 (rmail-what-message))))))
4970 (if message-number
4971 (progn
4972 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4973 (rmail-show-message message-number)
4974 message-number)
4975 (error "Message not found"))))
4976
4977 (defun org-open-file (path &optional in-emacs line)
4978 "Open the file at PATH.
4979 First, this expands any special file name abbreviations. Then the
4980 configuration variable `org-file-apps' is checked if it contains an
4981 entry for this file type, and if yes, the corresponding command is launched.
4982 If no application is found, Emacs simply visits the file.
4983 With optional argument IN-EMACS, Emacs will visit the file.
4984 If the file does not exist, an error is thrown."
4985 (let* ((file (convert-standard-filename (org-expand-file-name path)))
4986 (dfile (downcase file))
4987 ext cmd apps)
4988 (if (and (not (file-exists-p file))
4989 (not org-open-non-existing-files))
4990 (error "No such file: %s" file))
4991 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
4992 (setq ext (match-string 1 dfile))
4993 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
4994 (setq ext (match-string 1 dfile))))
4995 (setq apps (append org-file-apps (org-default-apps)))
4996 (if in-emacs
4997 (setq cmd 'emacs)
4998 (setq cmd (or (cdr (assoc ext apps))
4999 (cdr (assoc t apps)))))
5000 (cond
5001 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5002 (setq cmd (format cmd file))
5003 (save-window-excursion
5004 (shell-command (concat cmd " & &"))))
5005 ((or (stringp cmd)
5006 (eq cmd 'emacs))
5007 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5008 (if line (goto-line line)))
5009 ((consp cmd)
5010 (eval cmd))
5011 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5012
5013 (defun org-default-apps ()
5014 "Return the default applications for this operating system."
5015 (cond
5016 ((eq system-type 'darwin)
5017 org-file-apps-defaults-macosx)
5018 ((eq system-type 'windows-nt)
5019 org-file-apps-defaults-windowsnt)
5020 ((eq system-type 'linux)
5021 org-file-apps-defaults-linux)
5022 (t org-file-apps-defaults-linux)))
5023
5024 (defun org-expand-file-name (path)
5025 "Replace special path abbreviations and expand the file name."
5026 (expand-file-name path))
5027
5028
5029 (defvar org-insert-link-history nil
5030 "Minibuffer history for links inserted with `org-insert-link'.")
5031
5032 (defvar org-stored-links nil
5033 "Contains the links stored with `org-store-link'.")
5034
5035 ;;;###autoload
5036 (defun org-store-link (arg)
5037 "\\<org-mode-map>Store an org-link to the current location.
5038 This link can later be inserted into an org-buffer with
5039 \\[org-insert-link].
5040 For some link types, a prefix arg is interpreted:
5041 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5042 For file links, arg negates `org-line-numbers-in-file-links'."
5043 (interactive "P")
5044 (let (link cpltxt)
5045 (cond
5046
5047 ((eq major-mode 'bbdb-mode)
5048 (setq link (concat "bbdb:"
5049 (or (bbdb-record-name (bbdb-current-record))
5050 (bbdb-record-company (bbdb-current-record))))))
5051
5052 ((eq major-mode 'calendar-mode)
5053 (let ((cd (calendar-cursor-to-date)))
5054 (setq link
5055 (format-time-string
5056 (car org-time-stamp-formats)
5057 (apply 'encode-time
5058 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5059 nil nil nil))))))
5060
5061 ((or (eq major-mode 'vm-summary-mode)
5062 (eq major-mode 'vm-presentation-mode))
5063 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5064 (vm-follow-summary-cursor)
5065 (save-excursion
5066 (vm-select-folder-buffer)
5067 (let* ((message (car vm-message-pointer))
5068 (folder (buffer-file-name))
5069 (subject (vm-su-subject message))
5070 (author (vm-su-full-name message))
5071 (message-id (vm-su-message-id message)))
5072 (setq folder (abbreviate-file-name folder))
5073 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5074 folder)
5075 (setq folder (replace-match "" t t folder)))
5076 (setq cpltxt (concat author " on: " subject))
5077 (setq link (concat cpltxt "\n " "vm:" folder
5078 "#" message-id)))))
5079
5080 ((eq major-mode 'wl-summary-mode)
5081 (let* ((msgnum (wl-summary-message-number))
5082 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5083 msgnum 'message-id))
5084 (wl-message-entity (elmo-msgdb-overview-get-entity
5085 msgnum (wl-summary-buffer-msgdb)))
5086 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5087 (subject "???")) ; FIXME: How to get subject of email?
5088 (setq cpltxt (concat author " on: " subject))
5089 (setq link (concat cpltxt "\n " "wl:" wl-summary-buffer-folder-name
5090 "#" message-id))))
5091
5092 ((eq major-mode 'rmail-mode)
5093 (save-excursion
5094 (save-restriction
5095 (rmail-narrow-to-non-pruned-header)
5096 (let ((folder (buffer-file-name))
5097 (message-id (mail-fetch-field "message-id"))
5098 (author (mail-fetch-field "from"))
5099 (subject (mail-fetch-field "subject")))
5100 (setq cpltxt (concat author " on: " subject))
5101 (setq link (concat cpltxt "\n " "rmail:" folder
5102 "#" message-id))))))
5103
5104 ((eq major-mode 'gnus-group-mode)
5105 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5106 (gnus-group-group-name)) ; version
5107 ((fboundp 'gnus-group-name)
5108 (gnus-group-name))
5109 (t "???"))))
5110 (setq link (concat
5111 (if (org-xor arg org-usenet-links-prefer-google)
5112 "http://groups.google.com/groups?group="
5113 "gnus:")
5114 group))))
5115
5116 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5117 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5118 (gnus-summary-beginning-of-article)
5119 (let* ((group (car gnus-article-current))
5120 (article (cdr gnus-article-current))
5121 (header (gnus-summary-article-header article))
5122 (author (mail-header-from header))
5123 (message-id (mail-header-id header))
5124 (date (mail-header-date header))
5125 (subject (gnus-summary-subject-string)))
5126 (setq cpltxt (concat author " on: " subject))
5127 (if (org-xor arg org-usenet-links-prefer-google)
5128 (setq link
5129 (concat
5130 cpltxt "\n "
5131 (format "http://groups.google.com/groups?as_umsgid=%s"
5132 (org-fixup-message-id-for-http message-id))))
5133 (setq link (concat cpltxt "\n" "gnus:" group
5134 "#" (number-to-string article))))))
5135
5136 ((eq major-mode 'w3-mode)
5137 (setq link (url-view-url t)))
5138 ((eq major-mode 'w3m-mode)
5139 (setq link w3m-current-url))
5140
5141 ((buffer-file-name)
5142 ;; Just link to this file here.
5143 (setq link (concat "file:"
5144 (abbreviate-file-name (buffer-file-name))))
5145 ;; Add the line number?
5146 (if (org-xor org-line-numbers-in-file-links arg)
5147 (setq link
5148 (concat link
5149 ":" (int-to-string
5150 (+ (if (bolp) 1 0) (count-lines
5151 (point-min) (point))))))))
5152 ((interactive-p)
5153 (error "Cannot link to a buffer which is not visiting a file"))
5154 (t (setq link nil)))
5155
5156 (if (and (interactive-p) link)
5157 (progn
5158 (setq org-stored-links
5159 (cons (cons (or cpltxt link) link) org-stored-links))
5160 (message "Stored: %s" (or cpltxt link)))
5161 link)))
5162
5163 (defun org-xor (a b)
5164 "Exclusive or."
5165 (if a (not b) b))
5166
5167 (defun org-get-header (header)
5168 "Find a header field in the current buffer."
5169 (save-excursion
5170 (goto-char (point-min))
5171 (let ((case-fold-search t) s)
5172 (cond
5173 ((eq header 'from)
5174 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5175 (setq s (match-string 1)))
5176 (while (string-match "\"" s)
5177 (setq s (replace-match "" t t s)))
5178 (if (string-match "[<(].*" s)
5179 (setq s (replace-match "" t t s))))
5180 ((eq header 'message-id)
5181 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5182 (setq s (match-string 1))))
5183 ((eq header 'subject)
5184 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5185 (setq s (match-string 1)))))
5186 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5187 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5188 s)))
5189
5190
5191 (defun org-fixup-message-id-for-http (s)
5192 "Replace special characters in a message id, so it can be used in an http query."
5193 (while (string-match "<" s)
5194 (setq s (replace-match "%3C" t t s)))
5195 (while (string-match ">" s)
5196 (setq s (replace-match "%3E" t t s)))
5197 (while (string-match "@" s)
5198 (setq s (replace-match "%40" t t s)))
5199 s)
5200
5201 (defun org-insert-link (&optional complete-file)
5202 "Insert a link. At the prompt, enter the link.
5203
5204 Completion can be used to select a link previously stored with
5205 `org-store-link'. When the empty string is entered (i.e. if you just
5206 press RET at the prompt), the link defaults to the most recently
5207 stored link.
5208
5209 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5210 selected using completion. The path to the file will be relative to
5211 the current directory if the file is in the current directory or a
5212 subdirectory. Otherwise, the link will be the absolute path as
5213 completed in the minibuffer (i.e. normally ~/path/to/file).
5214
5215 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5216 is in the current directory or below."
5217 (interactive "P")
5218 (let ((link (if complete-file
5219 (read-file-name "File: ")
5220 (completing-read
5221 "Link: " org-stored-links nil nil nil
5222 org-insert-link-history
5223 (or (car (car org-stored-links))))))
5224 linktxt matched)
5225 (if (or (not link) (equal link ""))
5226 (error "No links available"))
5227 (if complete-file
5228 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5229 (cond
5230 ((equal complete-file '(16))
5231 (insert "file:" (abbreviate-file-name (expand-file-name link))))
5232 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5233 (expand-file-name link))
5234 (insert "file:" (match-string 1 (expand-file-name link))))
5235 (t (insert "file:" link))))
5236 (setq linktxt (cdr (assoc link org-stored-links)))
5237 (if (not org-keep-stored-link-after-insertion)
5238 (setq org-stored-links (delq (assoc link org-stored-links)
5239 org-stored-links)))
5240 (let ((lines (org-split-string (or linktxt link) "\n")))
5241 (insert (car lines))
5242 (setq matched (string-match org-link-regexp (car lines)))
5243 (setq lines (cdr lines))
5244 (while lines
5245 (insert "\n")
5246 (if (save-excursion
5247 (beginning-of-line 0)
5248 (looking-at "[ \t]+\\S-"))
5249 (indent-relative))
5250 (setq matched (or matched
5251 (string-match org-link-regexp (car lines))))
5252 (insert (car lines))
5253 (setq lines (cdr lines))))
5254 (unless matched
5255 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5256
5257 ;;; Hooks for remember.el
5258 ;;;###autoload
5259 (defun org-remember-annotation ()
5260 "Return a link to the current location as an annotation for remember.el.
5261 If you are using Org-mode files as target for data storage with
5262 remember.el, then the annotations should include a link compatible with the
5263 conventions in Org-mode. This function returns such a link."
5264 (org-store-link nil))
5265
5266 (defconst org-remember-help
5267 "Select a destination location for the note.
5268 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5269 RET at beg-of-buf -> Append to file as level 2 headline
5270 RET on headline -> Store as sublevel entry to current headline
5271 <left>/<right> -> before/after current headline, same headings level")
5272
5273 ;;;###autoload
5274 (defun org-remember-handler ()
5275 "Store stuff from remember.el into an org file.
5276 First prompts for an org file. If the user just presses return, the value
5277 of `org-default-notes-file' is used.
5278 Then the command offers the headings tree of the selected file in order to
5279 file the text at a specific location.
5280 You can either immediately press RET to get the note appended to the
5281 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5282 find a better place. Then press RET or <left> or <right> in insert the note.
5283
5284 Key Cursor position Note gets inserted
5285 -----------------------------------------------------------------------------
5286 RET buffer-start as level 2 heading at end of file
5287 RET on headline as sublevel of the heading at cursor
5288 RET no heading at cursor position, level taken from context.
5289 Or use prefix arg to specify level manually.
5290 <left> on headline as same level, before current heading
5291 <right> on headline as same level, after current heading
5292
5293 So the fastest way to store the note is to press RET RET to append it to
5294 the default file. This way your current train of thought is not
5295 interrupted, in accordance with the principles of remember.el. But with
5296 little extra effort, you can push it directly to the correct location.
5297
5298 Before being stored away, the function ensures that the text has a
5299 headline, i.e. a first line that starts with a \"*\". If not, a headline
5300 is constructed from the current date and some additional data.
5301
5302 If the variable `org-adapt-indentation' is non-nil, the entire text is
5303 also indented so that it starts in the same column as the headline
5304 \(i.e. after the stars).
5305
5306 See also the variable `org-reverse-note-order'."
5307 (catch 'quit
5308 (let* ((txt (buffer-substring (point-min) (point-max)))
5309 (fastp current-prefix-arg)
5310 (file (if fastp org-default-notes-file (org-get-org-file)))
5311 (visiting (find-buffer-visiting file))
5312 (org-startup-with-deadline-check nil)
5313 (org-startup-folded nil)
5314 spos level indent reversed)
5315 ;; Modify text so that it becomes a nice subtree which can be inserted
5316 ;; into an org tree.
5317 (let* ((lines (split-string txt "\n"))
5318 (first (car lines))
5319 (lines (cdr lines)))
5320 (if (string-match "^\\*+" first)
5321 ;; Is already a headline
5322 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5323 -1) ?\ ))
5324 ;; We need to add a headline: Use time and first buffer line
5325 (setq lines (cons first lines)
5326 first (concat "* " (current-time-string)
5327 " (" (remember-buffer-desc) ")")
5328 indent " "))
5329 (if org-adapt-indentation
5330 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5331 (setq txt (concat first "\n"
5332 (mapconcat 'identity lines "\n"))))
5333 ;; Find the file
5334 (if (not visiting)
5335 (find-file-noselect file))
5336 (with-current-buffer (get-file-buffer file)
5337 (setq reversed (org-notes-order-reversed-p))
5338 (save-excursion
5339 (save-restriction
5340 (widen)
5341 ;; Ask the User for a location
5342 (setq spos (if fastp 1 (org-get-location
5343 (current-buffer)
5344 org-remember-help)))
5345 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5346 ; not handle this note
5347 (goto-char spos)
5348 (cond ((bobp)
5349 ;; Put it at the start or end, as level 2
5350 (save-restriction
5351 (widen)
5352 (goto-char (if reversed (point-min) (point-max)))
5353 (if (not (bolp)) (newline))
5354 (org-paste-subtree (or current-prefix-arg 2) txt)))
5355 ((and (org-on-heading-p nil) (not current-prefix-arg))
5356 ;; Put it below this entry, at the beg/end of the subtree
5357 (org-back-to-heading)
5358 (setq level (outline-level))
5359 (if reversed
5360 (outline-end-of-heading)
5361 (outline-end-of-subtree))
5362 (if (not (bolp)) (newline))
5363 (beginning-of-line 1)
5364 (org-paste-subtree (1+ level) txt))
5365 (t
5366 ;; Put it right there, with automatic level determined by
5367 ;; org-paste-subtree or from prefix arg
5368 (org-paste-subtree current-prefix-arg txt)))
5369 (when remember-save-after-remembering
5370 (save-buffer)
5371 (if (not visiting) (kill-buffer (current-buffer)))))))))
5372 t) ;; return t to indicate that we took care of this note.
5373
5374 (defun org-get-org-file ()
5375 "Read a filename, with default directory `org-directory'."
5376 (let ((default (or org-default-notes-file remember-data-file)))
5377 (read-file-name (format "File name [%s]: " default)
5378 (file-name-as-directory org-directory)
5379 default)))
5380
5381 (defun org-notes-order-reversed-p ()
5382 "Check if the current file should receive notes in reversed order."
5383 (cond
5384 ((not org-reverse-note-order) nil)
5385 ((eq t org-reverse-note-order) t)
5386 ((not (listp org-reverse-note-order)) nil)
5387 (t (catch 'exit
5388 (let ((all org-reverse-note-order)
5389 entry)
5390 (while (setq entry (pop all))
5391 (if (string-match (car entry) (buffer-file-name))
5392 (throw 'exit (cdr entry))))
5393 nil)))))
5394
5395 ;;; Tables
5396
5397 ;; Watch out: Here we are talking about two different kind of tables.
5398 ;; Most of the code is for the tables created with the Org-mode table editor.
5399 ;; Sometimes, we talk about tables created and edited with the table.el
5400 ;; Emacs package. We call the former org-type tables, and the latter
5401 ;; table.el-type tables.
5402
5403
5404 (defun org-before-change-function (beg end)
5405 "Every change indicates that a table might need an update."
5406 (setq org-table-may-need-update t))
5407
5408 (defconst org-table-line-regexp "^[ \t]*|"
5409 "Detects an org-type table line.")
5410 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5411 "Detects an org-type table line.")
5412 (defconst org-table-hline-regexp "^[ \t]*|-"
5413 "Detects an org-type table hline.")
5414 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5415 "Detects a table-type table hline.")
5416 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5417 "Detects an org-type or table-type table.")
5418 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5419 "Searching from within a table (any type) this finds the first line
5420 outside the table.")
5421 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5422 "Searching from within a table (any type) this finds the first line
5423 outside the table.")
5424
5425 (defun org-table-create-with-table.el ()
5426 "Use the table.el package to insert a new table.
5427 If there is already a table at point, convert between Org-mode tables
5428 and table.el tables."
5429 (interactive)
5430 (require 'table)
5431 (cond
5432 ((org-at-table.el-p)
5433 (if (y-or-n-p "Convert table to Org-mode table? ")
5434 (org-table-convert)))
5435 ((org-at-table-p)
5436 (if (y-or-n-p "Convert table to table.el table? ")
5437 (org-table-convert)))
5438 (t (call-interactively 'table-insert))))
5439
5440 (defun org-table-create (&optional size)
5441 "Query for a size and insert a table skeleton.
5442 SIZE is a string Columns x Rows like for example \"3x2\"."
5443 (interactive "P")
5444 (unless size
5445 (setq size (read-string
5446 (concat "Table size Columns x Rows [e.g. "
5447 org-table-default-size "]: ")
5448 "" nil org-table-default-size)))
5449
5450 (let* ((pos (point))
5451 (indent (make-string (current-column) ?\ ))
5452 (split (org-split-string size " *x *"))
5453 (rows (string-to-number (nth 1 split)))
5454 (columns (string-to-number (car split)))
5455 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5456 "\n")))
5457 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5458 (point-at-bol) (point)))
5459 (beginning-of-line 1)
5460 (newline))
5461 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5462 (dotimes (i rows) (insert line))
5463 (goto-char pos)
5464 (if (> rows 1)
5465 ;; Insert a hline after the first row.
5466 (progn
5467 (end-of-line 1)
5468 (insert "\n|-")
5469 (goto-char pos)))
5470 (org-table-align)))
5471
5472 (defun org-table-convert-region (beg0 end0 nspace)
5473 "Convert region to a table.
5474 The region goes from BEG0 to END0, but these borders will be moved
5475 slightly, to make sure a beginning of line in the first line is included.
5476 When NSPACE is non-nil, it indicates the minimum number of spaces that
5477 separate columns (default: just one space)"
5478 (let* ((beg (min beg0 end0))
5479 (end (max beg0 end0))
5480 (tabsep t)
5481 re)
5482 (goto-char beg)
5483 (beginning-of-line 1)
5484 (setq beg (move-marker (make-marker) (point)))
5485 (goto-char end)
5486 (if (bolp) (backward-char 1) (end-of-line 1))
5487 (setq end (move-marker (make-marker) (point)))
5488 ;; Lets see if this is tab-separated material. If every nonempty line
5489 ;; contains a tab, we will assume that it is tab-separated material
5490 (if nspace
5491 (setq tabsep nil)
5492 (goto-char beg)
5493 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5494 (if nspace (setq tabsep nil))
5495 (if tabsep
5496 (setq re "^\\|\t")
5497 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5498 (max 1 (prefix-numeric-value nspace)))))
5499 (goto-char beg)
5500 (while (re-search-forward re end t)
5501 (replace-match "|" t t))
5502 (goto-char beg)
5503 (insert " ")
5504 (org-table-align)))
5505
5506 (defun org-table-import (file arg)
5507 "Import FILE as a table.
5508 The file is assumed to be tab-separated. Such files can be produced by most
5509 spreadsheet and database applications. If no tabs (at least one per line)
5510 are found, lines will be split on whitespace into fields."
5511 (interactive "f\nP")
5512 (or (bolp) (newline))
5513 (let ((beg (point))
5514 (pm (point-max)))
5515 (insert-file-contents file)
5516 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5517
5518 (defun org-table-export ()
5519 "Export table as a tab-separated file.
5520 Such a file can be imported into a spreadsheet program like Excel."
5521 (interactive)
5522 (let* ((beg (org-table-begin))
5523 (end (org-table-end))
5524 (table (buffer-substring beg end))
5525 (file (read-file-name "Export table to: "))
5526 buf)
5527 (unless (or (not (file-exists-p file))
5528 (y-or-n-p (format "Overwrite file %s? " file)))
5529 (error "Abort"))
5530 (with-current-buffer (find-file-noselect file)
5531 (setq buf (current-buffer))
5532 (erase-buffer)
5533 (fundamental-mode)
5534 (insert table)
5535 (goto-char (point-min))
5536 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5537 (replace-match "" t t)
5538 (end-of-line 1))
5539 (goto-char (point-min))
5540 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5541 (replace-match "" t t)
5542 (goto-char (min (1+ (point)) (point-max))))
5543 (goto-char (point-min))
5544 (while (re-search-forward "^-[-+]*$" nil t)
5545 (replace-match "")
5546 (if (looking-at "\n")
5547 (delete-char 1)))
5548 (goto-char (point-min))
5549 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5550 (replace-match "\t" t t))
5551 (save-buffer))
5552 (kill-buffer buf)))
5553
5554 (defvar org-table-aligned-begin-marker (make-marker)
5555 "Marker at the beginning of the table last aligned.
5556 Used to check if cursor still is in that table, to minimize realignment.")
5557 (defvar org-table-aligned-end-marker (make-marker)
5558 "Marker at the end of the table last aligned.
5559 Used to check if cursor still is in that table, to minimize realignment.")
5560 (defvar org-table-last-alignment nil
5561 "List of flags for flushright alignment, from the last re-alignment.
5562 This is being used to correctly align a single field after TAB or RET.")
5563 ;; FIXME: The following is currently not used.
5564 (defvar org-table-last-column-widths nil
5565 "List of max width of fields in each column.
5566 This is being used to correctly align a single field after TAB or RET.")
5567
5568
5569 (defun org-table-align ()
5570 "Align the table at point by aligning all vertical bars."
5571 (interactive)
5572 (let* (
5573 ;; Limits of table
5574 (beg (org-table-begin))
5575 (end (org-table-end))
5576 ;; Current cursor position
5577 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5578 (colpos (org-table-current-column))
5579 (winstart (window-start))
5580 text lines (new "") lengths l typenums ty fields maxfields i
5581 column
5582 (indent "") cnt frac
5583 rfmt hfmt
5584 (spaces (if (org-in-invisibility-spec-p '(org-table))
5585 org-table-spaces-around-invisible-separators
5586 org-table-spaces-around-separators))
5587 (sp1 (car spaces))
5588 (sp2 (cdr spaces))
5589 (rfmt1 (concat
5590 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5591 (hfmt1 (concat
5592 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5593 emptystrings)
5594 (untabify beg end)
5595 ;; (message "Aligning table...")
5596 ;; Get the rows
5597 (setq lines (org-split-string
5598 (buffer-substring-no-properties beg end) "\n"))
5599 ;; Store the indentation of the first line
5600 (if (string-match "^ *" (car lines))
5601 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5602 ;; Mark the hlines
5603 (setq lines (mapcar (lambda (l) (if (string-match "^ *|-" l) nil l))
5604 lines))
5605 ;; Get the data fields
5606 (setq fields (mapcar
5607 (lambda (l)
5608 (org-split-string l " *| *"))
5609 (delq nil (copy-sequence lines))))
5610 ;; How many fields in the longest line?
5611 (condition-case nil
5612 (setq maxfields (apply 'max (mapcar 'length fields)))
5613 (error
5614 (kill-region beg end)
5615 (org-table-create org-table-default-size)
5616 (error "Empty table - created default table")))
5617 ;; A list of empty string to fill any short rows on output
5618 (setq emptystrings (make-list maxfields ""))
5619 ;; Get the maximum length of a field and the most common datatype
5620 ;; for each column
5621 (setq i -1)
5622 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5623 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5624 ;; maximum length
5625 (push (apply 'max 1 (mapcar 'length column)) lengths)
5626 ;; compute the fraction stepwise, ignoring empty fields
5627 (setq cnt 0 frac 0.0)
5628 (mapcar
5629 (lambda (x)
5630 (if (equal x "")
5631 nil
5632 (setq frac ( / (+ (* frac cnt)
5633 (if (string-match org-table-number-regexp x) 1 0))
5634 (setq cnt (1+ cnt))))))
5635 column)
5636 (push (>= frac org-table-number-fraction) typenums))
5637 (setq lengths (nreverse lengths)
5638 typenums (nreverse typenums))
5639 (setq org-table-last-alignment typenums
5640 org-table-last-column-widths lengths)
5641 ;; Compute the formats needed for output of the table
5642 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
5643 (while (setq l (pop lengths))
5644 (setq ty (if (pop typenums) "" "-")) ; number types flushright
5645 (setq rfmt (concat rfmt (format rfmt1 ty l))
5646 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
5647 (setq rfmt (concat rfmt "\n")
5648 hfmt (concat (substring hfmt 0 -1) "|\n"))
5649 ;; Produce the new table
5650 ;;(while lines
5651 ;; (setq l (pop lines))
5652 ;; (if l
5653 ;; (setq new (concat new (apply 'format rfmt
5654 ;; (append (pop fields) emptystrings))))
5655 ;; (setq new (concat new hfmt))))
5656 (setq new (mapconcat
5657 (lambda (l)
5658 (if l (apply 'format rfmt
5659 (append (pop fields) emptystrings))
5660 hfmt))
5661 lines ""))
5662 ;; Replace the old one
5663 (delete-region beg end)
5664 (move-marker end nil)
5665 (move-marker org-table-aligned-begin-marker (point))
5666 (insert new)
5667 (move-marker org-table-aligned-end-marker (point))
5668 ;; Try to move to the old location (approximately)
5669 (goto-line linepos)
5670 (set-window-start (selected-window) winstart 'noforce)
5671 (org-table-goto-column colpos)
5672 (setq org-table-may-need-update nil)
5673 (if (org-in-invisibility-spec-p '(org-table))
5674 (org-table-add-invisible-to-vertical-lines))
5675 ))
5676
5677 (defun org-table-begin (&optional table-type)
5678 "Find the beginning of the table and return its position.
5679 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
5680 (save-excursion
5681 (if (not (re-search-backward
5682 (if table-type org-table-any-border-regexp
5683 org-table-border-regexp)
5684 nil t))
5685 (error "Can't find beginning of table")
5686 (goto-char (match-beginning 0))
5687 (beginning-of-line 2)
5688 (point))))
5689
5690 (defun org-table-end (&optional table-type)
5691 "Find the end of the table and return its position.
5692 With argument TABLE-TYPE, go to the end of a table.el-type table."
5693 (save-excursion
5694 (if (not (re-search-forward
5695 (if table-type org-table-any-border-regexp
5696 org-table-border-regexp)
5697 nil t))
5698 (goto-char (point-max))
5699 (goto-char (match-beginning 0)))
5700 (point-marker)))
5701
5702 (defun org-table-justify-field-maybe ()
5703 "Justify the current field, text to left, number to right."
5704 (cond
5705 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
5706 ((org-at-table-hline-p)
5707 ;; This is pretty stupid, but I don't know how to deal with hlines
5708 (setq org-table-may-need-update t))
5709 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
5710 (current-buffer)))
5711 (< (point) org-table-aligned-begin-marker)
5712 (>= (point) org-table-aligned-end-marker))
5713 ;; This is not the same table, force a full re-align
5714 (setq org-table-may-need-update t))
5715 (t ;; realign the current field, based on previous full realign
5716 (let* ((pos (point)) s org-table-may-need-update
5717 (col (org-table-current-column))
5718 (num (nth (1- col) org-table-last-alignment))
5719 l f)
5720 (when (> col 0)
5721 (skip-chars-backward "^|\n")
5722 (if (looking-at " *\\([^|\n]*?\\) *|")
5723 (progn
5724 (setq s (match-string 1)
5725 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
5726 (setq f (format (if num " %%%ds |" " %%-%ds |") l))
5727 (replace-match (format f s t t)))
5728 (setq org-table-may-need-update t))
5729 (goto-char pos))))))
5730
5731 (defun org-table-next-field ()
5732 "Go to the next field in the current table.
5733 Before doing so, re-align the table if necessary."
5734 (interactive)
5735 (if (and org-table-automatic-realign
5736 org-table-may-need-update)
5737 (org-table-align))
5738 (if (org-at-table-hline-p)
5739 (end-of-line 1))
5740 (condition-case nil
5741 (progn
5742 (re-search-forward "|" (org-table-end))
5743 (if (looking-at "[ \t]*$")
5744 (re-search-forward "|" (org-table-end)))
5745 (if (looking-at "-")
5746 (progn
5747 (beginning-of-line 0)
5748 (org-table-insert-row 'below))
5749 (if (looking-at " ") (forward-char 1))))
5750 (error
5751 (org-table-insert-row 'below))))
5752
5753 (defun org-table-previous-field ()
5754 "Go to the previous field in the table.
5755 Before doing so, re-align the table if necessary."
5756 (interactive)
5757 (if (and org-table-automatic-realign
5758 org-table-may-need-update)
5759 (org-table-align))
5760 (if (org-at-table-hline-p)
5761 (end-of-line 1))
5762 (re-search-backward "|" (org-table-begin))
5763 (re-search-backward "|" (org-table-begin))
5764 (while (looking-at "|\\(-\\|[ \t]*$\\)")
5765 (re-search-backward "|" (org-table-begin)))
5766 (if (looking-at "| ?")
5767 (goto-char (match-end 0))))
5768
5769 (defun org-table-next-row ()
5770 "Go to the next row (same column) in the current table.
5771 Before doing so, re-align the table if necessary."
5772 (interactive)
5773 (if (or (looking-at "[ \t]*$")
5774 (save-excursion (skip-chars-backward " \t") (bolp)))
5775 (newline)
5776 (if (and org-table-automatic-realign
5777 org-table-may-need-update)
5778 (org-table-align))
5779 (let ((col (org-table-current-column)))
5780 (beginning-of-line 2)
5781 (if (or (not (org-at-table-p))
5782 (org-at-table-hline-p))
5783 (progn
5784 (beginning-of-line 0)
5785 (org-table-insert-row 'below)))
5786 (org-table-goto-column col)
5787 (skip-chars-backward "^|\n\r")
5788 (if (looking-at " ") (forward-char 1)))))
5789
5790 (defun org-table-copy-down (n)
5791 "Copy a field down in the current column.
5792 If the field at the cursor is empty, copy into it the content of the nearest
5793 non-empty field above. With argument N, use the Nth non-empty field.
5794 If the current field is not empty, it is copied down to the next row, and
5795 the cursor is moved with it. Therefore, repeating this command causes the
5796 column to be filled row-by-row.
5797 If the variable `org-table-copy-increment' is non-nil and the field is an
5798 integer, it will be incremented while copying."
5799 (interactive "p")
5800 (let* ((colpos (org-table-current-column))
5801 (field (org-table-get-field))
5802 (non-empty (string-match "[^ \t]" field))
5803 (beg (org-table-begin))
5804 txt)
5805 (org-table-check-inside-data-field)
5806 (if non-empty (progn (org-table-next-row) (org-table-blank-field)))
5807 (if (save-excursion
5808 (setq txt
5809 (catch 'exit
5810 (while (progn (beginning-of-line 1)
5811 (re-search-backward org-table-dataline-regexp
5812 beg t))
5813 (org-table-goto-column colpos t)
5814 (if (and (looking-at
5815 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
5816 (= (setq n (1- n)) 0))
5817 (throw 'exit (match-string 1)))))))
5818 (progn
5819 (if (and org-table-copy-increment
5820 (string-match "^[0-9]+$" txt))
5821 (setq txt (format "%d" (+ (string-to-int txt) 1))))
5822 (insert txt)
5823 (org-table-align))
5824 (error "No non-empty field found"))))
5825
5826 (defun org-table-check-inside-data-field ()
5827 "Is point inside a table data field?
5828 I.e. not on a hline or before the first or after the last column?"
5829 (if (or (not (org-at-table-p))
5830 (= (org-table-current-column) 0)
5831 (org-at-table-hline-p)
5832 (looking-at "[ \t]*$"))
5833 (error "Not in table data field")))
5834
5835 (defvar org-table-clip nil
5836 "Clipboard for table regions.")
5837
5838 (defun org-table-blank-field ()
5839 "Blank the current table field or active region."
5840 (interactive)
5841 (org-table-check-inside-data-field)
5842 (if (and (interactive-p) (org-region-active-p))
5843 (let (org-table-clip)
5844 (org-table-cut-region))
5845 (skip-chars-backward "^|")
5846 (backward-char 1)
5847 (if (looking-at "|[^|]+")
5848 (let* ((pos (match-beginning 0))
5849 (match (match-string 0))
5850 (len (length match)))
5851 (replace-match (concat "|" (make-string (1- len) ?\ )))
5852 (goto-char (+ 2 pos))
5853 (substring match 1)))))
5854
5855 (defun org-table-get-field (&optional n replace)
5856 "Return the value of the field in column N of current row.
5857 N defaults to current field.
5858 If REPLACE is a string, replace field with this value. The return value
5859 is always the old value."
5860 (and n (org-table-goto-column n))
5861 (skip-chars-backward "^|")
5862 (backward-char 1)
5863 (if (looking-at "|[^|\r\n]*")
5864 (let* ((pos (match-beginning 0))
5865 (val (buffer-substring (1+ pos) (match-end 0))))
5866 (if replace
5867 (replace-match (concat "|" replace)))
5868 (goto-char (+ 2 pos))
5869 val)))
5870
5871 (defun org-table-current-column ()
5872 "Find out which column we are in.
5873 When called interactively, column is also displayed in echo area."
5874 (interactive)
5875 (if (interactive-p) (org-table-check-inside-data-field))
5876 (save-excursion
5877 (let ((cnt 0) (pos (point)))
5878 (beginning-of-line 1)
5879 (while (search-forward "|" pos t)
5880 (setq cnt (1+ cnt)))
5881 (if (interactive-p) (message "This is table column %d" cnt))
5882 cnt)))
5883
5884 (defun org-table-goto-column (n &optional on-delim force)
5885 "Move the cursor to the Nth column in the current table line.
5886 With optional argument ON-DELIM, stop with point before the left delimiter
5887 of the field.
5888 If there are less than N fields, just go to after the last delimiter.
5889 However, when FORCE is non-nil, create new columns if necessary."
5890 (let ((pos (point-at-eol)))
5891 (beginning-of-line 1)
5892 (when (> n 0)
5893 (while (and (> (setq n (1- n)) -1)
5894 (or (search-forward "|" pos t)
5895 (and force
5896 (progn (end-of-line 1)
5897 (skip-chars-backward "^|")
5898 (insert " |")
5899 (backward-char 2) t)))))
5900 (when (and force (not (looking-at ".*|")))
5901 (save-excursion (end-of-line 1) (insert "|")))
5902 (if on-delim
5903 (backward-char 1)
5904 (if (looking-at " ") (forward-char 1))))))
5905
5906 (defun org-at-table-p (&optional table-type)
5907 "Return t if the cursor is inside an org-type table."
5908 (if org-enable-table-editor
5909 (save-excursion
5910 (beginning-of-line 1)
5911 (looking-at (if table-type org-table-any-line-regexp
5912 org-table-line-regexp)))
5913 nil))
5914
5915 (defun org-table-recognize-table.el ()
5916 "If there is a table.el table nearby, recognize it and move into it."
5917 (if org-table-tab-recognizes-table.el
5918 (if (org-at-table.el-p)
5919 (progn
5920 (beginning-of-line 1)
5921 (if (looking-at org-table-dataline-regexp)
5922 nil
5923 (if (looking-at org-table1-hline-regexp)
5924 (progn
5925 (beginning-of-line 2)
5926 (if (looking-at org-table-any-border-regexp)
5927 (beginning-of-line -1)))))
5928 (if (re-search-forward "|" (org-table-end t) t)
5929 (progn
5930 (require 'table)
5931 (if (table--at-cell-p (point))
5932 t
5933 (message "recognizing table.el table...")
5934 (table-recognize-table)
5935 (message "recognizing table.el table...done")))
5936 (error "This should not happen..."))
5937 t)
5938 nil)
5939 nil))
5940
5941 (defun org-at-table.el-p ()
5942 "Return t if the cursor is inside a table.el-type table."
5943 (save-excursion
5944 (if (org-at-table-p 'any)
5945 (progn
5946 (goto-char (org-table-begin 'any))
5947 (looking-at org-table1-hline-regexp))
5948 nil)))
5949
5950 (defun org-at-table-hline-p ()
5951 "Return t if the cursor is inside a hline in a table."
5952 (if org-enable-table-editor
5953 (save-excursion
5954 (beginning-of-line 1)
5955 (looking-at org-table-hline-regexp))
5956 nil))
5957
5958 (defun org-table-insert-column ()
5959 "Insert a new column into the table."
5960 (interactive)
5961 (if (not (org-at-table-p))
5962 (error "Not at a table"))
5963 (org-table-find-dataline)
5964 (let* ((col (max 1 (org-table-current-column)))
5965 (beg (org-table-begin))
5966 (end (org-table-end))
5967 ;; Current cursor position
5968 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5969 (colpos col))
5970 (goto-char beg)
5971 (while (< (point) end)
5972 (if (org-at-table-hline-p)
5973 nil
5974 (org-table-goto-column col t)
5975 (insert "| "))
5976 (beginning-of-line 2))
5977 (move-marker end nil)
5978 (goto-line linepos)
5979 (org-table-goto-column colpos))
5980 (org-table-align))
5981
5982 (defun org-table-find-dataline ()
5983 "Find a dataline in the current table, which is needed for column commands."
5984 (if (and (org-at-table-p)
5985 (not (org-at-table-hline-p)))
5986 t
5987 (let ((col (current-column))
5988 (end (org-table-end)))
5989 (move-to-column col)
5990 (while (and (< (point) end)
5991 (or (not (= (current-column) col))
5992 (org-at-table-hline-p)))
5993 (beginning-of-line 2)
5994 (move-to-column col))
5995 (if (and (org-at-table-p)
5996 (not (org-at-table-hline-p)))
5997 t
5998 (error
5999 "Please position cursor in a data line for column operations")))))
6000
6001 (defun org-table-delete-column ()
6002 "Delete a column into the table."
6003 (interactive)
6004 (if (not (org-at-table-p))
6005 (error "Not at a table"))
6006 (org-table-find-dataline)
6007 (org-table-check-inside-data-field)
6008 (let* ((col (org-table-current-column))
6009 (beg (org-table-begin))
6010 (end (org-table-end))
6011 ;; Current cursor position
6012 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6013 (colpos col))
6014 (goto-char beg)
6015 (while (< (point) end)
6016 (if (org-at-table-hline-p)
6017 nil
6018 (org-table-goto-column col t)
6019 (and (looking-at "|[^|\n]+|")
6020 (replace-match "|")))
6021 (beginning-of-line 2))
6022 (move-marker end nil)
6023 (goto-line linepos)
6024 (org-table-goto-column colpos))
6025 (org-table-align))
6026
6027 (defun org-table-move-column-right ()
6028 "Move column to the right."
6029 (interactive)
6030 (org-table-move-column nil))
6031 (defun org-table-move-column-left ()
6032 "Move column to the left."
6033 (interactive)
6034 (org-table-move-column 'left))
6035
6036 (defun org-table-move-column (&optional left)
6037 "Move the current column to the right. With arg LEFT, move to the left."
6038 (interactive "P")
6039 (if (not (org-at-table-p))
6040 (error "Not at a table"))
6041 (org-table-find-dataline)
6042 (org-table-check-inside-data-field)
6043 (let* ((col (org-table-current-column))
6044 (col1 (if left (1- col) col))
6045 (beg (org-table-begin))
6046 (end (org-table-end))
6047 ;; Current cursor position
6048 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6049 (colpos (if left (1- col) (1+ col))))
6050 (if (and left (= col 1))
6051 (error "Cannot move column further left"))
6052 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6053 (error "Cannot move column further right"))
6054 (goto-char beg)
6055 (while (< (point) end)
6056 (if (org-at-table-hline-p)
6057 nil
6058 (org-table-goto-column col1 t)
6059 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6060 (replace-match "|\\2|\\1|")))
6061 (beginning-of-line 2))
6062 (move-marker end nil)
6063 (goto-line linepos)
6064 (org-table-goto-column colpos))
6065 (org-table-align))
6066
6067 (defun org-table-move-row-down ()
6068 "Move table row down."
6069 (interactive)
6070 (org-table-move-row nil))
6071 (defun org-table-move-row-up ()
6072 "Move table row up."
6073 (interactive)
6074 (org-table-move-row 'up))
6075
6076 (defun org-table-move-row (&optional up)
6077 "Move the current table line down. With arg UP, move it up."
6078 (interactive "P")
6079 (let ((col (current-column))
6080 (pos (point))
6081 (tonew (if up 0 2))
6082 txt)
6083 (beginning-of-line tonew)
6084 (if (not (org-at-table-p))
6085 (progn
6086 (goto-char pos)
6087 (error "Cannot move row further.")))
6088 (goto-char pos)
6089 (beginning-of-line 1)
6090 (setq pos (point))
6091 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6092 (delete-region (point) (1+ (point-at-eol)))
6093 (beginning-of-line tonew)
6094 (insert txt)
6095 (beginning-of-line 0)
6096 (move-to-column col)))
6097
6098 (defun org-table-insert-row (&optional arg)
6099 "Insert a new row above the current line into the table.
6100 With prefix ARG, insert below the current line."
6101 (interactive "P")
6102 (if (not (org-at-table-p))
6103 (error "Not at a table"))
6104 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
6105 (if (string-match "^[ \t]*|-" line)
6106 (setq line (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6107 (setq line (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6108 (beginning-of-line (if arg 2 1))
6109 (let (org-table-may-need-update)
6110 (apply 'insert-before-markers line)
6111 (insert-before-markers "\n"))
6112 (beginning-of-line 0)
6113 (re-search-forward "| ?" (point-at-eol) t)
6114 (and org-table-may-need-update (org-table-align))))
6115
6116 (defun org-table-insert-hline (&optional arg)
6117 "Insert a horizontal-line below the current line into the table.
6118 With prefix ARG, insert above the current line."
6119 (interactive "P")
6120 (if (not (org-at-table-p))
6121 (error "Not at a table"))
6122 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6123 (col (current-column))
6124 start)
6125 (if (string-match "^[ \t]*|-" line)
6126 (setq line
6127 (mapcar (lambda (x) (if (member x '(?| ?+))
6128 (prog1 (if start ?+ ?|) (setq start t))
6129 (if start ?- ?\ )))
6130 line))
6131 (setq line
6132 (mapcar (lambda (x) (if (equal x ?|)
6133 (prog1 (if start ?+ ?|) (setq start t))
6134 (if start ?- ?\ )))
6135 line)))
6136 (beginning-of-line (if arg 1 2))
6137 (apply 'insert line)
6138 (if (equal (char-before (point)) ?+)
6139 (progn (backward-delete-char 1) (insert "|")))
6140 (insert "\n")
6141 (beginning-of-line 0)
6142 (move-to-column col)))
6143
6144 (defun org-table-kill-row ()
6145 "Delete the current row or horizontal line from the table."
6146 (interactive)
6147 (if (not (org-at-table-p))
6148 (error "Not at a table"))
6149 (let ((col (current-column)))
6150 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6151 (if (not (org-at-table-p)) (beginning-of-line 0))
6152 (move-to-column col)))
6153
6154
6155 (defun org-table-cut-region ()
6156 "Copy region in table to the clipboard and blank all relevant fields."
6157 (interactive)
6158 (org-table-copy-region 'cut))
6159
6160 (defun org-table-copy-region (&optional cut)
6161 "Copy rectangular region in table to clipboard.
6162 A special clipboard is used which can only be accessed
6163 with `org-table-paste-rectangle'"
6164 (interactive "P")
6165 (unless (org-region-active-p) (error "No active region"))
6166 (let* ((beg (region-beginning))
6167 (end (region-end))
6168 l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6169 region cols
6170 (rpl (if cut " " nil)))
6171 (goto-char beg)
6172 (org-table-check-inside-data-field)
6173 (setq l01 (count-lines (point-min) (point))
6174 c01 (org-table-current-column))
6175 (goto-char end)
6176 (org-table-check-inside-data-field)
6177 (setq l02 (count-lines (point-min) (point))
6178 c02 (org-table-current-column))
6179 (setq l1 (min l01 l02) l2 (max l01 l02)
6180 c1 (min c01 c02) c2 (max c01 c02))
6181 (catch 'exit
6182 (while t
6183 (catch 'nextline
6184 (if (> l1 l2) (throw 'exit t))
6185 (goto-line l1)
6186 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6187 (setq cols nil ic1 c1 ic2 c2)
6188 (while (< ic1 (1+ ic2))
6189 (push (org-table-get-field ic1 rpl) cols)
6190 (setq ic1 (1+ ic1)))
6191 (push (nreverse cols) region)
6192 (setq l1 (1+ l1)))))
6193 (setq org-table-clip (nreverse region))
6194 (if cut (org-table-align))))
6195
6196 (defun org-table-paste-rectangle ()
6197 "Paste a rectangular region into a table.
6198 The upper right corner ends up in the current field. All involved fields
6199 will be overwritten. If the rectangle does not fit into the present table,
6200 the table is enlarged as needed. The process ignores horizontal separator
6201 lines."
6202 (interactive)
6203 (unless (and org-table-clip (listp org-table-clip))
6204 (error "First cut/copy a region to paste!"))
6205 (org-table-check-inside-data-field)
6206 (let* ((clip org-table-clip)
6207 (line (count-lines (point-min) (point)))
6208 (col (org-table-current-column))
6209 (org-enable-table-editor t)
6210 (org-table-automatic-realign nil)
6211 c cols field)
6212 (while (setq cols (pop clip))
6213 (while (org-at-table-hline-p) (beginning-of-line 2))
6214 (if (not (org-at-table-p))
6215 (progn (end-of-line 0) (org-table-next-field)))
6216 (setq c col)
6217 (while (setq field (pop cols))
6218 (org-table-goto-column c nil 'force)
6219 (org-table-get-field nil field)
6220 (setq c (1+ c)))
6221 (beginning-of-line 2))
6222 (goto-line line)
6223 (org-table-goto-column col)
6224 (org-table-align)))
6225
6226 (defun org-table-convert ()
6227 "Convert from `org-mode' table to table.el and back.
6228 Obviously, this only works within limits. When an Org-mode table is
6229 converted to table.el, all horizontal separator lines get lost, because
6230 table.el uses these as cell boundaries and has no notion of horizontal lines.
6231 A table.el table can be converted to an Org-mode table only if it does not
6232 do row or column spanning. Multiline cells will become multiple cells.
6233 Beware, Org-mode does not test if the table can be successfully converted - it
6234 blindly applies a recipe that works for simple tables."
6235 (interactive)
6236 (require 'table)
6237 (if (org-at-table.el-p)
6238 ;; convert to Org-mode table
6239 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6240 (end (move-marker (make-marker) (org-table-end t))))
6241 (table-unrecognize-region beg end)
6242 (goto-char beg)
6243 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6244 (replace-match ""))
6245 (goto-char beg))
6246 (if (org-at-table-p)
6247 ;; convert to table.el table
6248 (let ((beg (move-marker (make-marker) (org-table-begin)))
6249 (end (move-marker (make-marker) (org-table-end))))
6250 ;; first, get rid of all horizontal lines
6251 (goto-char beg)
6252 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6253 (replace-match ""))
6254 ;; insert a hline before first
6255 (goto-char beg)
6256 (org-table-insert-hline 'above)
6257 ;; insert a hline after each line
6258 (while (progn (beginning-of-line 2) (< (point) end))
6259 (org-table-insert-hline))
6260 (goto-char beg)
6261 (setq end (move-marker end (org-table-end)))
6262 ;; replace "+" at beginning and ending of hlines
6263 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6264 (replace-match "\\1+-"))
6265 (goto-char beg)
6266 (while (re-search-forward "-|[ \t]*$" end t)
6267 (replace-match "-+"))
6268 (goto-char beg)))))
6269
6270 (defun org-table-wrap-region (arg)
6271 "Wrap several fields in a column like a paragraph.
6272 This is useful if you'd like to spread the contents of a field over several
6273 lines, in order to keep the table compact.
6274
6275 If there is an active region, and both point and mark are in the same column,
6276 the text in the column is wrapped to minimum width for the given number of
6277 lines. Generally, this makes the table more compact. A prefix ARG may be
6278 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6279 formats the selected text to two lines. If the region was longer than 2
6280 lines, the remaining lines remain empty. A negative prefix argument reduces
6281 the current number of lines by that amount. The wrapped text is pasted back
6282 into the table. If you formatted it to more lines than it was before, fields
6283 further down in the table get overwritten - so you might need to make space in
6284 the table first.
6285
6286 If there is no region, the current field is split at the cursor position and
6287 the text fragment to the right of the cursor is prepended to the field one
6288 line down.
6289
6290 If there is no region, but you specify a prefix ARG, the current field gets
6291 blank, and the content is appended to the field above."
6292 (interactive "P")
6293 (org-table-check-inside-data-field)
6294 (if (org-region-active-p)
6295 ;; There is a region: fill as a paragraph
6296 (let ((beg (region-beginning))
6297 nlines)
6298 (org-table-cut-region)
6299 (if (> (length (car org-table-clip)) 1)
6300 (error "Region must be limited to single column"))
6301 (setq nlines (if arg
6302 (if (< arg 1)
6303 (+ (length org-table-clip) arg)
6304 arg)
6305 (length org-table-clip)))
6306 (setq org-table-clip
6307 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6308 nil nlines)))
6309 (goto-char beg)
6310 (org-table-paste-rectangle))
6311 ;; No region, split the current field at point
6312 (if arg
6313 ;; combine with field above
6314 (let ((s (org-table-blank-field))
6315 (col (org-table-current-column)))
6316 (beginning-of-line 0)
6317 (while (org-at-table-hline-p) (beginning-of-line 0))
6318 (org-table-goto-column col)
6319 (skip-chars-forward "^|")
6320 (skip-chars-backward " ")
6321 (insert " " (org-trim s))
6322 (org-table-align))
6323 ;; split field
6324 (when (looking-at "\\([^|]+\\)+|")
6325 (let ((s (match-string 1)))
6326 (replace-match " |")
6327 (goto-char (match-beginning 0))
6328 (org-table-next-row)
6329 (insert (org-trim s) " ")
6330 (org-table-align))))))
6331
6332 (defun org-trim (s)
6333 "Remove whitespace at beginning and end of string."
6334 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6335 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s))))
6336
6337 (defun org-wrap (string &optional width lines)
6338 "Wrap string to either a number of lines, or a width in characters.
6339 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6340 that costs. If there is a word longer than WIDTH, the text is actually
6341 wrapped to the length of that word.
6342 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6343 many lines, whatever width that takes.
6344 The return value is a list of lines, without newlines at the end."
6345 (let* ((words (org-split-string string "[ \t\n]+"))
6346 (maxword (apply 'max (mapcar 'length words)))
6347 w ll)
6348 (cond (width
6349 (org-do-wrap words (max maxword width)))
6350 (lines
6351 (setq w maxword)
6352 (setq ll (org-do-wrap words maxword))
6353 (if (<= (length ll) lines)
6354 ll
6355 (setq ll words)
6356 (while (> (length ll) lines)
6357 (setq w (1+ w))
6358 (setq ll (org-do-wrap words w)))
6359 ll))
6360 (t (error "Cannot wrap this")))))
6361
6362
6363 (defun org-do-wrap (words width)
6364 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6365 (let (lines line)
6366 (while words
6367 (setq line (pop words))
6368 (while (and words (< (+ (length line) (length (car words))) width))
6369 (setq line (concat line " " (pop words))))
6370 (setq lines (push line lines)))
6371 (nreverse lines)))
6372
6373 ;; FIXME: I think I can make this more efficient
6374 (defun org-split-string (string &optional separators)
6375 "Splits STRING into substrings at SEPARATORS.
6376 No empty strings are returned if there are matches at the beginning
6377 and end of string."
6378 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6379 (start 0)
6380 notfirst
6381 (list nil))
6382 (while (and (string-match rexp string
6383 (if (and notfirst
6384 (= start (match-beginning 0))
6385 (< start (length string)))
6386 (1+ start) start))
6387 (< (match-beginning 0) (length string)))
6388 (setq notfirst t)
6389 (or (eq (match-beginning 0) 0)
6390 (and (eq (match-beginning 0) (match-end 0))
6391 (eq (match-beginning 0) start))
6392 (setq list
6393 (cons (substring string start (match-beginning 0))
6394 list)))
6395 (setq start (match-end 0)))
6396 (or (eq start (length string))
6397 (setq list
6398 (cons (substring string start)
6399 list)))
6400 (nreverse list)))
6401
6402 (defun org-table-add-invisible-to-vertical-lines ()
6403 "Add an `invisible' property to vertical lines of current table."
6404 (interactive)
6405 (let* ((beg (org-table-begin))
6406 (end (org-table-end))
6407 (end1))
6408 (save-excursion
6409 (goto-char beg)
6410 (while (< (point) end)
6411 (setq end1 (point-at-eol))
6412 (if (looking-at org-table-dataline-regexp)
6413 (while (re-search-forward "|" end1 t)
6414 (add-text-properties (1- (point)) (point)
6415 '(invisible org-table)))
6416 (while (re-search-forward "[+|]" end1 t)
6417 (add-text-properties (1- (point)) (point)
6418 '(invisible org-table))))
6419 (beginning-of-line 2)))))
6420
6421 (defun org-table-toggle-vline-visibility (&optional arg)
6422 "Toggle the visibility of table vertical lines.
6423 The effect is immediate and on all tables in the file.
6424 With prefix ARG, make lines invisible when ARG is positive, make lines
6425 visible when ARG is not positive"
6426 (interactive "P")
6427 (let ((action (cond
6428 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6429 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6430 (t (if (org-in-invisibility-spec-p '(org-table))
6431 'off
6432 'on)))))
6433 (if (eq action 'off)
6434 (progn
6435 (org-remove-from-invisibility-spec '(org-table))
6436 (org-table-map-tables 'org-table-align)
6437 (message "Vertical table lines visible")
6438 (if (org-at-table-p)
6439 (org-table-align)))
6440 (org-add-to-invisibility-spec '(org-table))
6441 (org-table-map-tables 'org-table-align)
6442 (message "Vertical table lines invisible"))
6443 (redraw-frame (selected-frame))))
6444
6445 (defun org-table-map-tables (function)
6446 "Apply FUNCTION to the start of all tables in the buffer."
6447 (save-excursion
6448 (save-restriction
6449 (widen)
6450 (goto-char (point-min))
6451 (while (re-search-forward org-table-any-line-regexp nil t)
6452 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6453 (beginning-of-line 1)
6454 (if (looking-at org-table-line-regexp)
6455 (save-excursion (funcall function)))
6456 (re-search-forward org-table-any-border-regexp nil 1)))))
6457
6458 (defun org-table-sum ()
6459 "Sum numbers in region of current table column.
6460 The result will be displayed in the echo area, and will be available
6461 as kill to be inserted with \\[yank].
6462
6463 If there is an active region, it is interpreted as a rectangle and all
6464 numbers in that rectangle will be summed. If there is no active
6465 region and point is located in a table column, sum all numbers in that
6466 column.
6467
6468 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6469 numbers are assumed to be times as well (in decimal hours) and the
6470 numbers are added as such."
6471 (interactive)
6472 (save-excursion
6473 (let (beg end col (timecnt 0) diff h m s)
6474 (if (org-region-active-p)
6475 (setq beg (region-beginning) end (region-end))
6476 (setq col (org-table-current-column))
6477 (goto-char (org-table-begin))
6478 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6479 (error "No table data"))
6480 (org-table-goto-column col)
6481 (skip-chars-backward "^|")
6482 (setq beg (point))
6483 (goto-char (org-table-end))
6484 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6485 (error "No table data"))
6486 (org-table-goto-column col)
6487 (skip-chars-forward "^|")
6488 (setq end (point)))
6489 (let* ((l1 (progn (goto-char beg)
6490 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6491 (l2 (progn (goto-char end)
6492 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6493 (items (if (= l1 l2)
6494 (split-string (buffer-substring beg end))
6495 (split-string
6496 (mapconcat 'identity (extract-rectangle beg end) " "))))
6497 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6498 items)))
6499 (res (apply '+ numbers))
6500 (sres (if (= timecnt 0)
6501 (format "%g" res)
6502 (setq diff (* 3600 res)
6503 h (floor (/ diff 3600)) diff (mod diff 3600)
6504 m (floor (/ diff 60)) diff (mod diff 60)
6505 s diff)
6506 (format "%d:%02d:%02d" h m s))))
6507 (kill-new sres)
6508 (message (substitute-command-keys
6509 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6510 (length numbers) sres)))))))
6511
6512 (defun org-table-get-number-for-summing (s)
6513 (let (n)
6514 (if (string-match "^ *|? *" s)
6515 (setq s (replace-match "" nil nil s)))
6516 (if (string-match " *|? *$" s)
6517 (setq s (replace-match "" nil nil s)))
6518 (setq n (string-to-number s))
6519 (cond
6520 ((and (string-match "0" s)
6521 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6522 ((string-match "\\`[ \t]+\\'" s) nil)
6523 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6524 (let ((h (string-to-number (or (match-string 1 s) "0")))
6525 (m (string-to-number (or (match-string 2 s) "0")))
6526 (s (string-to-number (or (match-string 4 s) "0"))))
6527 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6528 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6529 ((equal n 0) nil)
6530 (t n))))
6531
6532 (defvar org-table-current-formula nil)
6533 (defvar org-table-formula-history nil)
6534 (defun org-table-get-formula (current)
6535 (if (and current (not (equal "" org-table-current-formula)))
6536 org-table-current-formula
6537 (setq org-table-current-formula
6538 (read-string
6539 "Formula [last]: " "" 'org-table-formula-history
6540 org-table-current-formula))))
6541
6542 (defun org-this-word ()
6543 ;; Get the current word
6544 (save-excursion
6545 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
6546 (end (progn (skip-chars-forward "^ \t\n") (point))))
6547 (buffer-substring-no-properties beg end))))
6548
6549 (defun org-table-eval-formula (&optional ndown)
6550 "Replace the table field value at the cursor by the result of a calculation.
6551
6552 This function makes use of Dave Gillespie's calc package, arguably the most
6553 exciting program ever written for GNU Emacs. So you need to have calc
6554 installed in order to use this function.
6555
6556 In a table, this command replaces the value in the current field with the
6557 result of a formula. While nowhere near the computation options of a
6558 spreadsheet program, this is still very useful. Note that there is no
6559 automatic updating of a calculated field, nor will the field remember the
6560 formula. The command needs to be applied again after changing input
6561 fields.
6562
6563 When called, the command first prompts for a formula, which is read in the
6564 minibuffer. Previously entered formulae are available through the history
6565 list, and the last used formula is the default, reachable by simply
6566 pressing RET.
6567
6568 The formula can be any algebraic expression understood by the calc package.
6569 Before evaluation, variable substitution takes place: \"$\" is replaced by
6570 the field the cursor is currently in, and $1..$n reference the fields in
6571 the current row. Values from a *different* row can *not* be referenced
6572 here, so the command supports only horizontal computing. The formula can
6573 contain an optional printf format specifier after a semicolon, to reformat
6574 the result.
6575
6576 A few examples for formulae:
6577 $1+$2 Sum of first and second field
6578 $1+$2;%.2f Same, and format result to two digits after dec.point
6579 exp($2)+exp($1) Math functions can be used
6580 $;%.1f Reformat current cell to 1 digit after dec.point
6581 ($3-32)*5/9 degrees F -> C conversion
6582
6583 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
6584 field, and to the same same column in all following rows, until reaching a
6585 horizontal line or the end of the table. When the command is called with a
6586 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
6587 to the current row, and to the following n-1 rows (but not beyond a
6588 separator line)."
6589 (interactive "P")
6590 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
6591 (require 'calc)
6592 (org-table-check-inside-data-field)
6593 (let* (fields
6594 (org-table-automatic-realign nil)
6595 (down (> ndown 1))
6596 (formula (org-table-get-formula nil))
6597 (n0 (org-table-current-column))
6598 n form fmt x ev)
6599 (if (string-match ";" formula)
6600 (let ((tmp (org-split-string formula ";")))
6601 (setq formula (car tmp) fmt (nth 1 tmp))))
6602 (while (> ndown 0)
6603 (setq fields (org-split-string
6604 (concat " " (buffer-substring
6605 (point-at-bol) (point-at-eol))) "|"))
6606 (setq ndown (1- ndown))
6607 (setq form (copy-sequence formula))
6608 (while (string-match "\\$\\([0-9]+\\)?" form)
6609 (setq n (if (match-beginning 1)
6610 (string-to-int (match-string 1 form))
6611 n0)
6612 x (nth n fields))
6613 (unless x (error "Invalid field specifier \"%s\""
6614 (match-string 0 form)))
6615 (if (equal (string-to-number x) 0) (setq x "0"))
6616 (setq form (replace-match x t t form)))
6617 (setq ev (calc-eval (list form) 'num))
6618 (if (listp ev)
6619 (error "Invalid expression: %s (%s at %d)" form (nth 1 ev) (car ev)))
6620 (org-table-blank-field)
6621 (if fmt
6622 (insert (format fmt (string-to-number ev)))
6623 (insert ev))
6624 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
6625 (call-interactively 'org-return)
6626 (setq ndown 0)))
6627 (org-table-align)))
6628
6629 ;;; The orgtbl minor mode
6630
6631 ;; Define a minor mode which can be used in other modes in order to
6632 ;; integrate the org-mode table editor.
6633
6634 ;; This is really a hack, because the org-mode table editor uses several
6635 ;; keys which normally belong to the major mode, for example the TAB and
6636 ;; RET keys. Here is how it works: The minor mode defines all the keys
6637 ;; necessary to operate the table editor, but wraps the commands into a
6638 ;; function which tests if the cursor is currently inside a table. If that
6639 ;; is the case, the table editor command is executed. However, when any of
6640 ;; those keys is used outside a table, the function uses `key-binding' to
6641 ;; look up if the key has an associated command in another currently active
6642 ;; keymap (minor modes, major mode, global), and executes that command.
6643 ;; There might be problems if any of the keys used by the table editor is
6644 ;; otherwise used as a prefix key.
6645
6646 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6647 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6648 ;; addresses this by checking explicitly for both bindings.
6649
6650 ;; The optimized version (see variable `orgtbl-optimized') takes over
6651 ;; all keys which are bound to `self-insert-command' in the *global map*.
6652 ;; Some modes bind other commands to simple characters, for example
6653 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
6654 ;; active, this binding is ignored inside tables and replaced with a
6655 ;; modified self-insert.
6656
6657 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
6658 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
6659 In the optimized version, the table editor takes over all simple keys that
6660 normally just insert a character. In tables, the characters are inserted
6661 in a way to minimize disturbing the table structure (i.e. in overwrite mode
6662 for empty fields). Outside tables, the correct binding of the keys is
6663 restored.
6664
6665 The default for this option is t if the optimized version is also used in
6666 Org-mode. See the variable `org-enable-table-editor' for details. Changing
6667 this variable requires a restart of Emacs to become effective."
6668 :group 'org-table
6669 :type 'boolean)
6670
6671 (defvar orgtbl-mode nil
6672 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
6673 table editor in arbitrary modes.")
6674 (make-variable-buffer-local 'orgtbl-mode)
6675
6676 (defvar orgtbl-mode-map (make-sparse-keymap)
6677 "Keymap for `orgtbl-mode'.")
6678
6679 ;;;###autoload
6680 (defun turn-on-orgtbl ()
6681 "Unconditionally turn on `orgtbl-mode'."
6682 (orgtbl-mode 1))
6683
6684 ;;;###autoload
6685 (defun orgtbl-mode (&optional arg)
6686 "The `org-mode' table editor as a minor mode for use in other modes."
6687 (interactive)
6688 (setq orgtbl-mode
6689 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
6690 (if orgtbl-mode
6691 (progn
6692 (set (make-local-variable (quote org-table-may-need-update)) t)
6693 (make-local-hook (quote before-change-functions))
6694 (add-hook 'before-change-functions 'org-before-change-function
6695 nil 'local)
6696 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
6697 auto-fill-inhibit-regexp)
6698 (set (make-local-variable 'auto-fill-inhibit-regexp)
6699 (if auto-fill-inhibit-regexp
6700 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
6701 "[ \t]*|"))
6702 (easy-menu-add orgtbl-mode-menu)
6703 (run-hooks (quote orgtbl-mode-hook)))
6704 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
6705 (remove-hook 'before-change-functions 'org-before-change-function t)
6706 (easy-menu-remove orgtbl-mode-menu)
6707 (force-mode-line-update 'all)))
6708
6709 ;; Install it as a minor mode.
6710 (put 'orgtbl-mode :included t)
6711 (put 'orgtbl-mode :menu-tag "Org Table Mode")
6712 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
6713
6714 (defun orgtbl-make-binding (fun &rest keys)
6715 "Create a function for binding in the table minor mode."
6716 (list 'lambda '(arg) '(interactive "p")
6717 (list 'if
6718 '(org-at-table-p)
6719 (list 'call-interactively (list 'quote fun))
6720 (list 'let '(orgtbl-mode)
6721 (list 'call-interactively
6722 (append '(or)
6723 (mapcar (lambda (k)
6724 (list 'key-binding k))
6725 keys)
6726 '('orgtbl-error)))))))
6727
6728 (defun orgtbl-error ()
6729 "Error when there is no default binding for a table key."
6730 (interactive)
6731 (error "This key is has no function outside tables"))
6732
6733 ;; Keybindings for the minor mode
6734 (let ((bindings
6735 '(([(meta shift left)] org-table-delete-column)
6736 ([(meta left)] org-table-move-column-left)
6737 ([(meta right)] org-table-move-column-right)
6738 ([(meta shift right)] org-table-insert-column)
6739 ([(meta shift up)] org-table-kill-row)
6740 ([(meta shift down)] org-table-insert-row)
6741 ([(meta up)] org-table-move-row-up)
6742 ([(meta down)] org-table-move-row-down)
6743 ("\C-c\C-w" org-table-cut-region)
6744 ("\C-c\M-w" org-table-copy-region)
6745 ("\C-c\C-y" org-table-paste-rectangle)
6746 ("\C-c-" org-table-insert-hline)
6747 ([(shift tab)] org-table-previous-field)
6748 ("\C-c\C-c" org-table-align)
6749 ([(return)] org-table-next-row)
6750 ([(shift return)] org-table-copy-down)
6751 ([(meta return)] org-table-wrap-region)
6752 ("\C-c\C-q" org-table-wrap-region)
6753 ("\C-c?" org-table-current-column)
6754 ("\C-c " org-table-blank-field)
6755 ("\C-c+" org-table-sum)
6756 ("\C-c|" org-table-toggle-vline-visibility)
6757 ("\C-c=" org-table-eval-formula)))
6758 elt key fun cmd)
6759 (while (setq elt (pop bindings))
6760 (setq key (car elt)
6761 fun (nth 1 elt)
6762 cmd (orgtbl-make-binding fun key))
6763 (define-key orgtbl-mode-map key cmd)))
6764
6765 ;; Special treatment needed for TAB and RET
6766 ;(define-key orgtbl-mode-map [(return)]
6767 ; (orgtbl-make-binding 'org-table-next-row [(return)] "\C-m"))
6768 ;(define-key orgtbl-mode-map "\C-m"
6769 ; (orgtbl-make-binding 'org-table-next-row "\C-m" [(return)]))
6770 ;(define-key orgtbl-mode-map [(tab)]
6771 ; (orgtbl-make-binding 'org-table-next-field [(tab)] "\C-i"))
6772 ;(define-key orgtbl-mode-map "\C-i"
6773 ; (orgtbl-make-binding 'org-table-next-field "\C-i" [(tab)]))
6774
6775 (define-key orgtbl-mode-map [(return)]
6776 (orgtbl-make-binding 'orgtbl-ret [(return)] "\C-m"))
6777 (define-key orgtbl-mode-map "\C-m"
6778 (orgtbl-make-binding 'orgtbl-ret "\C-m" [(return)]))
6779 (define-key orgtbl-mode-map [(tab)]
6780 (orgtbl-make-binding 'orgtbl-tab [(tab)] "\C-i"))
6781 (define-key orgtbl-mode-map "\C-i"
6782 (orgtbl-make-binding 'orgtbl-tab "\C-i" [(tab)]))
6783
6784 (when orgtbl-optimized
6785 ;; If the user wants maximum table support, we need to hijack
6786 ;; some standard editing functions
6787 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
6788 orgtbl-mode-map global-map)
6789 (substitute-key-definition 'delete-char 'orgtbl-delete-char
6790 orgtbl-mode-map global-map)
6791 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
6792 orgtbl-mode-map global-map)
6793 (define-key org-mode-map "|" 'self-insert-command))
6794
6795 (defun orgtbl-tab ()
6796 "Justification and field motion for `orgtbl-mode'."
6797 (interactive)
6798 (org-table-justify-field-maybe)
6799 (org-table-next-field))
6800
6801 (defun orgtbl-ret ()
6802 "Justification and field motion for `orgtbl-mode'."
6803 (interactive)
6804 (org-table-justify-field-maybe)
6805 (org-table-next-row))
6806
6807 (defun orgtbl-self-insert-command (N)
6808 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
6809 If the cursor is in a table looking at whitespace, the whitespace is
6810 overwritten, and the table is not marked as requiring realignment."
6811 (interactive "p")
6812 (if (and (org-at-table-p)
6813 (eq N 1)
6814 (looking-at "[^|\n]* +|"))
6815 (let (org-table-may-need-update)
6816 (goto-char (1- (match-end 0)))
6817 (delete-backward-char 1)
6818 (goto-char (match-beginning 0))
6819 (self-insert-command N))
6820 (setq org-table-may-need-update t)
6821 (let (orgtbl-mode)
6822 (call-interactively (key-binding (vector last-input-event))))))
6823
6824 (defun orgtbl-delete-backward-char (N)
6825 "Like `delete-backward-char', insert whitespace at field end in tables.
6826 When deleting backwards, in tables this function will insert whitespace in
6827 front of the next \"|\" separator, to keep the table aligned. The table will
6828 still be marked for re-alignment, because a narrow field may lead to a
6829 reduced column width."
6830 (interactive "p")
6831 (if (and (org-at-table-p)
6832 (eq N 1)
6833 (looking-at ".*?|"))
6834 (let ((pos (point)))
6835 (backward-delete-char N)
6836 (skip-chars-forward "^|")
6837 (insert " ")
6838 (goto-char (1- pos)))
6839 (message "%s" last-input-event) (sit-for 1)
6840 (delete-backward-char N)))
6841
6842 (defun orgtbl-delete-char (N)
6843 "Like `delete-char', but insert whitespace at field end in tables.
6844 When deleting characters, in tables this function will insert whitespace in
6845 front of the next \"|\" separator, to keep the table aligned. The table
6846 will still be marked for re-alignment, because a narrow field may lead to
6847 a reduced column width."
6848 (interactive "p")
6849 (if (and (org-at-table-p)
6850 (eq N 1))
6851 (if (looking-at ".*?|")
6852 (let ((pos (point)))
6853 (replace-match (concat
6854 (substring (match-string 0) 1 -1)
6855 " |"))
6856 (goto-char pos)))
6857 (delete-char N)))
6858
6859 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
6860 '("Tbl"
6861 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
6862 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
6863 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
6864 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
6865 "--"
6866 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
6867 ["Copy Field from Above"
6868 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
6869 "--"
6870 ("Column"
6871 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
6872 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
6873 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
6874 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
6875 ("Row"
6876 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
6877 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
6878 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
6879 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
6880 "--"
6881 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
6882 ("Rectangle"
6883 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
6884 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
6885 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
6886 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
6887 "--"
6888 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
6889 ["Sum Column/Rectangle" org-table-sum
6890 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
6891 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
6892 ))
6893
6894 ;;; Exporting
6895
6896 (defconst org-level-max 20)
6897
6898 (defun org-export-find-first-heading-line (list)
6899 "Remove all lines from LIST which are before the first headline."
6900 (let ((orig-list list)
6901 (re (concat "^" outline-regexp)))
6902 (while (and list
6903 (not (string-match re (car list))))
6904 (pop list))
6905 (or list orig-list)))
6906
6907 (defun org-skip-comments (lines)
6908 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
6909 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
6910 (re2 "^\\(\\*+\\)[ \t\n\r]")
6911 rtn line level)
6912 (while (setq line (pop lines))
6913 (cond
6914 ((and (string-match re1 line)
6915 (setq level (- (match-end 1) (match-beginning 1))))
6916 ;; Beginning of a COMMENT subtree. Skip it.
6917 (while (and (setq line (pop lines))
6918 (or (not (string-match re2 line))
6919 (> (- (match-end 1) (match-beginning 1)) level))))
6920 (setq lines (cons line lines)))
6921 ((string-match "^#" line)
6922 ;; an ordinary comment line
6923 )
6924 (t (setq rtn (cons line rtn)))))
6925 (nreverse rtn)))
6926
6927 ;; ASCII
6928
6929 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
6930 "Characters for underlining headings in ASCII export.")
6931
6932 (defconst org-html-entities
6933 '(("nbsp")
6934 ("iexcl")
6935 ("cent")
6936 ("pound")
6937 ("curren")
6938 ("yen")
6939 ("brvbar")
6940 ("sect")
6941 ("uml")
6942 ("copy")
6943 ("ordf")
6944 ("laquo")
6945 ("not")
6946 ("shy")
6947 ("reg")
6948 ("macr")
6949 ("deg")
6950 ("plusmn")
6951 ("sup2")
6952 ("sup3")
6953 ("acute")
6954 ("micro")
6955 ("para")
6956 ("middot")
6957 ("odot"."o")
6958 ("star"."*")
6959 ("cedil")
6960 ("sup1")
6961 ("ordm")
6962 ("raquo")
6963 ("frac14")
6964 ("frac12")
6965 ("frac34")
6966 ("iquest")
6967 ("Agrave")
6968 ("Aacute")
6969 ("Acirc")
6970 ("Atilde")
6971 ("Auml")
6972 ("Aring") ("AA"."&Aring;")
6973 ("AElig")
6974 ("Ccedil")
6975 ("Egrave")
6976 ("Eacute")
6977 ("Ecirc")
6978 ("Euml")
6979 ("Igrave")
6980 ("Iacute")
6981 ("Icirc")
6982 ("Iuml")
6983 ("ETH")
6984 ("Ntilde")
6985 ("Ograve")
6986 ("Oacute")
6987 ("Ocirc")
6988 ("Otilde")
6989 ("Ouml")
6990 ("times")
6991 ("Oslash")
6992 ("Ugrave")
6993 ("Uacute")
6994 ("Ucirc")
6995 ("Uuml")
6996 ("Yacute")
6997 ("THORN")
6998 ("szlig")
6999 ("agrave")
7000 ("aacute")
7001 ("acirc")
7002 ("atilde")
7003 ("auml")
7004 ("aring")
7005 ("aelig")
7006 ("ccedil")
7007 ("egrave")
7008 ("eacute")
7009 ("ecirc")
7010 ("euml")
7011 ("igrave")
7012 ("iacute")
7013 ("icirc")
7014 ("iuml")
7015 ("eth")
7016 ("ntilde")
7017 ("ograve")
7018 ("oacute")
7019 ("ocirc")
7020 ("otilde")
7021 ("ouml")
7022 ("divide")
7023 ("oslash")
7024 ("ugrave")
7025 ("uacute")
7026 ("ucirc")
7027 ("uuml")
7028 ("yacute")
7029 ("thorn")
7030 ("yuml")
7031 ("fnof")
7032 ("Alpha")
7033 ("Beta")
7034 ("Gamma")
7035 ("Delta")
7036 ("Epsilon")
7037 ("Zeta")
7038 ("Eta")
7039 ("Theta")
7040 ("Iota")
7041 ("Kappa")
7042 ("Lambda")
7043 ("Mu")
7044 ("Nu")
7045 ("Xi")
7046 ("Omicron")
7047 ("Pi")
7048 ("Rho")
7049 ("Sigma")
7050 ("Tau")
7051 ("Upsilon")
7052 ("Phi")
7053 ("Chi")
7054 ("Psi")
7055 ("Omega")
7056 ("alpha")
7057 ("beta")
7058 ("gamma")
7059 ("delta")
7060 ("epsilon")
7061 ("varepsilon"."&epsilon;")
7062 ("zeta")
7063 ("eta")
7064 ("theta")
7065 ("iota")
7066 ("kappa")
7067 ("lambda")
7068 ("mu")
7069 ("nu")
7070 ("xi")
7071 ("omicron")
7072 ("pi")
7073 ("rho")
7074 ("sigmaf") ("varsigma"."&sigmaf;")
7075 ("sigma")
7076 ("tau")
7077 ("upsilon")
7078 ("phi")
7079 ("chi")
7080 ("psi")
7081 ("omega")
7082 ("thetasym") ("vartheta"."&thetasym;")
7083 ("upsih")
7084 ("piv")
7085 ("bull") ("bullet"."&bull;")
7086 ("hellip") ("dots"."&hellip;")
7087 ("prime")
7088 ("Prime")
7089 ("oline")
7090 ("frasl")
7091 ("weierp")
7092 ("image")
7093 ("real")
7094 ("trade")
7095 ("alefsym")
7096 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
7097 ("uarr") ("uparrow"."&uarr;")
7098 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
7099 ("darr")("downarrow"."&darr;")
7100 ("harr") ("leftrightarrow"."&harr;")
7101 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
7102 ("lArr") ("Leftarrow"."&lArr;")
7103 ("uArr") ("Uparrow"."&uArr;")
7104 ("rArr") ("Rightarrow"."&rArr;")
7105 ("dArr") ("Downarrow"."&dArr;")
7106 ("hArr") ("Leftrightarrow"."&hArr;")
7107 ("forall")
7108 ("part") ("partial"."&part;")
7109 ("exist") ("exists"."&exist;")
7110 ("empty") ("emptyset"."&empty;")
7111 ("nabla")
7112 ("isin") ("in"."&isin;")
7113 ("notin")
7114 ("ni")
7115 ("prod")
7116 ("sum")
7117 ("minus")
7118 ("lowast") ("ast"."&lowast;")
7119 ("radic")
7120 ("prop") ("proptp"."&prop;")
7121 ("infin") ("infty"."&infin;")
7122 ("ang") ("angle"."&ang;")
7123 ("and") ("vee"."&and;")
7124 ("or") ("wedge"."&or;")
7125 ("cap")
7126 ("cup")
7127 ("int")
7128 ("there4")
7129 ("sim")
7130 ("cong") ("simeq"."&cong;")
7131 ("asymp")("approx"."&asymp;")
7132 ("ne") ("neq"."&ne;")
7133 ("equiv")
7134 ("le")
7135 ("ge")
7136 ("sub") ("subset"."&sub;")
7137 ("sup") ("supset"."&sup;")
7138 ("nsub")
7139 ("sube")
7140 ("supe")
7141 ("oplus")
7142 ("otimes")
7143 ("perp")
7144 ("sdot") ("cdot"."&sdot;")
7145 ("lceil")
7146 ("rceil")
7147 ("lfloor")
7148 ("rfloor")
7149 ("lang")
7150 ("rang")
7151 ("loz") ("Diamond"."&loz;")
7152 ("spades") ("spadesuit"."&spades;")
7153 ("clubs") ("clubsuit"."&clubs;")
7154 ("hearts") ("diamondsuit"."&hearts;")
7155 ("diams") ("diamondsuit"."&diams;")
7156 ("quot")
7157 ("amp")
7158 ("lt")
7159 ("gt")
7160 ("OElig")
7161 ("oelig")
7162 ("Scaron")
7163 ("scaron")
7164 ("Yuml")
7165 ("circ")
7166 ("tilde")
7167 ("ensp")
7168 ("emsp")
7169 ("thinsp")
7170 ("zwnj")
7171 ("zwj")
7172 ("lrm")
7173 ("rlm")
7174 ("ndash")
7175 ("mdash")
7176 ("lsquo")
7177 ("rsquo")
7178 ("sbquo")
7179 ("ldquo")
7180 ("rdquo")
7181 ("bdquo")
7182 ("dagger")
7183 ("Dagger")
7184 ("permil")
7185 ("lsaquo")
7186 ("rsaquo")
7187 ("euro")
7188
7189 ("arccos"."arccos")
7190 ("arcsin"."arcsin")
7191 ("arctan"."arctan")
7192 ("arg"."arg")
7193 ("cos"."cos")
7194 ("cosh"."cosh")
7195 ("cot"."cot")
7196 ("coth"."coth")
7197 ("csc"."csc")
7198 ("deg"."deg")
7199 ("det"."det")
7200 ("dim"."dim")
7201 ("exp"."exp")
7202 ("gcd"."gcd")
7203 ("hom"."hom")
7204 ("inf"."inf")
7205 ("ker"."ker")
7206 ("lg"."lg")
7207 ("lim"."lim")
7208 ("liminf"."liminf")
7209 ("limsup"."limsup")
7210 ("ln"."ln")
7211 ("log"."log")
7212 ("max"."max")
7213 ("min"."min")
7214 ("Pr"."Pr")
7215 ("sec"."sec")
7216 ("sin"."sin")
7217 ("sinh"."sinh")
7218 ("sup"."sup")
7219 ("tan"."tan")
7220 ("tanh"."tanh")
7221 )
7222 "Entities for TeX->HTML translation.
7223 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
7224 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
7225 In that case, \"\\ent\" will be translated to \"&other;\".
7226 The list contains HTML entities for Latin-1, Greek and other symbols.
7227 It is supplemented by a number of commonly used TeX macros with appropriate
7228 translations.")
7229
7230 (defvar org-last-level nil) ; dynamically scoped variable
7231
7232 (defun org-export-as-ascii (arg)
7233 "Export the outline as a pretty ASCII file.
7234 If there is an active region, export only the region.
7235 The prefix ARG specifies how many levels of the outline should become
7236 underlined headlines. The default is 3."
7237 (interactive "P")
7238 (setq-default org-todo-line-regexp org-todo-line-regexp)
7239 (let* ((region
7240 (buffer-substring
7241 (if (org-region-active-p) (region-beginning) (point-min))
7242 (if (org-region-active-p) (region-end) (point-max))))
7243 (lines (org-export-find-first-heading-line
7244 (org-skip-comments (org-split-string region "[\r\n]"))))
7245 (org-startup-with-deadline-check nil)
7246 (level 0) line txt
7247 (umax nil)
7248 (case-fold-search nil)
7249 (filename (concat (file-name-sans-extension (buffer-file-name))
7250 ".txt"))
7251 (buffer (find-file-noselect filename))
7252 (levels-open (make-vector org-level-max nil))
7253 (date (format-time-string "%Y/%m/%d" (current-time)))
7254 (time (format-time-string "%X" (current-time)))
7255 (author user-full-name)
7256 (title (buffer-name))
7257 (options nil)
7258 (email user-mail-address)
7259 (language org-export-default-language)
7260 (text nil)
7261 (todo nil)
7262 (lang-words nil))
7263
7264 (setq org-last-level 1)
7265 (org-init-section-numbers)
7266
7267 (find-file-noselect filename)
7268
7269 ;; Search for the export key lines
7270 (org-parse-key-lines)
7271
7272 (setq lang-words (or (assoc language org-export-language-setup)
7273 (assoc "en" org-export-language-setup)))
7274 (if org-export-ascii-show-new-buffer
7275 (switch-to-buffer-other-window buffer)
7276 (set-buffer buffer))
7277 (erase-buffer)
7278 (fundamental-mode)
7279 (if options (org-parse-export-options options))
7280 (setq umax (if arg (prefix-numeric-value arg)
7281 org-export-headline-levels))
7282
7283 ;; File header
7284 (if title (org-insert-centered title ?=))
7285 (insert "\n")
7286 (if (or author email)
7287 (insert (concat (nth 1 lang-words) ": " (or author "")
7288 (if email (concat " <" email ">") "")
7289 "\n")))
7290 (if (and date time)
7291 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
7292 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
7293
7294 (insert "\n\n")
7295
7296 (if org-export-with-toc
7297 (progn
7298 (insert (nth 3 lang-words) "\n"
7299 (make-string (length (nth 3 lang-words)) ?=) "\n")
7300 (mapcar '(lambda (line)
7301 (if (string-match org-todo-line-regexp
7302 line)
7303 ;; This is a headline
7304 (progn
7305 (setq level (- (match-end 1) (match-beginning 1))
7306 txt (match-string 3 line)
7307 todo
7308 (or (and (match-beginning 2)
7309 (not (equal (match-string 2 line)
7310 org-done-string)))
7311 ; TODO, not DONE
7312 (and (= level umax)
7313 (org-search-todo-below
7314 line lines level))))
7315 (setq txt (org-html-expand-for-ascii txt))
7316
7317 (if org-export-with-section-numbers
7318 (setq txt (concat (org-section-number level)
7319 " " txt)))
7320 (if (<= level umax)
7321 (progn
7322 (insert
7323 (make-string (* (1- level) 4) ?\ )
7324 (format (if todo "%s (*)\n" "%s\n") txt))
7325 (setq org-last-level level))
7326 ))))
7327 lines)))
7328
7329 (org-init-section-numbers)
7330 (while (setq line (pop lines))
7331 ;; Remove the quoted HTML tags.
7332 (setq line (org-html-expand-for-ascii line))
7333 (cond
7334 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
7335 ;; a Headline
7336 (setq level (- (match-end 1) (match-beginning 1))
7337 txt (match-string 2 line))
7338 (org-ascii-level-start level txt umax))
7339 (t (insert line "\n"))))
7340 (normal-mode)
7341 (save-buffer)
7342 (goto-char (point-min))))
7343
7344 (defun org-search-todo-below (line lines level)
7345 "Search the subtree below LINE for any TODO entries."
7346 (let ((rest (cdr (memq line lines)))
7347 (re org-todo-line-regexp)
7348 line lv todo)
7349 (catch 'exit
7350 (while (setq line (pop rest))
7351 (if (string-match re line)
7352 (progn
7353 (setq lv (- (match-end 1) (match-beginning 1))
7354 todo (and (match-beginning 2)
7355 (not (equal (match-string 2 line)
7356 org-done-string))))
7357 ; TODO, not DONE
7358 (if (<= lv level) (throw 'exit nil))
7359 (if todo (throw 'exit t))))))))
7360
7361 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
7362 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
7363 (defun org-html-expand-for-ascii (line)
7364 "Handle quoted HTML for ASCII export."
7365 (if org-export-html-expand
7366 (while (string-match "@<[^<>\n]*>" line)
7367 ;; We just remove the tags for now.
7368 (setq line (replace-match "" nil nil line))))
7369 line)
7370
7371 (defun org-insert-centered (s &optional underline)
7372 "Insert the string S centered and underline it with character UNDERLINE."
7373 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
7374 (insert (make-string ind ?\ ) s "\n")
7375 (if underline
7376 (insert (make-string ind ?\ )
7377 (make-string (length s) underline)
7378 "\n"))))
7379
7380 (defun org-ascii-level-start (level title umax)
7381 "Insert a new level in ASCII export."
7382 (let (char)
7383 (if (> level umax)
7384 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
7385 (if (or (not (equal (char-before) ?\n))
7386 (not (equal (char-before (1- (point))) ?\n)))
7387 (insert "\n"))
7388 (setq char (nth (- umax level) (reverse org-ascii-underline)))
7389 (if org-export-with-section-numbers
7390 (setq title (concat (org-section-number level) " " title)))
7391 (insert title "\n" (make-string (string-width title) char) "\n"))))
7392
7393 (defun org-export-copy-visible ()
7394 "Copy the visible part of the buffer to another buffer, for printing.
7395 Also removes the first line of the buffer if it specifies a mode,
7396 and all options lines."
7397 (interactive)
7398 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
7399 ".txt"))
7400 (buffer (find-file-noselect filename))
7401 (ore (concat
7402 (org-make-options-regexp
7403 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP"
7404 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
7405 (if org-noutline-p "\\(\n\\|$\\)" "")))
7406 s e)
7407 (with-current-buffer buffer
7408 (erase-buffer)
7409 (text-mode))
7410 (save-excursion
7411 (setq s (goto-char (point-min)))
7412 (while (not (= (point) (point-max)))
7413 (goto-char (org-find-invisible))
7414 (append-to-buffer buffer s (point))
7415 (setq s (goto-char (org-find-visible)))))
7416 (switch-to-buffer-other-window buffer)
7417 (newline)
7418 (goto-char (point-min))
7419 (if (looking-at ".*-\\*- mode:.*\n")
7420 (replace-match ""))
7421 (while (re-search-forward ore nil t)
7422 (replace-match ""))
7423 (goto-char (point-min))))
7424
7425 (defun org-find-visible ()
7426 (if (featurep 'noutline)
7427 (let ((s (point)))
7428 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7429 (get-char-property s 'invisible)))
7430 s)
7431 (skip-chars-forward "^\n")
7432 (point)))
7433 (defun org-find-invisible ()
7434 (if (featurep 'noutline)
7435 (let ((s (point)))
7436 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7437 (not (get-char-property s 'invisible))))
7438 s)
7439 (skip-chars-forward "^\r")
7440 (point)))
7441
7442 ;; HTML
7443
7444 (defun org-get-current-options ()
7445 "Return a string with current options as keyword options.
7446 Does include HTML export options as well as TODO and CATEGORY stuff."
7447 (format
7448 "#+TITLE: %s
7449 #+AUTHOR: %s
7450 #+EMAIL: %s
7451 #+LANGUAGE: %s
7452 #+TEXT: Some descriptive text to be emitted. Several lines OK.
7453 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
7454 #+CATEGORY: %s
7455 #+SEQ_TODO: %s
7456 #+TYP_TODO: %s
7457 #+STARTUP: %s %s
7458 "
7459 (buffer-name) (user-full-name) user-mail-address org-export-default-language
7460 org-export-headline-levels
7461 org-export-with-section-numbers
7462 org-export-with-toc
7463 org-export-preserve-breaks
7464 org-export-html-expand
7465 org-export-with-fixed-width
7466 org-export-with-tables
7467 org-export-with-sub-superscripts
7468 org-export-with-emphasize
7469 org-export-with-TeX-macros
7470 (file-name-nondirectory (buffer-file-name))
7471 (if (equal org-todo-interpretation 'sequence)
7472 (mapconcat 'identity org-todo-keywords " ")
7473 "TODO FEEDBACK VERIFY DONE")
7474 (if (equal org-todo-interpretation 'type)
7475 (mapconcat 'identity org-todo-keywords " ")
7476 "Me Jason Marie DONE")
7477 (cdr (assoc org-startup-folded
7478 '((nil . "nofold")(t . "fold")(content . "content"))))
7479 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
7480 ))
7481
7482 (defun org-insert-export-options-template ()
7483 "Insert into the buffer a template with information for exporting."
7484 (interactive)
7485 (if (not (bolp)) (newline))
7486 (let ((s (org-get-current-options)))
7487 (and (string-match "#\\+CATEGORY" s)
7488 (setq s (substring s 0 (match-beginning 0))))
7489 (insert s)))
7490
7491 (defun org-toggle-fixed-width-section (arg)
7492 "Toggle the fixed-width indicator at the beginning of lines in the region.
7493 If there is no active region, only acts on the current line.
7494 If the first non-white character in the first line of the region is a
7495 vertical bar \"|\", then the command removes the bar from all lines in
7496 the region. If the first character is not a bar, the command adds a
7497 bar to all lines, in the column given by the beginning of the region.
7498
7499 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
7500 (interactive "P")
7501 (let* ((cc 0)
7502 (regionp (org-region-active-p))
7503 (beg (if regionp (region-beginning) (point)))
7504 (end (if regionp (region-end)))
7505 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
7506 (re "[ \t]*\\(:\\)")
7507 off)
7508 (save-excursion
7509 (goto-char beg)
7510 (setq cc (current-column))
7511 (beginning-of-line 1)
7512 (setq off (looking-at re))
7513 (while (> nlines 0)
7514 (setq nlines (1- nlines))
7515 (beginning-of-line 1)
7516 (cond
7517 (arg
7518 (move-to-column cc t)
7519 (insert ":\n")
7520 (forward-line -1))
7521 ((and off (looking-at re))
7522 (replace-match "" t t nil 1))
7523 ((not off) (move-to-column cc t) (insert ":")))
7524 (forward-line 1)))))
7525
7526 (defun org-export-as-html-and-open (arg)
7527 "Export the outline as HTML and immediately open it with a browser.
7528 If there is an active region, export only the region.
7529 The prefix ARG specifies how many levels of the outline should become
7530 headlines. The default is 3. Lower levels will become bulleted lists."
7531 (interactive "P")
7532 (org-export-as-html arg 'hidden)
7533 (org-open-file (buffer-file-name)))
7534
7535 (defun org-export-as-html-batch ()
7536 "Call `org-export-as-html', may be used in batch processing as
7537 emacs --batch
7538 --load=$HOME/lib/emacs/org.el
7539 --eval \"(setq org-export-headline-levels 2)\"
7540 --visit=MyFile --funcall org-export-as-html-batch"
7541 (org-export-as-html org-export-headline-levels 'hidden))
7542
7543 (defun org-export-as-html (arg &optional hidden)
7544 "Export the outline as a pretty HTML file.
7545 If there is an active region, export only the region.
7546 The prefix ARG specifies how many levels of the outline should become
7547 headlines. The default is 3. Lower levels will become bulleted lists."
7548 (interactive "P")
7549 (setq-default org-todo-line-regexp org-todo-line-regexp)
7550 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
7551 (setq-default org-done-string org-done-string)
7552 (let* ((region-p (org-region-active-p))
7553 (region
7554 (buffer-substring
7555 (if region-p (region-beginning) (point-min))
7556 (if region-p (region-end) (point-max))))
7557 (all_lines
7558 (org-skip-comments (org-split-string region "[\r\n]")))
7559 (lines (org-export-find-first-heading-line all_lines))
7560 (level 0) (line "") (origline "") txt todo
7561 (umax nil)
7562 (filename (concat (file-name-sans-extension (buffer-file-name))
7563 ".html"))
7564 (buffer (find-file-noselect filename))
7565 (levels-open (make-vector org-level-max nil))
7566 (date (format-time-string "%Y/%m/%d" (current-time)))
7567 (time (format-time-string "%X" (current-time)))
7568 (author user-full-name)
7569 (title (buffer-name))
7570 (options nil)
7571 (email user-mail-address)
7572 (language org-export-default-language)
7573 (text nil)
7574 (lang-words nil)
7575 (head-count 0) cnt
7576 table-open type
7577 table-buffer table-orig-buffer
7578 )
7579 (message "Exporting...")
7580
7581 (setq org-last-level 1)
7582 (org-init-section-numbers)
7583
7584 ;; Search for the export key lines
7585 (org-parse-key-lines)
7586 (setq lang-words (or (assoc language org-export-language-setup)
7587 (assoc "en" org-export-language-setup)))
7588
7589 ;; Switch to the output buffer
7590 (if (or hidden (not org-export-html-show-new-buffer))
7591 (set-buffer buffer)
7592 (switch-to-buffer-other-window buffer))
7593 (erase-buffer)
7594 (fundamental-mode)
7595 (let ((case-fold-search nil))
7596 (if options (org-parse-export-options options))
7597 (setq umax (if arg (prefix-numeric-value arg)
7598 org-export-headline-levels))
7599
7600 ;; File header
7601 (insert (format
7602 "<html lang=\"%s\"><head>
7603 <title>%s</title>
7604 <meta http-equiv=\"Content-Type\" content=\"text/html\">
7605 <meta name=generator content=\"Org-mode\">
7606 <meta name=generated content=\"%s %s\">
7607 <meta name=author content=\"%s\">
7608 </head><body>
7609 "
7610 language (org-html-expand title) date time author))
7611 (if title (insert (concat "<H1 align=\"center\">"
7612 (org-html-expand title) "</H1>\n")))
7613 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
7614 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
7615 email "&gt;</a>\n")))
7616 (if (or author email) (insert "<br>\n"))
7617 (if (and date time) (insert (concat (nth 2 lang-words) ": "
7618 date " " time "<br>\n")))
7619 (if text (insert (concat "<p>\n" (org-html-expand text))))
7620 (if org-export-with-toc
7621 (progn
7622 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
7623 (insert "<ul>\n")
7624 (mapcar '(lambda (line)
7625 (if (string-match org-todo-line-regexp line)
7626 ;; This is a headline
7627 (progn
7628 (setq level (- (match-end 1) (match-beginning 1))
7629 txt (save-match-data
7630 (org-html-expand
7631 (match-string 3 line)))
7632 todo
7633 (or (and (match-beginning 2)
7634 (not (equal (match-string 2 line)
7635 org-done-string)))
7636 ; TODO, not DONE
7637 (and (= level umax)
7638 (org-search-todo-below
7639 line lines level))))
7640 (if org-export-with-section-numbers
7641 (setq txt (concat (org-section-number level)
7642 " " txt)))
7643 (if (<= level umax)
7644 (progn
7645 (setq head-count (+ head-count 1))
7646 (if (> level org-last-level)
7647 (progn
7648 (setq cnt (- level org-last-level))
7649 (while (>= (setq cnt (1- cnt)) 0)
7650 (insert "<ul>"))
7651 (insert "\n")))
7652 (if (< level org-last-level)
7653 (progn
7654 (setq cnt (- org-last-level level))
7655 (while (>= (setq cnt (1- cnt)) 0)
7656 (insert "</ul>"))
7657 (insert "\n")))
7658 (insert
7659 (format
7660 (if todo
7661 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
7662 "<li><a href=\"#sec-%d\">%s</a></li>\n")
7663 head-count txt))
7664 (setq org-last-level level))
7665 ))))
7666 lines)
7667 (while (> org-last-level 0)
7668 (setq org-last-level (1- org-last-level))
7669 (insert "</ul>\n"))
7670 ))
7671 (setq head-count 0)
7672 (org-init-section-numbers)
7673
7674 (while (setq line (pop lines) origline line)
7675 ;; replace "<" and ">" by "&lt;" and "&gt;"
7676 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
7677 (setq line (org-html-expand line))
7678
7679 ;; Verbatim lines
7680 (if (and org-export-with-fixed-width
7681 (string-match "^[ \t]*:\\(.*\\)" line))
7682 (progn
7683 (let ((l (match-string 1 line)))
7684 (while (string-match " " l)
7685 (setq l (replace-match "&nbsp;" t t l)))
7686 (insert "\n<span style='font-family:Courier'>"
7687 l "</span>"
7688 (if (and lines
7689 (not (string-match "^[ \t]+\\(:.*\\)"
7690 (car lines))))
7691 "<br>\n" "\n"))))
7692
7693 (when (string-match org-link-regexp line)
7694 (setq type (match-string 1 line))
7695 (cond
7696 ((member type '("http" "https" "ftp" "mailto" "news"))
7697 ;; standard URL
7698 (setq line (replace-match
7699 "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
7700 nil nil line)))
7701 ((string= type "file")
7702 ;; FILE link
7703
7704 (let* ((filename (match-string 2 line))
7705 (file-is-image-p
7706 (save-match-data
7707 (string-match (org-image-file-name-regexp) filename))))
7708 (setq line (replace-match
7709 (if (and org-export-html-inline-images
7710 file-is-image-p)
7711 "<img src=\"\\2\"/>"
7712 "<a href=\"\\2\">\\1:\\2</a>")
7713 nil nil line))))
7714
7715 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
7716 (setq line (replace-match
7717 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
7718
7719 ;; TODO items
7720 (if (and (string-match org-todo-line-regexp line)
7721 (match-beginning 2))
7722 (if (equal (match-string 2 line) org-done-string)
7723 (setq line (replace-match
7724 "<span style='color:green'>\\2</span>"
7725 nil nil line 2))
7726 (setq line (replace-match "<span style='color:red'>\\2</span>"
7727 nil nil line 2))))
7728
7729 ;; DEADLINES
7730 (if (string-match org-deadline-line-regexp line)
7731 (progn
7732 (if (save-match-data
7733 (string-match "<a href"
7734 (substring line 0 (match-beginning 0))))
7735 nil ; Don't do the replacement - it is inside a link
7736 (setq line (replace-match "<span style='color:red'>\\&</span>"
7737 nil nil line 1)))))
7738
7739 (cond
7740 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
7741 ;; This is a headline
7742 (setq level (- (match-end 1) (match-beginning 1))
7743 txt (match-string 2 line))
7744 (if (<= level umax) (setq head-count (+ head-count 1)))
7745 (org-html-level-start level txt umax
7746 (and org-export-with-toc (<= level umax))
7747 head-count))
7748
7749 ((and org-export-with-tables
7750 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
7751 (if (not table-open)
7752 ;; New table starts
7753 (setq table-open t table-buffer nil table-orig-buffer nil))
7754 ;; Accumulate lines
7755 (setq table-buffer (cons line table-buffer)
7756 table-orig-buffer (cons origline table-orig-buffer))
7757 (when (or (not lines)
7758 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
7759 (car lines))))
7760 (setq table-open nil
7761 table-buffer (nreverse table-buffer)
7762 table-orig-buffer (nreverse table-orig-buffer))
7763 (insert (org-format-table-html table-buffer table-orig-buffer))))
7764 (t
7765 ;; Normal lines
7766 ;; Lines starting with "-", and empty lines make new paragraph.
7767 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
7768 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
7769 ))
7770 (if org-export-html-with-timestamp
7771 (insert org-export-html-html-helper-timestamp))
7772 (insert "</body>\n</html>\n")
7773 (normal-mode)
7774 (save-buffer)
7775 (goto-char (point-min)))))
7776
7777 (defun org-format-table-html (lines olines)
7778 "Find out which HTML converter to use and return the HTML code."
7779 (if (string-match "^[ \t]*|" (car lines))
7780 ;; A normal org table
7781 (org-format-org-table-html lines)
7782 ;; Table made by table.el - test for spanning
7783 (let* ((hlines (delq nil (mapcar
7784 (lambda (x)
7785 (if (string-match "^[ \t]*\\+-" x) x
7786 nil))
7787 lines)))
7788 (first (car hlines))
7789 (ll (and (string-match "\\S-+" first)
7790 (match-string 0 first)))
7791 (re (concat "^[ \t]*" (regexp-quote ll)))
7792 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
7793 hlines))))
7794 (if (and (not spanning)
7795 (not org-export-prefer-native-exporter-for-tables))
7796 ;; We can use my own converter with HTML conversions
7797 (org-format-table-table-html lines)
7798 ;; Need to use the code generator in table.el, with the original text.
7799 (org-format-table-table-html-using-table-generate-source olines)))))
7800
7801 (defun org-format-org-table-html (lines)
7802 "Format a table into html."
7803 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7804 (setq lines (nreverse lines))
7805 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7806 (setq lines (nreverse lines))
7807 (let ((head (and org-export-highlight-first-table-line
7808 (delq nil (mapcar
7809 (lambda (x) (string-match "^[ \t]*|-" x))
7810 lines))))
7811 lastline line fields html empty)
7812 (setq html (concat org-export-html-table-tag "\n"))
7813 (while (setq lastline line
7814 line (pop lines))
7815 (setq empty "&nbsp")
7816 (catch 'next-line
7817 (if (string-match "^[ \t]*|-" line)
7818 (if lastline
7819 ;; A hline: simulate an empty table row instead.
7820 (setq line (org-fake-empty-table-line lastline)
7821 head nil
7822 empty "")
7823 ;; Ignore this line
7824 (throw 'next-line t)))
7825 ;; Break the line into fields
7826 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7827 (setq html (concat
7828 html
7829 "<tr>"
7830 (mapconcat (lambda (x)
7831 (if (equal x "") (setq x empty))
7832 (if head
7833 (concat "<th>" x "</th>")
7834 (concat "<td valign=\"top\">" x "</td>")))
7835 fields "")
7836 "</tr>\n"))))
7837 (setq html (concat html "</table>\n"))
7838 html))
7839
7840 (defun org-fake-empty-table-line (line)
7841 "Replace everything except \"|\" with spaces."
7842 (let ((i (length line))
7843 (newstr (copy-sequence line)))
7844 (while (> i 0)
7845 (setq i (1- i))
7846 (if (not (eq (aref newstr i) ?|))
7847 (aset newstr i ?\ )))
7848 newstr))
7849
7850 (defun org-format-table-table-html (lines)
7851 "Format a table generated by table.el into html.
7852 This conversion does *not* use `table-generate-source' from table.el.
7853 This has the advantage that Org-mode's HTML conversions can be used.
7854 But it has the disadvantage, that no cell- or row-spanning is allowed."
7855 (let (line field-buffer
7856 (head org-export-highlight-first-table-line)
7857 fields html empty)
7858 (setq html (concat org-export-html-table-tag "\n"))
7859 (while (setq line (pop lines))
7860 (setq empty "&nbsp")
7861 (catch 'next-line
7862 (if (string-match "^[ \t]*\\+-" line)
7863 (progn
7864 (if field-buffer
7865 (progn
7866 (setq html (concat
7867 html
7868 "<tr>"
7869 (mapconcat
7870 (lambda (x)
7871 (if (equal x "") (setq x empty))
7872 (if head
7873 (concat "<th valign=\"top\">" x
7874 "</th>\n")
7875 (concat "<td valign=\"top\">" x
7876 "</td>\n")))
7877 field-buffer "\n")
7878 "</tr>\n"))
7879 (setq head nil)
7880 (setq field-buffer nil)))
7881 ;; Ignore this line
7882 (throw 'next-line t)))
7883 ;; Break the line into fields and store the fields
7884 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7885 (if field-buffer
7886 (setq field-buffer (mapcar
7887 (lambda (x)
7888 (concat x "<br>" (pop fields)))
7889 field-buffer))
7890 (setq field-buffer fields))))
7891 (setq html (concat html "</table>\n"))
7892 html))
7893
7894 (defun org-format-table-table-html-using-table-generate-source (lines)
7895 "Format a table into html, using `table-generate-source' from table.el.
7896 This has the advantage that cell- or row-spanning is allowed.
7897 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
7898 (require 'table)
7899 (with-current-buffer (get-buffer-create " org-tmp1 ")
7900 (erase-buffer)
7901 (insert (mapconcat 'identity lines "\n"))
7902 (goto-char (point-min))
7903 (if (not (re-search-forward "|[^+]" nil t))
7904 (error "Error processing table."))
7905 (table-recognize-table)
7906 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
7907 (table-generate-source 'html " org-tmp2 ")
7908 (set-buffer " org-tmp2 ")
7909 (buffer-substring (point-min) (point-max))))
7910
7911 (defun org-html-expand (string)
7912 "Prepare STRING for HTML export. Applies all active conversions."
7913 ;; First check if there is a link in the line - if yes, apply conversions
7914 ;; only before the start of the link.
7915 (let* ((m (string-match org-link-regexp string))
7916 (s (if m (substring string 0 m) string))
7917 (r (if m (substring string m) "")))
7918 ;; convert < to &lt; and > to &gt;
7919 (while (string-match "<" s)
7920 (setq s (replace-match "&lt;" nil nil s)))
7921 (while (string-match ">" s)
7922 (setq s (replace-match "&gt;" nil nil s)))
7923 (if org-export-html-expand
7924 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
7925 (setq s (replace-match "<\\1>" nil nil s))))
7926 (if org-export-with-emphasize
7927 (setq s (org-export-html-convert-emphasize s)))
7928 (if org-export-with-sub-superscripts
7929 (setq s (org-export-html-convert-sub-super s)))
7930 (if org-export-with-TeX-macros
7931 (let ((start 0) wd ass)
7932 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
7933 (setq wd (match-string 1 s))
7934 (if (setq ass (assoc wd org-html-entities))
7935 (setq s (replace-match (or (cdr ass)
7936 (concat "&" (car ass) ";"))
7937 t t s))
7938 (setq start (+ start (length wd)))))))
7939 (concat s r)))
7940
7941 (defun org-create-multibrace-regexp (left right n)
7942 "Create a regular expression which will match a balanced sexp.
7943 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
7944 as single character strings.
7945 The regexp returned will match the entire expression including the
7946 delimiters. It will also define a single group which contains the
7947 match except for the outermost delimiters. The maximum depth of
7948 stacked delimiters is N. Escaping delimiters is not possible."
7949 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
7950 (or "\\|")
7951 (re nothing)
7952 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
7953 (while (> n 1)
7954 (setq n (1- n)
7955 re (concat re or next)
7956 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
7957 (concat left "\\(" re "\\)" right)))
7958
7959 (defvar org-match-substring-regexp
7960 (concat
7961 "\\([^\\]\\)\\([_^]\\)\\("
7962 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
7963 "\\|"
7964 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
7965 "\\|"
7966 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
7967 "The regular expression matching a sub- or superscript.")
7968
7969 (defun org-export-html-convert-sub-super (string)
7970 "Convert sub- and superscripts in STRING to HTML."
7971 (let (key c)
7972 (while (string-match org-match-substring-regexp string)
7973 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
7974 (setq c (or (match-string 8 string)
7975 (match-string 6 string)
7976 (match-string 5 string)))
7977 (setq string (replace-match
7978 (concat (match-string 1 string)
7979 "<" key ">" c "</" key ">")
7980 t t string)))
7981 (while (string-match "\\\\\\([_^]\\)" string)
7982 (setq string (replace-match (match-string 1 string) t t string))))
7983 string)
7984
7985 (defun org-export-html-convert-emphasize (string)
7986 (while (string-match
7987 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
7988 string)
7989 (setq string (replace-match
7990 (concat "<b>" (match-string 3 string) "</b>")
7991 t t string 2)))
7992 (while (string-match
7993 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
7994 string)
7995 (setq string (replace-match
7996 (concat "<i>" (match-string 3 string) "</i>")
7997 t t string 2)))
7998 (while (string-match
7999 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
8000 string)
8001 (setq string (replace-match
8002 (concat "<u>" (match-string 3 string) "</u>")
8003 t t string 2)))
8004 string)
8005
8006 (defun org-parse-key-lines ()
8007 "Find the special key lines with the information for exporters."
8008 (save-excursion
8009 (goto-char 0)
8010 (let ((re (org-make-options-regexp
8011 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
8012 key)
8013 (while (re-search-forward re nil t)
8014 (setq key (match-string 1))
8015 (cond ((string-equal key "TITLE")
8016 (setq title (match-string 2)))
8017 ((string-equal key "AUTHOR")
8018 (setq author (match-string 2)))
8019 ((string-equal key "EMAIL")
8020 (setq email (match-string 2)))
8021 ((string-equal key "LANGUAGE")
8022 (setq language (match-string 2)))
8023 ((string-equal key "TEXT")
8024 (setq text (concat text "\n" (match-string 2))))
8025 ((string-equal key "OPTIONS")
8026 (setq options (match-string 2))))))))
8027
8028 (defun org-parse-export-options (s)
8029 "Parse the export options line."
8030 (let ((op '(("H" . org-export-headline-levels)
8031 ("num" . org-export-with-section-numbers)
8032 ("toc" . org-export-with-toc)
8033 ("\\n" . org-export-preserve-breaks)
8034 ("@" . org-export-html-expand)
8035 (":" . org-export-with-fixed-width)
8036 ("|" . org-export-with-tables)
8037 ("^" . org-export-with-sub-superscripts)
8038 ("*" . org-export-with-emphasize)
8039 ("TeX" . org-export-with-TeX-macros)))
8040 o)
8041 (while (setq o (pop op))
8042 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
8043 s)
8044 (set (make-local-variable (cdr o))
8045 (car (read-from-string (match-string 1 s))))))))
8046
8047 (defun org-html-level-start (level title umax with-toc head-count)
8048 "Insert a new level in HTML export."
8049 (let ((l (1+ (max level umax))))
8050 (while (<= l org-level-max)
8051 (if (aref levels-open (1- l))
8052 (progn
8053 (org-html-level-close l)
8054 (aset levels-open (1- l) nil)))
8055 (setq l (1+ l)))
8056 (if (> level umax)
8057 (progn
8058 (if (aref levels-open (1- level))
8059 (insert "<li>" title "<p>\n")
8060 (aset levels-open (1- level) t)
8061 (insert "<ul><li>" title "<p>\n")))
8062 (if org-export-with-section-numbers
8063 (setq title (concat (org-section-number level) " " title)))
8064 (setq level (+ level 1))
8065 (if with-toc
8066 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
8067 level head-count title level))
8068 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
8069
8070 (defun org-html-level-close (&rest args)
8071 "Terminate one level in HTML export."
8072 (insert "</ul>"))
8073
8074
8075 ;; Variable holding the vector with section numbers
8076 (defvar org-section-numbers (make-vector org-level-max 0))
8077
8078 (defun org-init-section-numbers ()
8079 "Initialize the vector for the section numbers."
8080 (let* ((level -1)
8081 (numbers (nreverse (org-split-string "" "\\.")))
8082 (depth (1- (length org-section-numbers)))
8083 (i depth) number-string)
8084 (while (>= i 0)
8085 (if (> i level)
8086 (aset org-section-numbers i 0)
8087 (setq number-string (or (car numbers) "0"))
8088 (if (string-match "\\`[A-Z]\\'" number-string)
8089 (aset org-section-numbers i
8090 (- (string-to-char number-string) ?A -1))
8091 (aset org-section-numbers i (string-to-int number-string)))
8092 (pop numbers))
8093 (setq i (1- i)))))
8094
8095 (defun org-section-number (&optional level)
8096 "Return a string with the current section number.
8097 When LEVEL is non-nil, increase section numbers on that level."
8098 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
8099 (when level
8100 (when (> level -1)
8101 (aset org-section-numbers
8102 level (1+ (aref org-section-numbers level))))
8103 (setq idx (1+ level))
8104 (while (<= idx depth)
8105 (if (not (= idx 1))
8106 (aset org-section-numbers idx 0))
8107 (setq idx (1+ idx))))
8108 (setq idx 0)
8109 (while (<= idx depth)
8110 (setq n (aref org-section-numbers idx))
8111 (setq string (concat string (if (not (string= string "")) "." "")
8112 (int-to-string n)))
8113 (setq idx (1+ idx)))
8114 (save-match-data
8115 (if (string-match "\\`\\([@0]\\.\\)+" string)
8116 (setq string (replace-match "" nil nil string)))
8117 (if (string-match "\\(\\.0\\)+\\'" string)
8118 (setq string (replace-match "" nil nil string))))
8119 string))
8120
8121
8122 ;;; Key bindings
8123
8124 ;; - Bindings in Org-mode map are currently
8125 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
8126 ;; abcd fgh j lmnopqrstuvwxyz ? # -+ /= [] ; |,.<> \t necessary bindings
8127 ;; e (?) useful from outline-mode
8128 ;; i k @ expendable from outline-mode
8129 ;; 0123456789 ! $%^& * ()_{} " ~`' free
8130
8131 (define-key org-mode-map [(tab)] 'org-cycle)
8132 (define-key org-mode-map "\C-i" 'org-cycle)
8133 (define-key org-mode-map [(meta tab)] 'org-complete)
8134 (define-key org-mode-map "\M-\C-i" 'org-complete)
8135 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
8136 (define-key org-mode-map [(meta left)] 'org-metaleft)
8137 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
8138 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
8139 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
8140 (define-key org-mode-map [(meta right)] 'org-metaright)
8141 (define-key org-mode-map [(meta up)] 'org-metaup)
8142 (define-key org-mode-map [(meta down)] 'org-metadown)
8143 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
8144 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
8145 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
8146 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
8147 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
8148 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
8149 (define-key org-mode-map "\C-c\C-j" 'org-goto)
8150 (define-key org-mode-map "\C-c\C-t" 'org-todo)
8151 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
8152 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
8153 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
8154 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
8155 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
8156 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
8157 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
8158 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
8159 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
8160 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
8161 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
8162 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
8163 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
8164 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
8165 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
8166 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
8167 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
8168 (define-key org-mode-map "\C-c[" 'org-add-file)
8169 (define-key org-mode-map "\C-c]" 'org-remove-file)
8170 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
8171 (define-key org-mode-map [(shift up)] 'org-shiftup)
8172 (define-key org-mode-map [(shift down)] 'org-shiftdown)
8173 (define-key org-mode-map [(shift left)] 'org-timestamp-down-day)
8174 (define-key org-mode-map [(shift right)] 'org-timestamp-up-day)
8175 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
8176 ;; The following line is e.g. necessary for German keyboards under Suse Linux
8177 (unless org-xemacs-p
8178 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
8179 (define-key org-mode-map [(shift tab)] 'org-shifttab)
8180 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
8181 (define-key org-mode-map [(return)] 'org-return)
8182 (define-key org-mode-map [(shift return)] 'org-table-copy-down)
8183 (define-key org-mode-map [(meta return)] 'org-meta-return)
8184 (define-key org-mode-map [(control up)] 'org-move-line-up)
8185 (define-key org-mode-map [(control down)] 'org-move-line-down)
8186 (define-key org-mode-map "\C-c?" 'org-table-current-column)
8187 (define-key org-mode-map "\C-c " 'org-table-blank-field)
8188 (define-key org-mode-map "\C-c+" 'org-table-sum)
8189 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
8190 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
8191 (define-key org-mode-map "\C-c#" 'org-table-create-with-table.el)
8192 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
8193 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
8194 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
8195 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
8196 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
8197 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
8198 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
8199 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
8200 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
8201 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
8202 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
8203
8204
8205 ;; FIXME: Do we really need to save match data in these commands?
8206 ;; I would like to remove it in order to minimize impact.
8207 ;; Self-insert already does not preserve it. How much resources used by this???
8208
8209 (defsubst org-table-p ()
8210 (if (and (eq major-mode 'org-mode) font-lock-mode)
8211 (eq (get-text-property (point) 'face) 'org-table-face)
8212 (save-match-data (org-at-table-p))))
8213
8214 (defun org-self-insert-command (N)
8215 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8216 If the cursor is in a table looking at whitespace, the whitespace is
8217 overwritten, and the table is not marked as requiring realignment."
8218 (interactive "p")
8219 (if (and (org-table-p)
8220 (eq N 1)
8221 (looking-at "[^|\n]* +|"))
8222 (let (org-table-may-need-update)
8223 (goto-char (1- (match-end 0)))
8224 (delete-backward-char 1)
8225 (goto-char (match-beginning 0))
8226 (self-insert-command N))
8227 (setq org-table-may-need-update t)
8228 (self-insert-command N)))
8229
8230 ;; FIXME:
8231 ;; The following two functions might still be optimized to trigger
8232 ;; re-alignment less frequently.
8233
8234 (defun org-delete-backward-char (N)
8235 "Like `delete-backward-char', insert whitespace at field end in tables.
8236 When deleting backwards, in tables this function will insert whitespace in
8237 front of the next \"|\" separator, to keep the table aligned. The table will
8238 still be marked for re-alignment, because a narrow field may lead to a
8239 reduced column width."
8240 (interactive "p")
8241 (if (and (org-table-p)
8242 (eq N 1)
8243 (looking-at ".*?|"))
8244 (let ((pos (point)))
8245 (backward-delete-char N)
8246 (skip-chars-forward "^|")
8247 (insert " ")
8248 (goto-char (1- pos)))
8249 (backward-delete-char N)))
8250
8251 (defun org-delete-char (N)
8252 "Like `delete-char', but insert whitespace at field end in tables.
8253 When deleting characters, in tables this function will insert whitespace in
8254 front of the next \"|\" separator, to keep the table aligned. The table
8255 will still be marked for re-alignment, because a narrow field may lead to
8256 a reduced column width."
8257 (interactive "p")
8258 (if (and (org-table-p)
8259 (eq N 1))
8260 (if (looking-at ".*?|")
8261 (let ((pos (point)))
8262 (replace-match (concat
8263 (substring (match-string 0) 1 -1)
8264 " |"))
8265 (goto-char pos)))
8266 (delete-char N)))
8267
8268 ;; How to do this: Measure non-white length of current string
8269 ;; If equal to column width, we should realign.
8270
8271 (when (eq org-enable-table-editor 'optimized)
8272 ;; If the user wants maximum table support, we need to hijack
8273 ;; some standard editing functions
8274 (substitute-key-definition 'self-insert-command 'org-self-insert-command
8275 org-mode-map global-map)
8276 (substitute-key-definition 'delete-char 'org-delete-char
8277 org-mode-map global-map)
8278 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
8279 org-mode-map global-map)
8280 (define-key org-mode-map "|" 'self-insert-command))
8281
8282 (defun org-shiftcursor-error ()
8283 "Throw an error because Shift-Cursor command was applied in wrong context."
8284 (error "This command is only active in tables and on headlines."))
8285
8286 (defun org-shifttab ()
8287 "Call `(org-cycle t)' or `org-table-previous-field'."
8288 (interactive)
8289 (cond
8290 ((org-at-table-p) (org-table-previous-field))
8291 (t (org-cycle '(4)))))
8292
8293 (defun org-shiftmetaleft ()
8294 "Call `org-promote-subtree' or `org-table-delete-column'."
8295 (interactive)
8296 (cond
8297 ((org-at-table-p) (org-table-delete-column))
8298 ((org-on-heading-p) (org-promote-subtree))
8299 (t (org-shiftcursor-error))))
8300
8301 (defun org-shiftmetaright ()
8302 "Call `org-demote-subtree' or `org-table-insert-column'."
8303 (interactive)
8304 (cond
8305 ((org-at-table-p) (org-table-insert-column))
8306 ((org-on-heading-p) (org-demote-subtree))
8307 (t (org-shiftcursor-error))))
8308
8309 (defun org-shiftmetaup (&optional arg)
8310 "Call `org-move-subtree-up' or `org-table-kill-row'."
8311 (interactive "P")
8312 (cond
8313 ((org-at-table-p) (org-table-kill-row))
8314 ((org-on-heading-p) (org-move-subtree-up arg))
8315 (t (org-shiftcursor-error))))
8316 (defun org-shiftmetadown (&optional arg)
8317 "Call `org-move-subtree-down' or `org-table-insert-row'."
8318 (interactive "P")
8319 (cond
8320 ((org-at-table-p) (org-table-insert-row arg))
8321 ((org-on-heading-p) (org-move-subtree-down arg))
8322 (t (org-shiftcursor-error))))
8323
8324 (defun org-metaleft (&optional arg)
8325 "Call `org-do-promote' or `org-table-move-column' to left."
8326 (interactive "P")
8327 (cond
8328 ((org-at-table-p) (org-table-move-column 'left))
8329 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
8330 (t (backward-word (prefix-numeric-value arg)))))
8331
8332 (defun org-metaright (&optional arg)
8333 "Call `org-do-demote' or `org-table-move-column' to right."
8334 (interactive "P")
8335 (cond
8336 ((org-at-table-p) (org-table-move-column nil))
8337 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
8338 (t (forward-word (prefix-numeric-value arg)))))
8339
8340 (defun org-metaup (&optional arg)
8341 "Call `org-move-subtree-up' or `org-table-move-row' up."
8342 (interactive "P")
8343 (cond
8344 ((org-at-table-p) (org-table-move-row 'up))
8345 ((org-on-heading-p) (org-move-subtree-up arg))
8346 (t (org-shiftcursor-error))))
8347
8348 (defun org-metadown (&optional arg)
8349 "Call `org-move-subtree-down' or `org-table-move-row' down."
8350 (interactive "P")
8351 (cond
8352 ((org-at-table-p) (org-table-move-row nil))
8353 ((org-on-heading-p) (org-move-subtree-down arg))
8354 (t (org-shiftcursor-error))))
8355
8356 (defun org-shiftup (&optional arg)
8357 "Call `org-timestamp-up' or `org-priority-up'."
8358 (interactive "P")
8359 (cond
8360 ((org-at-timestamp-p) (org-timestamp-up arg))
8361 (t (org-priority-up))))
8362
8363 (defun org-shiftdown (&optional arg)
8364 "Call `org-timestamp-down' or `org-priority-down'."
8365 (interactive "P")
8366 (cond
8367 ((org-at-timestamp-p) (org-timestamp-down arg))
8368 (t (org-priority-down))))
8369
8370 (defun org-copy-special ()
8371 "Call either `org-table-copy' or `org-copy-subtree'."
8372 (interactive)
8373 (if (org-at-table-p)
8374 (org-table-copy-region)
8375 (org-copy-subtree)))
8376
8377 (defun org-cut-special ()
8378 "Call either `org-table-copy' or `org-cut-subtree'."
8379 (interactive)
8380 (if (org-at-table-p)
8381 (org-table-cut-region)
8382 (org-cut-subtree)))
8383
8384 (defun org-paste-special (arg)
8385 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
8386 (interactive "P")
8387 (if (org-at-table-p)
8388 (org-table-paste-rectangle)
8389 (org-paste-subtree arg)))
8390
8391 (defun org-ctrl-c-ctrl-c (&optional arg)
8392 "Call realign table, or recognize a table.el table.
8393 When the cursor is inside a table created by the table.el package,
8394 activate that table. Otherwise, if the cursor is at a normal table
8395 created with org.el, re-align that table. This command works even if
8396 the automatic table editor has been turned off."
8397 (interactive "P")
8398 (let ((org-enable-table-editor t))
8399 (cond
8400 ((org-at-table.el-p)
8401 (require 'table)
8402 (beginning-of-line 1)
8403 (re-search-forward "|" (save-excursion (end-of-line 2) (point))) ;FIXME: line-end-position?
8404 (table-recognize-table))
8405 ((org-at-table-p)
8406 (org-table-align))
8407 ((save-excursion (beginning-of-line 1) (looking-at "#\\+[A-Z]+"))
8408 (let ((org-inhibit-startup t)) (org-mode)))
8409 ((org-region-active-p)
8410 (org-table-convert-region (region-beginning) (region-end) arg))
8411 ((and (region-beginning) (region-end))
8412 (if (y-or-n-p "Convert inactive region to table? ")
8413 (org-table-convert-region (region-beginning) (region-end) arg)
8414 (error "Abort")))
8415 (t (error "No table at point, and no region to make one.")))))
8416
8417 (defun org-return ()
8418 "Call `org-table-next-row' or `newline'."
8419 (interactive)
8420 (cond
8421 ((org-at-table-p)
8422 (org-table-justify-field-maybe)
8423 (org-table-next-row))
8424 (t (newline))))
8425
8426 (defun org-meta-return (&optional arg)
8427 "Call `org-insert-heading' or `org-table-wrap-region'."
8428 (interactive "P")
8429 (cond
8430 ((org-at-table-p)
8431 (org-table-wrap-region arg))
8432 (t (org-insert-heading))))
8433
8434 ;;; Menu entries
8435
8436 ;; First, remove the outline menus.
8437 (if org-xemacs-p
8438 (add-hook 'org-mode-hook
8439 (lambda ()
8440 (delete-menu-item '("Headings"))
8441 (delete-menu-item '("Show"))
8442 (delete-menu-item '("Hide"))
8443 (set-menubar-dirty-flag)))
8444 (setq org-mode-map (delq (assoc 'menu-bar (cdr org-mode-map))
8445 org-mode-map)))
8446
8447 ;; Define the Org-mode menus
8448 (easy-menu-define org-org-menu org-mode-map "Org menu"
8449 '("Org"
8450 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
8451 ["Sparse Tree" org-occur t]
8452 ["Show All" show-all t]
8453 "--"
8454 ["New Heading" org-insert-heading t]
8455 ("Navigate Headings"
8456 ["Up" outline-up-heading t]
8457 ["Next" outline-next-visible-heading t]
8458 ["Previous" outline-previous-visible-heading t]
8459 ["Next Same Level" outline-forward-same-level t]
8460 ["Previous Same Level" outline-backward-same-level t]
8461 "--"
8462 ["Jump" org-goto t])
8463 ("Edit Structure"
8464 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
8465 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
8466 "--"
8467 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
8468 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
8469 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
8470 "--"
8471 ["Promote Heading" org-metaleft (not (org-at-table-p))]
8472 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
8473 ["Demote Heading" org-metaright (not (org-at-table-p))]
8474 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))])
8475 "--"
8476 ("TODO Lists"
8477 ["TODO/DONE/-" org-todo t]
8478 ["Show TODO Tree" org-show-todo-tree t]
8479 "--"
8480 ["Set Priority" org-priority t]
8481 ["Priority Up" org-shiftup t]
8482 ["Priority Down" org-shiftdown t])
8483 ("Dates and Scheduling"
8484 ["Timestamp" org-time-stamp t]
8485 ("Change Date"
8486 ["1 Day Later" org-timestamp-up-day t]
8487 ["1 Day Earlier" org-timestamp-down-day t]
8488 ["1 ... Later" org-shiftup t]
8489 ["1 ... Earlier" org-shiftdown t])
8490 ["Compute Time Range" org-evaluate-time-range t]
8491 ["Schedule Item" org-schedule t]
8492 ["Deadline" org-deadline t]
8493 "--"
8494 ["Goto Calendar" org-goto-calendar t]
8495 ["Date from Calendar" org-date-from-calendar t])
8496 "--"
8497 ("Timeline/Agenda"
8498 ["Show TODO Tree this File" org-show-todo-tree t]
8499 ["Check Deadlines this File" org-check-deadlines t]
8500 ["Timeline Current File" org-timeline t]
8501 "--"
8502 ["Agenda" org-agenda t])
8503 ("File List for Agenda")
8504 "--"
8505 ("Hyperlinks"
8506 ["Store Link (Global)" org-store-link t]
8507 ["Insert Link" org-insert-link t]
8508 ["Follow Link" org-open-at-point t])
8509 "--"
8510 ("Table"
8511 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
8512 ["Next Field" org-cycle (org-at-table-p)]
8513 ["Previous Field" org-shifttab (org-at-table-p)]
8514 ["Next Row" org-return (org-at-table-p)]
8515 "--"
8516 ["Blank Field" org-table-blank-field (org-at-table-p)]
8517 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
8518 "--"
8519 ("Column"
8520 ["Move Column Left" org-metaleft (org-at-table-p)]
8521 ["Move Column Right" org-metaright (org-at-table-p)]
8522 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
8523 ["Insert Column" org-shiftmetaright (org-at-table-p)])
8524 ("Row"
8525 ["Move Row Up" org-metaup (org-at-table-p)]
8526 ["Move Row Down" org-metadown (org-at-table-p)]
8527 ["Delete Row" org-shiftmetaup (org-at-table-p)]
8528 ["Insert Row" org-shiftmetadown (org-at-table-p)]
8529 "--"
8530 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
8531 ("Rectangle"
8532 ["Copy Rectangle" org-copy-special (org-at-table-p)]
8533 ["Cut Rectangle" org-cut-special (org-at-table-p)]
8534 ["Paste Rectangle" org-paste-special (org-at-table-p)]
8535 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
8536 "--"
8537 ["Which Column?" org-table-current-column (org-at-table-p)]
8538 ["Sum Column/Rectangle" org-table-sum
8539 (or (org-at-table-p) (org-region-active-p))]
8540 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
8541 "--"
8542 ["Invisible Vlines" org-table-toggle-vline-visibility
8543 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
8544 "--"
8545 ["Create" org-table-create (and (not (org-at-table-p))
8546 org-enable-table-editor)]
8547 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
8548 ["Import from File" org-table-import (not (org-at-table-p))]
8549 ["Export to File" org-table-export (org-at-table-p)]
8550 "--"
8551 ["Create/Convert from/to table.el" org-table-create-with-table.el t])
8552 "--"
8553 ("Export"
8554 ["ASCII" org-export-as-ascii t]
8555 ["Extract Visible Text" org-export-copy-visible t]
8556 ["HTML" org-export-as-html t]
8557 ["HTML and Open" org-export-as-html-and-open t]
8558 ; ["OPML" org-export-as-opml nil]
8559 "--"
8560 ["Option Template" org-insert-export-options-template t]
8561 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
8562 "--"
8563 ("Documentation"
8564 ["Show Version" org-version t]
8565 ["Info Documentation" org-info t])
8566 ("Customize"
8567 ["Browse Org Group" org-customize t]
8568 "--"
8569 ["Build Full Customize Menu" org-create-customize-menu
8570 (fboundp 'customize-menu-create)])
8571 ))
8572
8573 (defun org-info (&optional node)
8574 "Read documentation for Org-mode in the info system.
8575 With optional NODE, go directly to that node."
8576 (interactive)
8577 (require 'info)
8578 (Info-goto-node (format "(org)%s" (or node ""))))
8579
8580 (defun org-install-agenda-files-menu ()
8581 (easy-menu-change
8582 '("Org") "File List for Agenda"
8583 (append
8584 (list
8585 ["Edit File List" (customize-variable 'org-agenda-files) t]
8586 ["Add Current File to List" org-add-file t]
8587 ["Remove Current File from List" org-remove-file t]
8588 "--")
8589 (mapcar 'org-file-menu-entry org-agenda-files))))
8590
8591 ;;; Documentation
8592
8593 (defun org-customize ()
8594 "Call the customize function with org as argument."
8595 (interactive)
8596 (customize-browse 'org))
8597
8598 (defun org-create-customize-menu ()
8599 "Create a full customization menu for Org-mode, insert it into the menu."
8600 (interactive)
8601 (if (fboundp 'customize-menu-create)
8602 (progn
8603 (easy-menu-change
8604 '("Org") "Customize"
8605 `(["Browse Org group" org-customize t]
8606 "--"
8607 ,(customize-menu-create 'org)
8608 ["Set" Custom-set t]
8609 ["Save" Custom-save t]
8610 ["Reset to Current" Custom-reset-current t]
8611 ["Reset to Saved" Custom-reset-saved t]
8612 ["Reset to Standard Settings" Custom-reset-standard t]))
8613 (message "\"Org\"-menu now contains full customization menu"))
8614 (error "Cannot expand menu (outdated version of cus-edit.el)")))
8615
8616 ;;; Miscellaneous stuff
8617
8618 (defun org-move-line-down (arg)
8619 "Move the current line down. With prefix argument, move it past ARG lines."
8620 (interactive "p")
8621 (let ((col (current-column))
8622 beg end pos)
8623 (beginning-of-line 1) (setq beg (point))
8624 (beginning-of-line 2) (setq end (point))
8625 (beginning-of-line (+ 1 arg))
8626 (setq pos (move-marker (make-marker) (point)))
8627 (insert (delete-and-extract-region beg end))
8628 (goto-char pos)
8629 (move-to-column col)))
8630
8631 (defun org-move-line-up (arg)
8632 "Move the current line up. With prefix argument, move it past ARG lines."
8633 (interactive "p")
8634 (let ((col (current-column))
8635 beg end pos)
8636 (beginning-of-line 1) (setq beg (point))
8637 (beginning-of-line 2) (setq end (point))
8638 (beginning-of-line (- arg))
8639 (setq pos (move-marker (make-marker) (point)))
8640 (insert (delete-and-extract-region beg end))
8641 (goto-char pos)
8642 (move-to-column col)))
8643
8644 ;; Functions needed for Emacs/XEmacs region compatibility
8645
8646 (defun org-region-active-p ()
8647 "Is `transient-mark-mode' on and the region active?
8648 Works on both Emacs and XEmacs."
8649 (if org-ignore-region
8650 nil
8651 (if org-xemacs-p
8652 (and zmacs-regions (region-active-p))
8653 (and transient-mark-mode mark-active))))
8654
8655 (defun org-add-to-invisibility-spec (arg)
8656 "Add elements to `buffer-invisibility-spec'.
8657 See documentation for `buffer-invisibility-spec' for the kind of elements
8658 that can be added."
8659 (cond
8660 ((fboundp 'add-to-invisibility-spec)
8661 (add-to-invisibility-spec arg))
8662 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
8663 (setq buffer-invisibility-spec (list arg)))
8664 (t
8665 (setq buffer-invisibility-spec
8666 (cons arg buffer-invisibility-spec)))))
8667
8668 (defun org-remove-from-invisibility-spec (arg)
8669 "Remove elements from `buffer-invisibility-spec'."
8670 (if (fboundp 'remove-from-invisibility-spec)
8671 (remove-from-invisibility-spec arg)
8672 (if (consp buffer-invisibility-spec)
8673 (setq buffer-invisibility-spec
8674 (delete arg buffer-invisibility-spec)))))
8675
8676 (defun org-in-invisibility-spec-p (arg)
8677 "Is ARG a member of `buffer-invisibility-spec'?."
8678 (if (consp buffer-invisibility-spec)
8679 (member arg buffer-invisibility-spec)
8680 nil))
8681
8682 (defun org-image-file-name-regexp ()
8683 "Return regexp matching the file names of images."
8684 (if (fboundp 'image-file-name-regexp)
8685 (image-file-name-regexp)
8686 (let ((image-file-name-extensions
8687 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
8688 "xbm" "xpm" "pbm" "pgm" "ppm")))
8689 (concat "\\."
8690 (regexp-opt (nconc (mapcar 'upcase
8691 image-file-name-extensions)
8692 image-file-name-extensions)
8693 t)
8694 "\\'"))))
8695
8696 ;; Functions needed for compatibility with old outline.el
8697
8698 ;; The following functions capture almost the entire compatibility code
8699 ;; between the different versions of outline-mode. The only other place
8700 ;; where this is important are the font-lock-keywords. Search for
8701 ;; `org-noutline-p' to find it.
8702
8703 ;; C-a should go to the beginning of a *visible* line, also in the
8704 ;; new outline.el. I guess this should be patched into Emacs?
8705 (defun org-beginning-of-line ()
8706 "Go to the beginning of the current line. If that is invisible, continue
8707 to a visible line beginning. This makes the function of C-a more intuitive."
8708 (interactive)
8709 (beginning-of-line 1)
8710 (if (bobp)
8711 nil
8712 (backward-char 1)
8713 (if (org-invisible-p)
8714 (while (and (not (bobp)) (org-invisible-p))
8715 (backward-char 1)
8716 (beginning-of-line 1))
8717 (forward-char 1))))
8718 (when org-noutline-p
8719 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
8720
8721 (defun org-invisible-p ()
8722 "Check if point is at a character currently not visible."
8723 (if org-noutline-p
8724 ;; Early versions of noutline don't have `outline-invisible-p'.
8725 (if (fboundp 'outline-invisible-p)
8726 (outline-invisible-p)
8727 (get-char-property (point) 'invisible))
8728 (save-excursion
8729 (skip-chars-backward "^\r\n")
8730 (equal (char-before) ?\r))))
8731
8732 (defun org-back-to-heading (&optional invisible-ok)
8733 "Move to previous heading line, or beg of this line if it's a heading.
8734 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
8735 (if org-noutline-p
8736 (outline-back-to-heading invisible-ok)
8737 (if (looking-at outline-regexp)
8738 t
8739 (if (re-search-backward (concat (if invisible-ok "[\r\n]" "^")
8740 outline-regexp)
8741 nil t)
8742 (if invisible-ok
8743 (progn (forward-char 1)
8744 (looking-at outline-regexp)))
8745 (error "Before first heading")))))
8746
8747 (defun org-on-heading-p (&optional invisible-ok)
8748 "Return t if point is on a (visible) heading line.
8749 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
8750 (if org-noutline-p
8751 (outline-on-heading-p 'invisible-ok)
8752 (save-excursion
8753 (skip-chars-backward "^\n\r")
8754 (and (looking-at outline-regexp)
8755 (or invisible-ok
8756 (bobp)
8757 (equal (char-before) ?\n))))))
8758
8759 (defun org-up-heading-all (arg)
8760 "Move to the heading line of which the present line is a subheading.
8761 This function considers both visible and invisible heading lines.
8762 With argument, move up ARG levels."
8763 (if org-noutline-p
8764 (if (fboundp 'outline-up-heading-all)
8765 (outline-up-heading-all arg) ; emacs 21 version of outline.el
8766 (outline-up-heading arg t)) ; emacs 22 version of outline.el
8767 (org-back-to-heading t)
8768 (looking-at outline-regexp)
8769 (if (<= (- (match-end 0) (match-beginning 0)) arg)
8770 (error "Cannot move up %d levels" arg)
8771 (re-search-backward
8772 (concat "[\n\r]" (regexp-quote
8773 (make-string (- (match-end 0) (match-beginning 0) arg)
8774 ?*))
8775 "[^*]"))
8776 (forward-char 1))))
8777
8778 (defun org-show-hidden-entry ()
8779 "Show an entry where even the heading is hidden."
8780 (save-excursion
8781 (if (not org-noutline-p)
8782 (progn
8783 (org-back-to-heading t)
8784 (org-flag-heading nil)))
8785 (org-show-entry)))
8786
8787 (defun org-check-occur-regexp (regexp)
8788 "If REGEXP starts with \"^\", modify it to check for \\r as well.
8789 Of course, only for the old outline mode."
8790 (if org-noutline-p
8791 regexp
8792 (if (string-match "^\\^" regexp)
8793 (concat "[\n\r]" (substring regexp 1))
8794 regexp)))
8795
8796 (defun org-flag-heading (flag &optional entry)
8797 "Flag the current heading. FLAG non-nil means make invisible.
8798 When ENTRY is non-nil, show the entire entry."
8799 (save-excursion
8800 (org-back-to-heading t)
8801 (if (not org-noutline-p)
8802 ;; Make the current headline visible
8803 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
8804 ;; Check if we should show the entire entry
8805 (if entry
8806 (progn
8807 (org-show-entry)
8808 (save-excursion ;; FIXME: Is this the fix for points in the -|
8809 ;; middle of text? |
8810 (and (outline-next-heading) ;; |
8811 (org-flag-heading nil)))) ; show the next heading _|
8812 (outline-flag-region (max 1 (1- (point)))
8813 (save-excursion (outline-end-of-heading) (point))
8814 (if org-noutline-p
8815 flag
8816 (if flag ?\r ?\n))))))
8817
8818 (defun org-show-subtree ()
8819 "Show everything after this heading at deeper levels."
8820 (outline-flag-region
8821 (point)
8822 (save-excursion
8823 (outline-end-of-subtree) (outline-next-heading) (point))
8824 (if org-noutline-p nil ?\n)))
8825
8826 (defun org-show-entry ()
8827 "Show the body directly following this heading.
8828 Show the heading too, if it is currently invisible."
8829 (interactive)
8830 (save-excursion
8831 (org-back-to-heading t)
8832 (outline-flag-region
8833 (1- (point))
8834 (save-excursion
8835 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
8836 (or (match-beginning 1) (point-max)))
8837 (if org-noutline-p nil ?\n))))
8838
8839
8840 (defun org-make-options-regexp (kwds)
8841 "Make a regular expression for keyword lines."
8842 (concat
8843 (if org-noutline-p "^" "[\n\r]")
8844 "#?[ \t]*\\+\\("
8845 (mapconcat 'regexp-quote kwds "\\|")
8846 "\\):[ \t]*"
8847 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
8848
8849 ;; Advise the bookmark-jump function to make jump position visible
8850 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
8851 (eval-after-load "bookmark"
8852 '(defadvice bookmark-jump (after org-make-visible activate)
8853 "Make the position visible."
8854 (and (eq major-mode 'org-mode)
8855 (org-invisible-p)
8856 (org-show-hierarchy-above))))
8857
8858 ;;; Finish up
8859
8860 (provide 'org)
8861
8862 (run-hooks 'org-load-hook)
8863
8864 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
8865
8866 ;;; org.el ends here
8867