]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-up-heading-all): Fixed bug with
[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.06
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
35 ;; top of outline-mode - ideal to keep the content of large files well
36 ;; structured. It supports ToDo items, deadlines and time stamps, which
37 ;; magically appear in the diary listing of the Emacs calendar. Tables are
38 ;; easily created with a built-in table editor. Plain text URL-like links
39 ;; connect to websites, emails (VM,RMAIL,WANDERLUST), Usenet messages (Gnus),
40 ;; BBDB entries, and any files related to the projects. For printing and
41 ;; sharing of notes, an Org-mode file (or a part of it) can be exported as
42 ;; a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; The instruction below assume that you have downloaded Org-mode from the
47 ;; web. If Org-mode is part of the Emacs distribution or an XEmacs package,
48 ;; you only need to add to .emacs the last three lines of Lisp code listed
49 ;; below, i.e. the `auto-mode-alist' modification and the global key bindings.
50 ;;
51 ;; Byte-compile org.el and put it on your load path. Then copy the
52 ;; following lines into .emacs. The last two lines define *global*
53 ;; keys for the commands `org-store-link' and `org-agenda' - please
54 ;; choose suitable keys yourself.
55 ;;
56 ;; (autoload 'org-mode "org" "Org mode" t)
57 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
58 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
59 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
60 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
61 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
62 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
63 ;; (define-key global-map "\C-cl" 'org-store-link)
64 ;; (define-key global-map "\C-ca" 'org-agenda)
65 ;;
66 ;; This will put all files with extension ".org" into Org-mode. As an
67 ;; 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.
77 ;; The distribution also contains a PDF version of it. At the homepage
78 ;; of Org-mode, you can read the same text online as HTML.
79 ;;
80 ;; Changes:
81 ;; -------
82 ;; Version 3.06
83 ;; - M-S-RET inserts a new TODO heading.
84 ;; - New startup option `content'.
85 ;; - Better visual response when TODO items in agenda change status.
86 ;; - Window positioning after visibility state changes optimized and made
87 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
88 ;;
89 ;; Version 3.05
90 ;; - Agenda entries from the diary are linked to the diary file, so
91 ;; adding and editing diary entries can be done directly from the agenda.
92 ;; - Many calendar/diary commands available directly from agenda.
93 ;; - Field copying in tables with S-RET does increment.
94 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
95 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
96 ;;
97 ;; Version 3.04
98 ;; - Table editor optimized to need fewer realignments, and to keep
99 ;; table shape when typing in fields.
100 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
101 ;; into arbitrary major modes.
102 ;; - Fixed bug with realignment in XEmacs.
103 ;; - Startup options can be set with special #+STARTUP line.
104 ;; - Heading following a match in org-occur can be suppressed.
105 ;;
106 ;; Version 3.03
107 ;; - Copyright transfer to the FSF.
108 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
109 ;; - Timeline now always contains today, and `.' jumps to it.
110 ;; - Table editor:
111 ;; - cut and paste of rectangular regions in tables
112 ;; - command to convert org-mode table to table.el table and back
113 ;; - command to treat several cells like a paragraph and fill it
114 ;; - command to convert a buffer region to a table
115 ;; - import/export tables as tab-separated files (exchange with Excel)
116 ;; - Agenda:
117 ;; - Sorting mechanism for agenda items rewritten from scratch.
118 ;; - Sorting fully configurable.
119 ;; - Entries specifying a time are sorted together.
120 ;; - Completion also covers option keywords after `#-'.
121 ;; - Bug fixes.
122 ;;
123 ;; Version 3.01
124 ;; - New reference card, thanks to Philip Rooke for creating it.
125 ;; - Single file agenda renamed to "Timeline". It no longer shows
126 ;; warnings about upcoming deadlines/overdue scheduled items.
127 ;; That functionality is now limited to the (multifile) agenda.
128 ;; - When reading a date, the calendar can be manipulated with keys.
129 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested)
130 ;; - Minor bug fixes and documentation improvements.
131
132 ;;; Code:
133
134 (eval-when-compile (require 'cl))
135 (require 'outline)
136 (require 'time-date)
137 (require 'easymenu)
138
139 ;;; Customization variables
140
141 (defvar org-version "3.06"
142 "The version number of the file org.el.")
143 (defun org-version ()
144 (interactive)
145 (message "Org-mode version %s" org-version))
146
147 ;; The following two constants are for compatibility with different
148 ;; Emacs versions (Emacs versus XEmacs) and with different versions of
149 ;; outline.el. All the compatibility code in org.el is based on these two
150 ;; constants.
151 (defconst org-xemacs-p (featurep 'xemacs)
152 "Are we running xemacs?")
153 (defconst org-noutline-p (featurep 'noutline)
154 "Are we using the new outline mode?")
155
156 (defgroup org nil
157 "Outline-based notes management and organizer "
158 :tag "Org"
159 :group 'outlines
160 :group 'hypermedia
161 :group 'calendar)
162
163 (defgroup org-startup nil
164 "Options concerning startup of Org-mode."
165 :tag "Org Startup"
166 :group 'org)
167
168 (defcustom org-startup-folded t
169 "Non-nil means, entering Org-mode will switch to OVERVIEW.
170 This can also be configured on a per-file basis by adding one of
171 the following lines anywhere in the buffer:
172
173 #+STARTUP: fold
174 #+STARTUP: nofold
175 #+STARTUP: content"
176 :group 'org-startup
177 :type '(choice
178 (const :tag "nofold: show all" nil)
179 (const :tag "fold: overview" t)
180 (const :tag "content: all headlines" content)))
181
182 (defcustom org-startup-truncated t
183 "Non-nil means, entering Org-mode will set `truncate-lines'.
184 This is useful since some lines containing links can be very long and
185 uninteresting. Also tables look terrible when wrapped."
186 :group 'org-startup
187 :type 'boolean)
188
189 (defcustom org-startup-with-deadline-check nil
190 "Non-nil means, entering Org-mode will run the deadline check.
191 This means, if you start editing an org file, you will get an
192 immediate reminder of any due deadlines.
193 This can also be configured on a per-file basis by adding one of
194 the following lines anywhere in the buffer:
195
196 #+STARTUP: dlcheck
197 #+STARTUP: nodlcheck
198 "
199 :group 'org-startup
200 :type 'boolean)
201
202 (defcustom org-insert-mode-line-in-empty-file nil
203 "Non-nil means insert the first line setting Org-mode in empty files.
204 When the function `org-mode' is called interactively in an empty file, this
205 normally means that the file name does not automatically trigger Org-mode.
206 To ensure that the file will always be in Org-mode in the future, a
207 line enforcing Org-mode will be inserted into the buffer, if this option
208 has been set."
209 :group 'org-startup
210 :type 'boolean)
211
212 (defgroup org-keywords nil
213 "Options concerning TODO items in Org-mode."
214 :tag "Org Keywords"
215 :group 'org)
216
217 (defcustom org-todo-keywords '("TODO" "DONE")
218 "List of TODO entry keywords.\\<org-mode-map>
219 By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
220 considered to mean that the entry is \"done\". All the other mean that
221 action is required, and will make the entry show up in todo lists, diaries
222 etc.
223 The command \\[org-todo] cycles an entry through these states, and an
224 additional state where no keyword is present. For details about this
225 cycling, see also the variable `org-todo-interpretation'
226 Changes become only effective after restarting Emacs."
227 :group 'org-keywords
228 :type '(repeat (string :tag "Keyword")))
229
230 (defcustom org-todo-interpretation 'sequence
231 "Controls how TODO keywords are interpreted.\\<org-mode-map>
232 Possible values are `sequence' and `type'.
233 This variable is only relevant if `org-todo-keywords' contains more than two
234 states. There are two ways how these keywords can be used:
235
236 - As a sequence in the process of working on a TODO item, for example
237 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
238 org-todo-interpretation 'sequence)
239
240 - As different types of TODO items, for example
241 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
242 org-todo-interpretation 'type)
243
244 When the states are interpreted as a sequence, \\[org-todo] always cycles
245 to the next state, in order to walk through all different states. So with
246 \\[org-todo], you turn an empty entry into the state TODO. When you started
247 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
248 later to VERIFY and finally to DONE.
249
250 When the states are interpreted as types, \\[org-todo] still cycles through
251 when it is called several times in direct succession, in order to initially
252 select the type. However, if not called immediately after a previous
253 \\[org-todo], it switches from each type directly to DONE. So with the
254 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
255 RELAXED. If you later return to this entry and press \\[org-todo] again,
256 RELAXED will not be changed REMIND, but directly to DONE.
257
258 You can create a large number of types. To initially select a
259 type, it is then best to use C-u \\[org-todo] in order to specify the
260 type with completion. Of course, you can also type the keyword
261 directly into the buffer. M-TAB completes TODO keywords at the
262 beginning of a headline."
263 :group 'org-keywords
264 :type '(choice (const sequence)
265 (const type)))
266
267 (defcustom org-default-priority ?B
268 "The default priority of TODO items.
269 This is the priority an item get if no explicit priority is given."
270 :group 'org-keywords
271 :type 'character)
272
273 (defcustom org-lowest-priority ?C
274 "The lowest priority of TODO items. A character like ?A, ?B etc."
275 :group 'org-keywords
276 :type 'character)
277
278 (defcustom org-deadline-string "DEADLINE:"
279 "String to mark deadline entries.
280 A deadline is this string, followed by a time stamp. Should be a word,
281 terminated by a colon. You can insert a schedule keyword and
282 a timestamp with \\[org-deadline].
283 Changes become only effective after restarting Emacs."
284 :group 'org-keywords
285 :type 'string)
286
287 (defcustom org-scheduled-string "SCHEDULED:"
288 "String to mark scheduled TODO entries.
289 A schedule is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-schedule].
292 Changes become only effective after restarting Emacs."
293 :group 'org-keywords
294 :type 'string)
295
296 (defcustom org-comment-string "COMMENT"
297 "Entries starting with this keyword will never be exported.
298 An entry can be toggled between COMMENT and normal with
299 \\[org-toggle-comment].
300 Changes become only effective after restarting Emacs."
301 :group 'org-keywords
302 :type 'string)
303
304 (defcustom org-after-todo-state-change-hook nil
305 "Hook which is run after the state of a TODO item was changed.
306 The new state (a string with a todo keyword, or nil) is available in the
307 lisp variable `state'."
308 :group 'org-keywords
309 :type 'hook)
310
311 ;; Variables for pre-computed regular expressions, all buffer local
312 (defvar org-todo-kwd-priority-p nil
313 "Do TODO items have priorities?")
314 (make-variable-buffer-local 'org-todo-kwd-priority-p)
315 (defvar org-todo-kwd-max-priority nil
316 "Maximum priority of TODO items")
317 (make-variable-buffer-local 'org-todo-kwd-max-priority)
318 (defvar org-ds-keyword-length 12
319 "Maximum length of the Deadline and SCHEDULED keywords.")
320 (make-variable-buffer-local 'org-ds-keyword-length)
321 (defvar org-done-string nil
322 "The last string in `org-todo-keywords', indicating an item is DONE.")
323 (make-variable-buffer-local 'org-done-string)
324 (defvar org-todo-regexp nil
325 "Matches any of the TODO state keywords.")
326 (make-variable-buffer-local 'org-todo-regexp)
327 (defvar org-not-done-regexp nil
328 "Matches any of the TODO state keywords except the last one.")
329 (make-variable-buffer-local 'org-not-done-regexp)
330 (defvar org-todo-line-regexp nil
331 "Matches a headline and puts TODO state into group 2 if present.")
332 (make-variable-buffer-local 'org-todo-line-regexp)
333 (defvar org-nl-done-regexp nil
334 "Matches newline followed by a headline with the DONE keyword.")
335 (make-variable-buffer-local 'org-nl-done-regexp)
336 (defvar org-looking-at-done-regexp nil
337 "Matches the DONE keyword a point.")
338 (make-variable-buffer-local 'org-looking-at-done-regexp)
339 (defvar org-deadline-regexp nil
340 "Matches the DEADLINE keyword.")
341 (make-variable-buffer-local 'org-deadline-regexp)
342 (defvar org-deadline-time-regexp nil
343 "Matches the DEADLINE keyword together with a time stamp.")
344 (make-variable-buffer-local 'org-deadline-time-regexp)
345 (defvar org-deadline-line-regexp nil
346 "Matches the DEADLINE keyword and the rest of the line.")
347 (make-variable-buffer-local 'org-deadline-line-regexp)
348 (defvar org-scheduled-regexp nil
349 "Matches the SCHEDULED keyword.")
350 (make-variable-buffer-local 'org-scheduled-regexp)
351 (defvar org-scheduled-time-regexp nil
352 "Matches the SCHEDULED keyword together with a time stamp.")
353 (make-variable-buffer-local 'org-scheduled-time-regexp)
354
355 (defun org-set-regexps-and-options ()
356 "Precompute regular expressions for current buffer."
357 (when (eq major-mode 'org-mode)
358 (let ((re (org-make-options-regexp
359 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP")))
360 (splitre "[ \t]+")
361 kwds int key value cat)
362 (save-restriction
363 (save-excursion
364 (widen)
365 (goto-char (point-min))
366 (while (re-search-forward re nil t)
367 (setq key (match-string 1) value (match-string 2))
368 (cond
369 ((equal key "CATEGORY")
370 (if (string-match "[ \t]+$" value)
371 (setq value (replace-match "" t t value)))
372 (setq cat (intern value)))
373 ((equal key "SEQ_TODO")
374 (setq int 'sequence
375 kwds (append kwds (org-split-string value splitre))))
376 ((equal key "PRI_TODO")
377 (setq int 'priority
378 kwds (append kwds (org-split-string value splitre))))
379 ((equal key "TYP_TODO")
380 (setq int 'type
381 kwds (append kwds (org-split-string value splitre))))
382 ((equal key "STARTUP")
383 (let ((opts (org-split-string value splitre))
384 (set '(("fold" org-startup-folded t)
385 ("nofold" org-startup-folded nil)
386 ("content" org-startup-folded 'content)
387 ("dlcheck" org-startup-with-deadline-check t)
388 ("nodlcheck" org-startup-with-deadline-check nil)))
389 l var val)
390 (while (setq l (assoc (pop opts) set))
391 (setq var (nth 1 l) val (nth 2 l))
392 (set (make-local-variable var) val)))))
393 )))
394 (and cat (set (make-local-variable 'org-category) cat))
395 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
396 (and int (set (make-local-variable 'org-todo-interpretation) int)))
397 ;; Compute the regular expressions and other local variables
398 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
399 org-todo-kwd-max-priority (1- (length org-todo-keywords))
400 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
401 (length org-scheduled-string)))
402 org-done-string
403 (nth (1- (length org-todo-keywords)) org-todo-keywords)
404 org-todo-regexp
405 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
406 "\\|") "\\)\\>")
407 org-not-done-regexp
408 (concat "\\<\\("
409 (mapconcat 'regexp-quote
410 (nreverse (cdr (reverse org-todo-keywords)))
411 "\\|")
412 "\\)\\>")
413 org-todo-line-regexp
414 (concat "^\\(\\*+\\)[ \t]*\\("
415 (mapconcat 'regexp-quote org-todo-keywords "\\|")
416 "\\)? *\\(.*\\)")
417 org-nl-done-regexp
418 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
419 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
420 org-deadline-regexp (concat "\\<" org-deadline-string)
421 org-deadline-time-regexp
422 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
423 org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 org-scheduled-regexp
426 (concat "\\<" org-scheduled-string)
427 org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
429 (org-set-font-lock-defaults)))
430
431 (defgroup org-time nil
432 "Options concerning time stamps and deadlines in Org-mode."
433 :tag "Org Time"
434 :group 'org)
435
436 (defcustom org-deadline-warning-days 30
437 "No. of days before expiration during which a deadline becomes active.
438 This variable governs the display in the org file."
439 :group 'org-time
440 :type 'number)
441
442 (defcustom org-popup-calendar-for-date-prompt t
443 "Non-nil means, pop up a calendar when prompting for a date.
444 In the calendar, the date can be selected with mouse-1. However, the
445 minibuffer will also be active, and you can simply enter the date as well.
446 When nil, only the minibuffer will be available."
447 :group 'org-time
448 :type 'number)
449
450 (defcustom org-calendar-follow-timestamp-change t
451 "Non-nil means, make the calendar window follow timestamp changes.
452 When a timestamp is modified and the calendar window is visible, it will be
453 moved to the new date."
454 :group 'org-time
455 :type 'boolean)
456
457 (defgroup org-agenda nil
458 "Options concerning agenda display Org-mode."
459 :tag "Org Agenda"
460 :group 'org)
461
462 (defcustom org-agenda-files nil
463 "A list of org files for agenda/diary display.
464 Entries are added to this list with \\[org-add-file] and removed with
465 \\[org-remove-file]. You can also use customize to edit the list."
466 :group 'org-agenda
467 :type '(repeat file))
468
469 (defcustom org-select-timeline-window t
470 "Non-nil means, after creating a timeline, move cursor into Timeline window.
471 When nil, cursor will remain in the current window."
472 :group 'org-agenda
473 :type 'boolean)
474
475 (defcustom org-select-agenda-window t
476 "Non-nil means, after creating an agenda, move cursor into Agenda window.
477 When nil, cursor will remain in the current window."
478 :group 'org-agenda
479 :type 'boolean)
480
481 (defcustom org-fit-agenda-window t
482 "Non-nil means, change window size of agenda to fit content."
483 :group 'org-agenda
484 :type 'boolean)
485
486 (defcustom org-agenda-show-all-dates t
487 "Non-nil means, `org-agenda' shows every day in the selected range.
488 When nil, only the days which actually have entries are shown."
489 :group 'org-agenda
490 :type 'boolean)
491
492 ;; FIXME: First day of month works only for current month because it would
493 ;; require a variable ndays treatment.
494 (defcustom org-agenda-start-on-weekday 1
495 "Non-nil means, start the overview always on the specified weekday.
496 0 Denotes Sunday, 1 denotes Monday etc.
497 When nil, always start on the current day."
498 :group 'org-agenda
499 :type '(choice (const :tag "Today" nil)
500 (const :tag "First day of month" t)
501 (number :tag "Weekday No.")))
502
503 (defcustom org-agenda-ndays 7
504 "Number of days to include in overview display."
505 :group 'org-agenda
506 :type 'number)
507
508 (defcustom org-agenda-include-all-todo t
509 "Non-nil means, the agenda will always contain all TODO entries.
510 When nil, date-less entries will only be shown if `org-agenda' is called
511 with a prefix argument.
512 When non-nil, the TODO entries will be listed at the top of the agenda, before
513 the entries for specific days."
514 :group 'org-agenda
515 :type 'boolean)
516
517 (defcustom org-agenda-include-diary nil
518 "Non-nil means, when preparing the agenda, also get the
519 entries from the emacs calendars diary."
520 :group 'org-agenda
521 :type 'boolean)
522
523 (defcustom org-calendar-to-agenda-key [?c]
524 "The key to be installed in `calendar-mode-map' for switching to the agenda.
525 The command `org-calendar-goto-agenda' will be bound to this key. The
526 default is the character `c' because then`c' can be used to switch back and
527 force between agenda and calendar."
528 :group 'org-agenda
529 :type 'sexp)
530
531 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
532 "Sorting structure for the agenda items of a single day.
533 This is a list of symbols which will be used in sequence to determine
534 if an entry should be listed before another entry. The following
535 symbols are recognized.
536
537 time-up Put entries with time-of-day indications first, early first
538 time-down Put entries with time-of-day indications first, late first
539 category-keep Keep the default order of categories, corresponding to the
540 sequence in `org-agenda-files'.
541 category-up Sort alphabetically by category, A-Z.
542 category-down Sort alphabetically by category, Z-A.
543 priority-up Sort numerically by priority, high priority last.
544 priority-down Sort numerically by priority, high priority first.
545
546 The different possibilities will be tried in sequence, and testing stops
547 if one comparison returns a \"not-equal\". For example, the default
548 '(time-up category-keep priority-down)
549 means: Pull out all entries having a specified time of day and sort them,
550 in order to make a time schedule for the current day the first thing in the
551 agenda listing for the day. Of the entries without a time indication, keep
552 the grouped in categories, don't sort the categories, but keep them in
553 the sequence given in `org-agenda-files'. Within each category sort by
554 priority.
555
556 Leaving out the `category-keep' would mean that items will be sorted across
557 categories by priority."
558 :group 'org-agenda
559 :type '(repeat
560 (choice
561 (const time-up)
562 (const time-down)
563 (const category-keep)
564 (const category-up)
565 (const category-down)
566 (const priority-up)
567 (const priority-down))))
568
569 (defcustom org-sort-agenda-notime-is-late t
570 "Non-nil means, items without time are considered late.
571 This is only relevant for sorting. When t, items which have no explicit
572 time like 15:30 will be considered as 24:01, i.e. later than any items which
573 do have a time. When nil, the default time is before 0:00."
574 :group 'org-agenda
575 :type 'boolean)
576
577 (defvar org-category nil
578 "Variable used by org files to set a category for agenda display.
579 Such files should use a file variable to set it, for example
580
581 -*- mode: org; org-category: \"ELisp\"
582
583 If the file does not specify a category, the file's base name
584 is used instead.")
585
586 (defgroup org-structure nil
587 "Options concerning structure editing in Org-mode."
588 :tag "Org Structure"
589 :group 'org)
590
591 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
592 "Hook that is run after `org-cycle' has changed the buffer visibility.
593 The function(s) in this hook must accept a single argument which indicates
594 the new state that was set by the most recent `org-cycle' command. The
595 argument is a symbol. After a global state change, it can have the values
596 `overview', `content', or `all'. After a local state change, it can have
597 the values `folded', `children', or `subtree'."
598 :group 'org-structure
599 :type 'hook)
600
601 (defcustom org-occur-hook '(org-first-headline-recenter)
602 "Hook that is run after `org-occur' has constructed a sparse tree.
603 This can be used to recenter the window to show as much of the structure
604 as possible."
605 :group 'org-structure
606 :type 'hook)
607
608 (defcustom org-adapt-indentation t
609 "Non-nil means, adapt indentation when promoting and demoting.
610 When this is set and the *entire* text in an entry is indented, the
611 indentation is increased by one space in a demotion command, and
612 decreased by one in a promotion command. If any line in the entry
613 body starts at column 0, indentation is not changed at all."
614 :group 'org-structure
615 :type 'boolean)
616
617 (defcustom org-cycle-emulate-tab t
618 "Where should `org-cycle' emulate TAB.
619 nil Never
620 white Only in completely white lines
621 t Everywhere except in headlines"
622 :group 'org-structure
623 :type '(choice (const :tag "Never" nil)
624 (const :tag "Only in completely white lines" white)
625 (const :tag "Everywhere except in headlines" t)
626 ))
627
628 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
629 "Formats for `format-time-string' which are used for time stamps.
630 It is not recommended to change this constant.")
631
632 (defcustom org-show-following-heading t
633 "Non-nil means, show heading following match in `org-occur'.
634 When doing an `org-occur' it is useful to show the headline which
635 follows the match, even if they do not match the regexp. This makes it
636 easier to edit directly inside the sparse tree. However, if you use
637 org-occur mainly as an overview, the following headlines are
638 unnecessary clutter."
639 :group 'org-structure
640 :type 'boolean)
641
642
643 (defgroup org-link nil
644 "Options concerning links in Org-mode."
645 :tag "Org Link"
646 :group 'org)
647
648 (defcustom org-allow-space-in-links t
649 "Non-nil means, file names in links may contain space characters.
650 When nil, it becomes possible to put several links into a line."
651 :group 'org-link
652 :type 'boolean)
653
654 (defcustom org-line-numbers-in-file-links t
655 "Non-nil means, file links from `org-store-link' contain line numbers.
656 The line number will be added to the file name with :NNN and interpreted
657 by the command `org-open-at-point'.
658 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
659 negates this setting for the duration of the command."
660 :group 'org-link
661 :type 'boolean)
662
663 (defcustom org-keep-stored-link-after-insertion nil
664 "Non-nil means, keep link in list for entire session.
665
666 The command `org-store-link' adds a link pointing to the current
667 location to an internal list. These links accumulate during a session.
668 The command `org-insert-link' can be used to insert links into any
669 Org-mode file (offering completion for all stored links). When this
670 option is nil, every link which has been inserted once using `C-c C-l'
671 will be removed from the list, to make completing the unused links
672 more efficient."
673 :group 'org-link
674 :type 'boolean)
675
676 (defcustom org-link-frame-setup
677 '((vm . vm-visit-folder-other-frame)
678 (gnus . gnus-other-frame)
679 (file . find-file-other-window))
680 "Setup the frame configuration for following links.
681 When following a link with Emacs, it may often be useful to display
682 this link in another window or frame. This variable can be used to
683 set this up for the different types of links.
684 For VM, use any of
685 vm-visit-folder
686 vm-visit-folder-other-frame
687 For Gnus, use any of
688 gnus
689 gnus-other-frame
690 For FILE, use any of
691 find-file
692 find-file-other-window
693 find-file-other-frame
694 For the calendar, use the variable `calendar-setup'.
695 For BBDB, it is currently only possible to display the matches in
696 another window."
697 :group 'org-link
698 :type '(list
699 (cons (const vm)
700 (choice
701 (const vm-visit-folder)
702 (const vm-visit-folder-other-window)
703 (const vm-visit-folder-other-frame)))
704 (cons (const gnus)
705 (choice
706 (const gnus)
707 (const gnus-other-frame)))
708 (cons (const file)
709 (choice
710 (const find-file)
711 (const find-file-other-window)
712 (const find-file-other-frame)))))
713
714 (defcustom org-usenet-links-prefer-google nil
715 "Non-nil means, `org-store-link' will create web links to google groups.
716 When nil, Gnus will be used for such links.
717 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
718 negates this setting for the duration of the command."
719 :group 'org-link
720 :type 'boolean)
721
722 (defcustom org-open-non-existing-files nil
723 "Non-nil means, `org-open-file' will open non-existing file.
724 When nil, an error will be generated."
725 :group 'org-link
726 :type 'boolean)
727
728 (defcustom org-confirm-shell-links t
729 "Non-nil means, ask for confirmation before executing shell links.
730 The default is true, to keep new users from shooting into their own foot."
731 :group 'org-link
732 :type 'boolean)
733
734 (defconst org-file-apps-defaults-linux
735 '((t . emacs)
736 ("jpg" . "xv %s")
737 ("gif" . "xv %s")
738 ("ppm" . "xv %s")
739 ("pgm" . "xv %s")
740 ("pbm" . "xv %s")
741 ("tif" . "xv %s")
742 ("png" . "xv %s")
743 ("ps" . "gv %s")
744 ("ps.gz" . "gv %s")
745 ("eps" . "gv %s")
746 ("eps.gz" . "gv %s")
747 ("dvi" . "xdvi %s")
748 ("mpeg" . "plaympeg %s")
749 ("mp3" . "plaympeg %s")
750 ("fig" . "xfig %s")
751 ("pdf" . "acroread %s")
752 ("doc" . "soffice %s")
753 ("ppt" . "soffice %s")
754 ("pps" . "soffice %s")
755 ("html" . "netscape -remote openURL(%s,new-window)")
756 ("htm" . "netscape -remote openURL(%s,new-window)")
757 ("xs" . "soffice %s"))
758 "Default file applications on a UNIX/LINUX system.
759 See `org-file-apps'.")
760
761 (defconst org-file-apps-defaults-macosx
762 '((t . "open %s")
763 ("ps" . "gv %s")
764 ("ps.gz" . "gv %s")
765 ("eps" . "gv %s")
766 ("eps.gz" . "gv %s")
767 ("dvi" . "xdvi %s")
768 ("fig" . "xfig %s"))
769 "Default file applications on a MacOS X system.
770 The system \"open\" is known as a default, but we use X11 applications
771 for some files for which the OS does not have a good default.
772 See `org-file-apps'.")
773
774 (defconst org-file-apps-defaults-windowsnt
775 '((t . (w32-shell-execute "open" file)))
776 "Default file applications on a Windows NT system.
777 The system \"open\" is used for most files.
778 See `org-file-apps'.")
779
780 (defcustom org-file-apps
781 '(
782 ("txt" . emacs)
783 ("tex" . emacs)
784 ("ltx" . emacs)
785 ("org" . emacs)
786 ("el" . emacs)
787 )
788 "External applications for opening `file:path' items in a document.
789 Org-mode uses system defaults for different file types, but
790 you can use this variable to set the application for a given file
791 extension. The entries in this list are cons cells with a file extension
792 and the corresponding command. Possible values for the command are:
793 `emacs' The file will be visited by the current Emacs process.
794 `default' Use the default application for this file type.
795 string A command to be executed by a shell. %s will be replaced
796 by the path to the file.
797 sexp A lisp form which will be evaluated. The file path will
798 be available in the lisp variable `file'.
799 For more examples, see the system specific constants
800 `org-file-apps-defaults-macosx'
801 `org-file-apps-defaults-windowsnt'
802 `org-file-apps-defaults-linux'."
803 :group 'org-link
804 :type '(repeat
805 (cons (string :tag "Extension")
806 (choice :value ""
807 (const :tag "Visit with Emacs" 'emacs)
808 (const :tag "Use system default" 'default)
809 (string :tag "Command")
810 (sexp :tag "Lisp form")))))
811
812
813 (defgroup org-remember nil
814 "Options concerning interaction with remember.el."
815 :tag "Org Remember"
816 :group 'org)
817
818 (defcustom org-directory "~/org"
819 "Directory with org files.
820 This directory will be used as default to prompt for org files.
821 Used by the hooks for remember.el."
822 :group 'org-remember
823 :type 'directory)
824
825 (defcustom org-default-notes-file "~/.notes"
826 "Default target for storing notes.
827 Used by the hooks for remember.el. This can be a string, or nil to mean
828 the value of `remember-data-file'."
829 :group 'org-remember
830 :type '(choice
831 (const :tag "Default from remember-data-file" nil)
832 file))
833
834 (defcustom org-reverse-note-order nil
835 "Non-nil means, store new notes at the beginning of a file or entry.
836 When nil, new notes will be filed to the end of a file or entry."
837 :group 'org-remember
838 :type '(choice
839 (const :tag "Reverse always" t)
840 (const :tag "Reverse never" nil)
841 (repeat :tag "By file name regexp"
842 (cons regexp boolean))))
843
844 (defgroup org-table nil
845 "Options concerning tables in Org-mode."
846 :tag "Org Table"
847 :group 'org)
848
849 (defcustom org-enable-table-editor 'optimized
850 "Non-nil means, lines starting with \"|\" are handled by the table editor.
851 When nil, such lines will be treated like ordinary lines.
852
853 When equal to the symbol `optimized', the table editor will be optimized to
854 do the following
855 - Use automatic overwrite mode in front of whitespace in table fields.
856 This make the structure of the table stay in tact as long as the edited
857 field does not exceed the column width.
858 - Minimize the number of realigns. Normally, the table is aligned each time
859 TAB or RET are pressed to move to another field. With optimization this
860 happens only if changes to a field might have changed the column width.
861 Optimization requires replacing the functions `self-insert-command',
862 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
863 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
864 very good at guessing when a re-align will be necessary, but you can always
865 force one with `C-c C-c'.
866
867 If you would like to use the optimized version in Org-mode, but the
868 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
869
870 This variable can be used to turn on and off the table editor during a session,
871 but in order to toggle optimization, a restart is required."
872 :group 'org-table
873 :type '(choice
874 (const :tag "off" nil)
875 (const :tag "on" t)
876 (const :tag "on, optimized" optimized)))
877
878 (defcustom org-table-default-size "5x2"
879 "The default size for newly created tables, Columns x Rows."
880 :group 'org-table
881 :type 'string)
882
883 (defcustom org-table-automatic-realign t
884 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
885 When nil, aligning is only done with \\[org-table-align], or after column
886 removal/insertion."
887 :group 'org-table
888 :type 'boolean)
889
890 (defcustom org-table-spaces-around-separators '(1 . 1)
891 "The number of spaces to be placed before and after separators."
892 :group 'org-table
893 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
894
895 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
896 "The number of spaces to be placed before and after separators.
897 This option applies when the column separators have been made invisible."
898 :group 'org-table
899 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
900
901 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
902 "Regular expression for recognizing numbers in table columns.
903 If a table column contains mostly numbers, it will be aligned to the
904 right. If not, it will be aligned to the left.
905
906 The default value of this option is a regular expression which allows
907 anything which looks remotely like a number as used in scientific
908 context. For example, all of the following will be considered a
909 number:
910 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
911
912 Other options offered by the customize interface are more restrictive."
913 :group 'org-table
914 :type '(choice
915 (const :tag "Positive Integers"
916 "^[0-9]+$")
917 (const :tag "Integers"
918 "^[-+]?[0-9]+$")
919 (const :tag "Floating Point Numbers"
920 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
921 (const :tag "Floating Point Number or Integer"
922 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
923 (const :tag "Exponential, Floating point, Integer"
924 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
925 (const :tag "Very General Number-Like"
926 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
927 (string :tag "Regexp:")))
928
929 (defcustom org-table-number-fraction 0.5
930 "Fraction of numbers in a column required to make the column align right.
931 In a column all non-white fields are considered. If at least this
932 fraction of fields is matched by `org-table-number-fraction',
933 alignment to the right border applies."
934 :group 'org-table
935 :type 'number)
936
937 (defcustom org-export-highlight-first-table-line t
938 "Non-nil means, highlight the first table line.
939 In HTML export, this means use <th> instead of <td>.
940 In tables created with table.el, this applies to the first table line.
941 In Org-mode tables, all lines before the first horizontal separator
942 line will be formatted with <th> tags."
943 :group 'org-table
944 :type 'boolean)
945
946 (defcustom org-table-copy-increment t
947 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
948 :group 'org-table
949 :type 'boolean)
950
951 (defcustom org-table-tab-recognizes-table.el t
952 "Non-nil means, TAB will automatically notice a table.el table.
953 When it sees such a table, it moves point into it and - if necessary -
954 calls `table-recognize-table'."
955 :group 'org-table
956 :type 'boolean)
957
958 (defcustom org-export-prefer-native-exporter-for-tables nil
959 "Non-nil means, always export tables created with table.el natively.
960 Natively means, use the HTML code generator in table.el.
961 When nil, Org-mode's own HTML generator is used when possible (i.e. if
962 the table does not use row- or column-spanning). This has the
963 advantage, that the automatic HTML conversions for math symbols and
964 sub/superscripts can be applied. Org-mode's HTML generator is also
965 much faster."
966 :group 'org-table
967 :type 'boolean)
968
969 (defcustom org-enable-fixed-width-editor t
970 "Non-nil means, lines starting with \":\" are treated as fixed-width.
971 This currently only means, they are never auto-wrapped.
972 When nil, such lines will be treated like ordinary lines."
973 :group 'org-table
974 :type 'boolean)
975
976 (defgroup org-export nil
977 "Options for exporting org-listings."
978 :tag "Org Export"
979 :group 'org)
980
981 (defcustom org-export-language-setup
982 '(("en" "Author" "Date" "Table of Contents")
983 ("da" "Ophavsmand" "Dato" "Indhold")
984 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
985 ("es" "Autor" "Fecha" "\xccndice")
986 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
987 ("it" "Autore" "Data" "Indice")
988 ("nl" "Auteur" "Datum" "Inhoudsopgave")
989 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
990 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
991 "Terms used in export text, translated to different languages.
992 Use the variable `org-export-default-language' to set the language,
993 or use the +OPTION lines for a per-file setting."
994 :group 'org-export
995 :type '(repeat
996 (list
997 (string :tag "HTML language tag")
998 (string :tag "Author")
999 (string :tag "Date")
1000 (string :tag "Table of Contents"))))
1001
1002 (defcustom org-export-default-language "en"
1003 "The default language of HTML export, as a string.
1004 This should have an association in `org-export-language-setup'"
1005 :group 'org-export
1006 :type 'string)
1007
1008 (defcustom org-export-headline-levels 3
1009 "The last level which is still exported as a headline.
1010 Inferior levels will produce itemize lists when exported.
1011 Note that a numeric prefix argument to an exporter function overrides
1012 this setting.
1013
1014 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1015 :group 'org-export
1016 :type 'number)
1017
1018 (defcustom org-export-with-section-numbers t
1019 "Non-nil means, add section numbers to headlines when exporting.
1020
1021 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1022 :group 'org-export
1023 :type 'boolean)
1024
1025 (defcustom org-export-with-toc t
1026 "Non-nil means, create a table of contents in exported files.
1027 The TOC contains headlines with levels up to`org-export-headline-levels'.
1028
1029 Headlines which contain any TODO items will be marked with \"(*)\" in
1030 ASCII export, and with red color in HTML output.
1031
1032 In HTML output, the TOC will be clickable.
1033
1034 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1035 :group 'org-export
1036 :type 'boolean)
1037
1038 (defcustom org-export-preserve-breaks nil
1039 "Non-nil means, preserve all line breaks when exporting.
1040 Normally, in HTML output paragraphs will be reformatted. In ASCII
1041 export, line breaks will always be preserved, regardless of this variable.
1042
1043 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1044 :group 'org-export
1045 :type 'boolean)
1046
1047 (defcustom org-export-html-inline-images t
1048 "Non-nil means, inline images into exported HTML pages.
1049 The link will still be to the original location of the image file.
1050 So if you are moving the page, lets say to your public HTML site,
1051 you will have to move the image and maybe change the link."
1052 :group 'org-export
1053 :type 'boolean)
1054
1055 (defcustom org-export-html-expand t
1056 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1057 When nil, these tags will be exported as plain text and therefore
1058 not be interpreted by a browser.
1059
1060 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1061 :group 'org-export
1062 :type 'boolean)
1063
1064 (defcustom org-export-with-fixed-width t
1065 "Non-nil means, lines starting with \":\" will be in fixed width font.
1066 This can be used to have pre-formatted text, fragments of code etc. For
1067 example
1068 : ;; Some Lisp examples
1069 : (while (defc cnt)
1070 : (ding))
1071 will be looking just like this in also HTML. In ASCII export, this option
1072 has no effect.
1073
1074 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1075 :group 'org-export
1076 :type 'boolean)
1077
1078 (defcustom org-export-with-tables t
1079 "Non-nil means, lines starting with \"|\" define a table
1080 For example:
1081
1082 | Name | Address | Birthday |
1083 |-------------+----------+-----------|
1084 | Arthur Dent | England | 29.2.2100 |
1085
1086 In ASCII export, this option has no effect.
1087
1088 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1089 :group 'org-export
1090 :type 'boolean)
1091
1092 (defcustom org-export-html-table-tag
1093 "<table border=1 cellspacing=0 cellpadding=6>"
1094 "The HTML tag used to start a table.
1095 This must be a <table> tag, but you may change the options like
1096 borders and spacing."
1097 :group 'org-export
1098 :type 'string)
1099
1100 (defcustom org-export-with-emphasize t
1101 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1102 If the export target supports emphasizing text, the word will be
1103 typeset in bold, italic, or underlined, respectively. Works only for
1104 single words, but you can say: I *really* *mean* *this*.
1105 In ASCII export, this option has no effect.
1106
1107 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1108 :group 'org-export
1109 :type 'boolean)
1110
1111 (defcustom org-match-sexp-depth 3
1112 "Number of stacked braces for sub/superscript matching.
1113 This has to be set before loading org.el to be effective."
1114 :group 'org-export
1115 :type 'integer)
1116
1117 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1118 (defcustom org-export-with-sub-superscripts t
1119 "Non-nil means, interpret \"_\" and \"^\" for export.
1120 When this option is turned on, you can use TeX-like syntax for sub- and
1121 superscripts. Several characters after \"_\" or \"^\" will be
1122 considered as a single item - so grouping with {} is normally not
1123 needed. For example, the following things will be parsed as single
1124 sub- or superscripts.
1125
1126 10^24 or 10^tau several digits will be considered 1 item
1127 10^-12 or 10^-tau a leading sign with digits or a word
1128 x^2-y^3 will be read as x^2 - y^3, because items are
1129 terminated by almost any nonword/nondigit char.
1130 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1131
1132 Still, ambiguity is possible - so when in doubt use {} to enclose the
1133 sub/superscript.
1134 In ASCII export, this option has no effect.
1135
1136 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1137 :group 'org-export
1138 :type 'boolean)
1139
1140 (defcustom org-export-with-TeX-macros t
1141 "Non-nil means, interpret simple TeX-like macros when exporting.
1142 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1143 No only real TeX macros will work here, but the standard HTML entities
1144 for math can be used as macro names as well. For a list of supported
1145 names in HTML export, see the constant `org-html-entities'.
1146 In ASCII export, this option has no effect.
1147
1148 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1149 :group 'org-export
1150 :type 'boolean)
1151
1152 (defcustom org-export-html-with-timestamp nil
1153 "Non-nil means, write `org-export-html-html-helper-timestamp'
1154 into the exported html text. Otherwise, the buffer will just be saved
1155 to a file."
1156 :group 'org-export
1157 :type 'boolean)
1158
1159 (defcustom org-export-html-html-helper-timestamp
1160 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1161 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1162 :group 'org-export
1163 :type 'string)
1164
1165 (defcustom org-export-ascii-show-new-buffer t
1166 "Non-nil means, popup buffer containing the exported ASCII text.
1167 Otherwise the buffer will just be saved to a file and stay hidden."
1168 :group 'org-export
1169 :type 'boolean)
1170
1171 (defcustom org-export-html-show-new-buffer nil
1172 "Non-nil means, popup buffer containing the exported html text.
1173 Otherwise, the buffer will just be saved to a file and stay hidden."
1174 :group 'org-export
1175 :type 'boolean)
1176
1177
1178 (defgroup org-faces nil
1179 "Faces for highlighting in Org-mode."
1180 :tag "Org Faces"
1181 :group 'org)
1182
1183 (defface org-level-1-face ;; font-lock-function-name-face
1184 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1185 (((class color) (background light)) (:foreground "Blue"))
1186 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1187 (t (:inverse-video t :bold t)))
1188 "Face used for level 1 headlines."
1189 :group 'org-faces)
1190
1191 (defface org-level-2-face ;; font-lock-variable-name-face
1192 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1193 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1194 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1195 (t (:bold t :italic t)))
1196 "Face used for level 2 headlines."
1197 :group 'org-faces)
1198
1199 (defface org-level-3-face ;; font-lock-keyword-face
1200 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1201 (((class color) (background light)) (:foreground "Purple"))
1202 (((class color) (background dark)) (:foreground "Cyan"))
1203 (t (:bold t)))
1204 "Face used for level 3 headlines."
1205 :group 'org-faces)
1206
1207 (defface org-level-4-face ;; font-lock-comment-face
1208 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1209 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1210 (((class color) (background light)) (:foreground "Firebrick"))
1211 (((class color) (background dark)) (:foreground "chocolate1"))
1212 (t (:bold t :italic t)))
1213 "Face used for level 4 headlines."
1214 :group 'org-faces)
1215
1216 (defface org-level-5-face ;; font-lock-type-face
1217 '((((type tty) (class color)) (:foreground "green"))
1218 (((class color) (background light)) (:foreground "ForestGreen"))
1219 (((class color) (background dark)) (:foreground "PaleGreen"))
1220 (t (:bold t :underline t)))
1221 "Face used for level 5 headlines."
1222 :group 'org-faces)
1223
1224 (defface org-level-6-face ;; font-lock-constant-face
1225 '((((type tty) (class color)) (:foreground "magenta"))
1226 (((class color) (background light)) (:foreground "CadetBlue"))
1227 (((class color) (background dark)) (:foreground "Aquamarine"))
1228 (t (:bold t :underline t)))
1229 "Face used for level 6 headlines."
1230 :group 'org-faces)
1231
1232 (defface org-level-7-face ;; font-lock-builtin-face
1233 '((((type tty) (class color)) (:foreground "blue" :weight light))
1234 (((class color) (background light)) (:foreground "Orchid"))
1235 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1236 (t (:bold t)))
1237 "Face used for level 7 headlines."
1238 :group 'org-faces)
1239
1240 (defface org-level-8-face ;; font-lock-string-face
1241 '((((type tty) (class color)) (:foreground "green"))
1242 (((class color) (background light)) (:foreground "RosyBrown"))
1243 (((class color) (background dark)) (:foreground "LightSalmon"))
1244 (t (:italic t)))
1245 "Face used for level 8 headlines."
1246 :group 'org-faces)
1247
1248 (defface org-warning-face ;; font-lock-warning-face
1249 '((((type tty) (class color)) (:foreground "red"))
1250 (((class color) (background light)) (:foreground "Red" :bold t))
1251 (((class color) (background dark)) (:foreground "Red1" :bold t))
1252 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1253 (t (:inverse-video t :bold t)))
1254 "Face for deadlines and TODO keywords."
1255 :group 'org-faces)
1256
1257 (defcustom org-fontify-done-headline nil
1258 "Non-nil means, change the face of a headline if it is marked DONE.
1259 Normally, only the TODO/DONE keyword indicates the state of a headline.
1260 When this is non-nil, the headline after the keyword is set to the
1261 `org-headline-done-face' as an additional indication."
1262 :group 'org-faces
1263 :type 'boolean)
1264
1265 (defface org-headline-done-face ;; font-lock-string-face
1266 '((((type tty) (class color)) (:foreground "green"))
1267 (((class color) (background light)) (:foreground "RosyBrown"))
1268 (((class color) (background dark)) (:foreground "LightSalmon"))
1269 (t (:italic t)))
1270 "Face used to indicate that a headline is DONE. See also the variable
1271 `org-fontify-done-headline'."
1272 :group 'org-faces)
1273
1274 ;; Inheritance does not yet work for xemacs. So we just copy...
1275
1276 (defface org-deadline-announce-face
1277 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1278 (((class color) (background light)) (:foreground "Blue"))
1279 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1280 (t (:inverse-video t :bold t)))
1281 "Face for upcoming deadlines."
1282 :group 'org-faces)
1283
1284 (defface org-scheduled-today-face
1285 '((((type tty) (class color)) (:foreground "green"))
1286 (((class color) (background light)) (:foreground "DarkGreen"))
1287 (((class color) (background dark)) (:foreground "PaleGreen"))
1288 (t (:bold t :underline t)))
1289 "Face for items scheduled for a certain day."
1290 :group 'org-faces)
1291
1292 (defface org-scheduled-previously-face
1293 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1294 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1295 (((class color) (background light)) (:foreground "Firebrick"))
1296 (((class color) (background dark)) (:foreground "chocolate1"))
1297 (t (:bold t :italic t)))
1298 "Face for items scheduled previously, and not yet done."
1299 :group 'org-faces)
1300
1301 (defface org-link-face
1302 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1303 (((class color) (background light)) (:foreground "Purple"))
1304 (((class color) (background dark)) (:foreground "Cyan"))
1305 (t (:bold t)))
1306 "Face for links."
1307 :group 'org-faces)
1308
1309 (defface org-done-face ;; font-lock-type-face
1310 '((((type tty) (class color)) (:foreground "green"))
1311 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1312 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1313 (t (:bold t :underline t)))
1314 "Face used for DONE."
1315 :group 'org-faces)
1316
1317 (defface org-table-face ;; font-lock-function-name-face
1318 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1319 (((class color) (background light)) (:foreground "Blue"))
1320 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1321 (t (:inverse-video t :bold t)))
1322 "Face used for tables."
1323 :group 'org-faces)
1324
1325 (defvar org-level-faces
1326 '(
1327 org-level-1-face
1328 org-level-2-face
1329 org-level-3-face
1330 org-level-4-face
1331 org-level-5-face
1332 org-level-6-face
1333 org-level-7-face
1334 org-level-8-face
1335 ))
1336 (defvar org-n-levels (length org-level-faces))
1337
1338 ;; Tell the compiler about dynamically scoped variables,
1339 ;; and variables from other packages
1340 (eval-when-compile
1341 (defvar zmacs-regions)
1342 (defvar original-date)
1343 (defvar org-transient-mark-mode)
1344 (defvar org-old-auto-fill-inhibit-regexp)
1345 (defvar orgtbl-mode-menu)
1346 (defvar org-html-entities)
1347 (defvar org-goto-start-pos)
1348 (defvar org-cursor-color)
1349 (defvar org-time-was-given)
1350 (defvar org-ts-what)
1351 (defvar timecnt)
1352 (defvar levels-open)
1353 (defvar title)
1354 (defvar author)
1355 (defvar email)
1356 (defvar text)
1357 (defvar entry)
1358 (defvar date)
1359 (defvar language)
1360 (defvar options)
1361 (defvar ans1)
1362 (defvar ans2)
1363 (defvar starting-day)
1364 (defvar include-all-loc)
1365 (defvar vm-message-pointer)
1366 (defvar vm-folder-directory)
1367 (defvar wl-summary-buffer-elmo-folder)
1368 (defvar wl-summary-buffer-folder-name)
1369 (defvar gnus-group-name)
1370 (defvar gnus-article-current)
1371 (defvar w3m-current-url)
1372 (defvar org-selected-point)
1373 (defvar calendar-mode-map)
1374 (defvar remember-save-after-remembering)
1375 (defvar remember-data-file))
1376
1377
1378 ;;; Define the mode
1379
1380 (defvar org-mode-map (copy-keymap outline-mode-map)
1381 "Keymap for Org-mode.")
1382
1383 (defvar org-struct-menu)
1384 (defvar org-org-menu)
1385
1386 ;;;###autoload
1387 (defun org-mode (&optional arg)
1388 "Outline-based notes management and organizer, alias
1389 \"Carstens outline-mode for keeping track of everything.\"
1390
1391 Org-mode develops organizational tasks around a NOTES file which
1392 contains information about projects as plain text. Org-mode is
1393 implemented on top of outline-mode, which is ideal to keep the content
1394 of large files well structured. It supports ToDo items, deadlines and
1395 time stamps, which magically appear in the diary listing of the Emacs
1396 calendar. Tables are easily created with a built-in table editor.
1397 Plain text URL-like links connect to websites, emails (VM), Usenet
1398 messages (Gnus), BBDB entries, and any files related to the project.
1399 For printing and sharing of notes, an Org-mode file (or a part of it)
1400 can be exported as a well-structured ASCII or HTML file.
1401
1402 The following commands are available:
1403
1404 \\{org-mode-map}"
1405 (interactive "P")
1406 (outline-mode)
1407 (setq major-mode 'org-mode)
1408 (setq mode-name "Org")
1409 (use-local-map org-mode-map)
1410 (easy-menu-add org-org-menu)
1411 (org-install-agenda-files-menu)
1412 (setq outline-regexp "\\*+")
1413 (if org-startup-truncated (setq truncate-lines t))
1414 (org-set-regexps-and-options)
1415 (set (make-local-variable 'font-lock-unfontify-region-function)
1416 'org-unfontify-region)
1417 ;; Activate before-change-function
1418 (set (make-local-variable 'org-table-may-need-update) t)
1419 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1420 (add-hook 'before-change-functions 'org-before-change-function nil
1421 'local)
1422 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1423 (set (make-local-variable 'auto-fill-inhibit-regexp)
1424 (concat "\\*"
1425 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1426 (concat
1427 "\\|[ \t]*["
1428 (if org-enable-table-editor "|" "")
1429 (if org-enable-fixed-width-editor ":" "")
1430 "]"))))
1431 ;; Hook, and startup actions
1432 (if (or arg
1433 (and org-insert-mode-line-in-empty-file
1434 (interactive-p)
1435 (= (point-min) (point-max))))
1436 (save-excursion
1437 (goto-char (point-min))
1438 (insert " -*- mode: org -*-\n\n")))
1439 (run-hooks 'org-mode-hook)
1440 (unless (boundp 'org-inhibit-startup)
1441 (if org-startup-with-deadline-check
1442 (call-interactively 'org-check-deadlines)
1443 (cond
1444 ((eq org-startup-folded t)
1445 (org-cycle))
1446 ((eq org-startup-folded 'contents)
1447 (org-cycle) (org-cycle))))))
1448
1449 ;;; Font-Lock stuff
1450
1451 (defvar org-mouse-map (make-sparse-keymap))
1452 (define-key org-mouse-map
1453 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1454 (define-key org-mouse-map
1455 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1456
1457 (require 'font-lock)
1458
1459 (defconst org-link-regexp
1460 (if org-allow-space-in-links
1461 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^\t\n\r]+[^ \t\n\r]\\)"
1462 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ \t\n\r]+\\)"
1463 )
1464 "Regular expression for matching links.")
1465 (defconst org-ts-lengths
1466 (cons (length (format-time-string (car org-time-stamp-formats)))
1467 (length (format-time-string (cdr org-time-stamp-formats))))
1468 "This holds the lengths of the two different time formats.")
1469 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1470 "Regular expression for fast time stamp matching.")
1471 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1472 "Regular expression matching time strings for analysis.")
1473 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1474 "Regular expression matching time stamps, with groups.")
1475 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1476 "Regular expression matching a time stamp range.")
1477 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1478 org-ts-regexp "\\)?")
1479 "Regular expression matching a time stamp or time stamp range.")
1480
1481 (defun org-activate-links (limit)
1482 "Run through the buffer and add overlays to links."
1483 (if (re-search-forward org-link-regexp limit t)
1484 (progn
1485 (add-text-properties (match-beginning 0) (match-end 0)
1486 (list 'mouse-face 'highlight
1487 'keymap org-mouse-map))
1488 t)))
1489
1490 (defun org-activate-dates (limit)
1491 "Run through the buffer and add overlays to dates."
1492 (if (re-search-forward org-tsr-regexp limit t)
1493 (progn
1494 (add-text-properties (match-beginning 0) (match-end 0)
1495 (list 'mouse-face 'highlight
1496 'keymap org-mouse-map))
1497 t)))
1498
1499
1500 (defun org-font-lock-level ()
1501 (save-excursion
1502 (org-back-to-heading t)
1503 (- (match-end 0) (match-beginning 0))))
1504
1505 (defun org-set-font-lock-defaults ()
1506 (let ((org-font-lock-extra-keywords
1507 (list
1508 '(org-activate-links (0 'org-link-face))
1509 '(org-activate-dates (0 'org-link-face))
1510 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1511 '(1 'org-warning-face t))
1512 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning-face t))
1513 (list (concat "\\<" org-deadline-string) '(0 'org-warning-face t))
1514 (list (concat "\\<" org-scheduled-string) '(0 'org-warning-face t))
1515 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1516 ;; (3 'bold))
1517 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1518 ;; (3 'italic))
1519 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1520 ;; (3 'underline))
1521 '("\\<FIXME\\>" (0 'org-warning-face t))
1522 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1523 '(1 'org-warning-face t))
1524 '("^#.*" (0 'font-lock-comment-face t))
1525 (if org-fontify-done-headline
1526 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1527 '(1 'org-done-face t) '(2 'org-headline-done-face t))
1528 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1529 '(1 'org-done-face t)))
1530 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1531 (1 'org-table-face t))
1532 '("^[ \t]*\\(:.*\\)" (1 'org-table-face t)))))
1533 (set (make-local-variable 'org-font-lock-keywords)
1534 (append
1535 (if org-noutline-p ; FIXME: I am not sure if eval will work
1536 ; on XEmacs if noutline is ever ported
1537 '((eval . (list "^\\(\\*+\\).*"
1538 0 '(nth
1539 (% (- (match-end 1) (match-beginning 1) 1)
1540 org-n-levels)
1541 org-level-faces)
1542 nil t)))
1543 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1544 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1545 org-n-levels)
1546 org-level-faces)
1547 nil t))))
1548 org-font-lock-extra-keywords))
1549 (set (make-local-variable 'font-lock-defaults)
1550 '(org-font-lock-keywords t nil nil backward-paragraph))
1551 (kill-local-variable 'font-lock-keywords) nil))
1552
1553 (defvar org-font-lock-keywords nil)
1554
1555 (defun org-unfontify-region (beg end &optional maybe_loudly)
1556 "Remove fontification and activation overlays from links."
1557 (font-lock-default-unfontify-region beg end)
1558 (let* ((modified (buffer-modified-p)) ;; FIXME: Why did I add this???
1559 (buffer-undo-list t)
1560 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1561 (inhibit-modification-hooks t)
1562 deactivate-mark buffer-file-name buffer-file-truename)
1563 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1564
1565 ;;; Visibility cycling
1566
1567 (defvar org-cycle-global-status nil)
1568 (defvar org-cycle-subtree-status nil)
1569 (defun org-cycle (&optional arg)
1570 "Visibility cycling for Org-mode.
1571
1572 - When this function is called with a prefix argument, rotate the entire
1573 buffer through 3 states (global cycling)
1574 1. OVERVIEW: Show only top-level headlines.
1575 2. CONTENTS: Show all headlines of all levels, but no body text.
1576 3. SHOW ALL: Show everything.
1577
1578 - When point is at the beginning of a headline, rotate the subtree started
1579 by this line through 3 different states (local cycling)
1580 1. FOLDED: Only the main headline is shown.
1581 2. CHILDREN: The main headline and the direct children are shown. From
1582 this state, you can move to one of the children and
1583 zoom in further.
1584 3. SUBTREE: Show the entire subtree, including body text.
1585
1586 - When there is a numeric prefix, go ARG levels up and do a `show-subtree',
1587 keeping cursor position.
1588
1589 - When point is not at the beginning of a headline, execute
1590 `indent-relative', like TAB normally does. See the option
1591 `org-cycle-emulate-tab' for details.
1592
1593 - Special case: if point is the the beginning of the buffer and there is
1594 no headline in line 1, this function will act as if called with prefix arg."
1595 (interactive "P")
1596
1597 (if (or (and (bobp) (not (looking-at outline-regexp)))
1598 (equal arg '(4)))
1599 ;; special case: use global cycling
1600 (setq arg t))
1601
1602 (cond
1603
1604 ((org-at-table-p 'any)
1605 ;; Enter the table or move to the next field in the table
1606 (or (org-table-recognize-table.el)
1607 (progn
1608 (org-table-justify-field-maybe)
1609 (org-table-next-field))))
1610
1611 ((eq arg t) ;; Global cycling
1612
1613 (cond
1614 ((and (eq last-command this-command)
1615 (eq org-cycle-global-status 'overview))
1616 ;; We just created the overview - now do table of contents
1617 ;; This can be slow in very large buffers, so indicate action
1618 (message "CONTENTS...")
1619 (save-excursion
1620 ;; Visit all headings and show their offspring
1621 (goto-char (point-max))
1622 (catch 'exit
1623 (while (and (progn (condition-case nil
1624 (outline-previous-visible-heading 1)
1625 (error (goto-char (point-min))))
1626 t)
1627 (looking-at outline-regexp))
1628 (show-branches)
1629 (if (bobp) (throw 'exit nil))))
1630 (message "CONTENTS...done"))
1631 (setq org-cycle-global-status 'contents)
1632 (run-hook-with-args 'org-cycle-hook 'contents))
1633
1634 ((and (eq last-command this-command)
1635 (eq org-cycle-global-status 'contents))
1636 ;; We just showed the table of contents - now show everything
1637 (show-all)
1638 (message "SHOW ALL")
1639 (setq org-cycle-global-status 'all)
1640 (run-hook-with-args 'org-cycle-hook 'all))
1641
1642 (t
1643 ;; Default action: go to overview
1644 (hide-sublevels 1)
1645 (message "OVERVIEW")
1646 (setq org-cycle-global-status 'overview)
1647 (run-hook-with-args 'org-cycle-hook 'overview))))
1648
1649 ((integerp arg)
1650 ;; Show-subtree, ARG levels up from here.
1651 (save-excursion
1652 (org-back-to-heading)
1653 (outline-up-heading arg)
1654 (show-subtree)))
1655
1656 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1657 ;; At a heading: rotate between three different views
1658 (org-back-to-heading)
1659 (let ((goal-column 0) beg eoh eol eos nxh)
1660 ;; First, some boundaries
1661 (save-excursion
1662 (org-back-to-heading) (setq beg (point))
1663 (save-excursion
1664 (beginning-of-line 2)
1665 (while (and (not (eobp)) ;; this is like `next-line'
1666 (get-char-property (1- (point)) 'invisible))
1667 (beginning-of-line 2)) (setq eol (point)))
1668 (outline-end-of-heading) (setq eoh (point))
1669 (outline-end-of-subtree) (setq eos (point))
1670 (outline-next-heading) (setq nxh (point)))
1671 ;; Find out what to do next and set `this-command'
1672 (cond
1673 ((= eos eoh)
1674 ;; Nothing is hidden behind this heading
1675 (message "EMPTY ENTRY")
1676 (setq org-cycle-subtree-status nil))
1677 ((>= eol eos)
1678 ;; Entire subtree is hidden in one line: open it
1679 (show-entry)
1680 (show-children)
1681 (message "CHILDREN")
1682 (setq org-cycle-subtree-status 'children)
1683 (run-hook-with-args 'org-cycle-hook 'children))
1684 ((and (eq last-command this-command)
1685 (eq org-cycle-subtree-status 'children))
1686 ;; We just showed the children, now show everything.
1687 (show-subtree)
1688 (message "SUBTREE")
1689 (setq org-cycle-subtree-status 'subtree)
1690 (run-hook-with-args 'org-cycle-hook 'subtree))
1691 (t
1692 ;; Default action: hide the subtree.
1693 (hide-subtree)
1694 (message "FOLDED")
1695 (setq org-cycle-subtree-status 'folded)
1696 (run-hook-with-args 'org-cycle-hook 'folded)))))
1697
1698 ;; TAB emulation
1699 (buffer-read-only (org-back-to-heading))
1700 ((if (and (eq org-cycle-emulate-tab 'white)
1701 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
1702 t
1703 (eq org-cycle-emulate-tab t))
1704 (if (and (looking-at "[ \n\r\t]")
1705 (string-match "^[ \t]*$" (buffer-substring
1706 (point-at-bol) (point))))
1707 (progn
1708 (beginning-of-line 1)
1709 (and (looking-at "[ \t]+") (replace-match ""))))
1710 (indent-relative))
1711
1712 (t (save-excursion
1713 (org-back-to-heading)
1714 (org-cycle)))))
1715
1716 (defun org-optimize-window-after-visibility-change (state)
1717 "Adjust the window after a change in outline visibility.
1718 This function is the default value of the hook `org-cycle-hook'."
1719 (cond
1720 ((eq state 'overview) (org-first-headline-recenter 1))
1721 ((eq state 'content) nil)
1722 ((eq state 'all) nil)
1723 ((eq state 'folded) nil)
1724 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
1725 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
1726
1727 (defun org-subtree-end-visible-p ()
1728 "Is the end of the current subtree visible?"
1729 (pos-visible-in-window-p
1730 (save-excursion (outline-end-of-subtree) (point))))
1731
1732 (defun org-first-headline-recenter (&optional N)
1733 "Move cursor to the first headline and recenter the headline.
1734 Optional argument N means, put the headline into the Nth line of the window."
1735 (goto-char (point-min))
1736 (re-search-forward (concat "^" outline-regexp))
1737 (beginning-of-line)
1738 (recenter (prefix-numeric-value N)))
1739
1740 (defvar org-goto-window-configuration nil)
1741 (defvar org-goto-marker nil)
1742 (defvar org-goto-map (make-sparse-keymap))
1743 (let ((cmds '(isearch-forward isearch-backward)) cmd)
1744 (while (setq cmd (pop cmds))
1745 (substitute-key-definition cmd cmd org-goto-map global-map)))
1746 (define-key org-goto-map [(return)] 'org-goto-ret)
1747 (define-key org-goto-map [(left)] 'org-goto-left)
1748 (define-key org-goto-map [(right)] 'org-goto-right)
1749 (define-key org-goto-map [(?q)] 'org-goto-quit)
1750 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
1751 (define-key org-goto-map [(tab)] 'org-cycle)
1752 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
1753 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
1754 (define-key org-goto-map "n" 'outline-next-visible-heading)
1755 (define-key org-goto-map "p" 'outline-previous-visible-heading)
1756 (define-key org-goto-map "f" 'outline-forward-same-level)
1757 (define-key org-goto-map "b" 'outline-backward-same-level)
1758 (define-key org-goto-map "u" 'outline-up-heading)
1759 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
1760 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
1761 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
1762 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
1763 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
1764 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
1765 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
1766
1767 (defconst org-goto-help
1768 "Select a location to jump to, press RET
1769 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
1770
1771 (defun org-goto ()
1772 "Go to a different location of the document, keeping current visibility.
1773
1774 When you want to go to a different location in a document, the fastest way
1775 is often to fold the entire buffer and then dive into the tree. This
1776 method has the disadvantage, that the previous location will be folded,
1777 which may not be what you want.
1778
1779 This command works around this by showing a copy of the current buffer in
1780 overview mode. You can dive into the tree in that copy, to find the
1781 location you want to reach. When pressing RET, the command returns to the
1782 original buffer in which the visibility is still unchanged. It then jumps
1783 to the new location, making it and the headline hierarchy above it visible."
1784 (interactive)
1785 (let* ((org-goto-start-pos (point))
1786 (selected-point
1787 (org-get-location (current-buffer) org-goto-help)))
1788 (if selected-point
1789 (progn
1790 (goto-char selected-point)
1791 (if (org-invisible-p) (org-show-hierarchy-above)))
1792 (error "Quit"))))
1793
1794 (defun org-get-location (buf help)
1795 "Let the user select a location in the Org-mode buffer BUF.
1796 This function uses a recursive edit. It returns the selected position
1797 or nil."
1798 (let (org-selected-point)
1799 (save-excursion
1800 (save-window-excursion
1801 (delete-other-windows)
1802 (switch-to-buffer (get-buffer-create "*org-goto*"))
1803 (with-output-to-temp-buffer "*Help*"
1804 (princ help))
1805 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
1806 (setq buffer-read-only nil)
1807 (erase-buffer)
1808 (insert-buffer buf)
1809 (let ((org-startup-truncated t)
1810 (org-startup-folded t)
1811 (org-startup-with-deadline-check nil))
1812 (org-mode))
1813 (setq buffer-read-only t)
1814 (if (boundp 'org-goto-start-pos)
1815 (goto-char org-goto-start-pos)
1816 (goto-char (point-min)))
1817 (org-beginning-of-line)
1818 (message "Select location and press RET")
1819 ;; now we make sure that during selection, ony very few keys work
1820 ;; and that it is impossible to switch to another window.
1821 (let ((gm (current-global-map))
1822 (overriding-local-map org-goto-map))
1823 (unwind-protect
1824 (progn
1825 (use-global-map org-goto-map)
1826 (recursive-edit))
1827 (use-global-map gm)))))
1828 (kill-buffer "*org-goto*")
1829 org-selected-point))
1830
1831 ;; FIXME: It may not be a good idea to temper with the prefix argument...
1832 (defun org-goto-ret (&optional arg)
1833 "Finish org-goto by going to the new location."
1834 (interactive "P")
1835 (setq org-selected-point (point)
1836 current-prefix-arg arg)
1837 (throw 'exit nil))
1838
1839 (defun org-goto-left (&optional arg)
1840 "Finish org-goto by going to the new location."
1841 (interactive "P")
1842 (if (org-on-heading-p)
1843 (progn
1844 (beginning-of-line 1)
1845 (setq org-selected-point (point)
1846 current-prefix-arg (- (match-end 0) (match-beginning 0)))
1847 (throw 'exit nil))
1848 (error "Not on a heading")))
1849
1850 (defun org-goto-right (&optional arg)
1851 "Finish org-goto by going to the new location."
1852 (interactive "P")
1853 (if (org-on-heading-p)
1854 (progn
1855 (outline-end-of-subtree)
1856 (or (eobp) (forward-char 1))
1857 (setq org-selected-point (point)
1858 current-prefix-arg (- (match-end 0) (match-beginning 0)))
1859 (throw 'exit nil))
1860 (error "Not on a heading")))
1861
1862 (defun org-goto-quit ()
1863 "Finish org-goto without cursor motion."
1864 (interactive)
1865 (setq org-selected-point nil)
1866 (throw 'exit nil))
1867
1868 ;;; Promotion, Demotion, Inserting new headlines
1869
1870 (defvar org-ignore-region nil
1871 "To temporarily disable the active region.")
1872
1873 (defun org-insert-heading (&optional arg)
1874 "Insert a new heading with same depth at point."
1875 (interactive "P")
1876 (let* ((head (save-excursion
1877 (condition-case nil
1878 (org-back-to-heading)
1879 (error (outline-next-heading)))
1880 (prog1 (match-string 0)
1881 (funcall outline-level)))))
1882 (unless (bolp) (newline))
1883 (insert head)
1884 (unless (eolp)
1885 (save-excursion (newline-and-indent)))
1886 (unless (equal (char-before) ?\ )
1887 (insert " "))
1888 (run-hooks 'org-insert-heading-hook)))
1889
1890 (defun org-insert-todo-heading (arg)
1891 "Insert a new heading with the same level and TODO state as current heading.
1892 If the heading has no TODO state, or if the state is DONE, use the first
1893 state (TODO by default). Also with prefix arg, force first state."
1894 (interactive "P")
1895 (org-insert-heading)
1896 (save-excursion
1897 (org-back-to-heading)
1898 (outline-previous-heading)
1899 (looking-at org-todo-line-regexp))
1900 (if (or arg
1901 (not (match-beginning 2))
1902 (equal (match-string 2) org-done-string))
1903 (insert (car org-todo-keywords) " ")
1904 (insert (match-string 2) " ")))
1905
1906 (defun org-promote-subtree (&optional arg)
1907 "Promote the entire subtree.
1908 See also `org-promote'."
1909 (interactive "P")
1910 (org-map-tree 'org-promote))
1911
1912 (defun org-demote-subtree (&optional arg)
1913 "Demote the entire subtree. See `org-demote'.
1914 See also `org-promote'."
1915 (interactive "P")
1916 (org-map-tree 'org-demote))
1917
1918 (defun org-do-promote (&optional arg)
1919 "Promote the current heading higher up the tree.
1920 If the region is active in transient-mark-mode, promote all headings
1921 in the region."
1922 (interactive "P")
1923 (save-excursion
1924 (if (org-region-active-p)
1925 (org-map-region 'org-promote (region-beginning) (region-end))
1926 (org-promote)))
1927 (org-fix-position-after-promote))
1928
1929 (defun org-do-demote (&optional arg)
1930 "Demote the current heading lower down the tree.
1931 If the region is active in transient-mark-mode, demote all headings
1932 in the region."
1933 (interactive "P")
1934 (save-excursion
1935 (if (org-region-active-p)
1936 (org-map-region 'org-demote (region-beginning) (region-end))
1937 (org-demote)))
1938 (org-fix-position-after-promote))
1939
1940 (defun org-fix-position-after-promote ()
1941 "Make sure that after pro/demotion cursor position is right."
1942 (and (equal (char-after) ?\ )
1943 (equal (char-before) ?*)
1944 (forward-char 1)))
1945
1946 (defun org-promote ()
1947 "Promote the current heading higher up the tree.
1948 If the region is active in transient-mark-mode, promote all headings
1949 in the region."
1950 (org-back-to-heading t)
1951 (let* ((level (save-match-data (funcall outline-level)))
1952 (up-head (make-string (1- level) ?*)))
1953 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover."))
1954 (replace-match up-head nil t)
1955 (if org-adapt-indentation
1956 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
1957
1958 (defun org-demote ()
1959 "Demote the current heading lower down the tree.
1960 If the region is active in transient-mark-mode, demote all headings
1961 in the region."
1962 (org-back-to-heading t)
1963 (let* ((level (save-match-data (funcall outline-level)))
1964 (down-head (make-string (1+ level) ?*)))
1965 (replace-match down-head nil t)
1966 (if org-adapt-indentation
1967 (org-fixup-indentation "^ " " " "^\\S-"))))
1968
1969 (defun org-map-tree (fun)
1970 "Call FUN for every heading underneath the current one."
1971 (org-back-to-heading)
1972 (let ((level (outline-level)))
1973 (save-excursion
1974 (funcall fun)
1975 (while (and (progn
1976 (outline-next-heading)
1977 (> (funcall outline-level) level))
1978 (not (eobp)))
1979 (funcall fun)))))
1980
1981 (defun org-map-region (fun beg end)
1982 "Call FUN for every heading between BEG and END."
1983 (let ((org-ignore-region t))
1984 (save-excursion
1985 (setq end (copy-marker end))
1986 (goto-char beg)
1987 ;; (if (fboundp 'deactivate-mark) (deactivate-mark))
1988 ;; (if (fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region))
1989 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
1990 (< (point) end))
1991 (funcall fun))
1992 (while (and (progn
1993 (outline-next-heading)
1994 (< (point) end))
1995 (not (eobp)))
1996 (funcall fun)))))
1997
1998 (defun org-fixup-indentation (from to prohibit)
1999 "Change the indentation in the current entry by re-replacing FROM with TO.
2000 However, if the regexp PROHIBIT matches at all, don't do anything.
2001 This is being used to change indentation along with the length of the
2002 heading marker. But if there are any lines which are not indented, nothing
2003 is changed at all."
2004 (save-excursion
2005 (let ((end (save-excursion (outline-next-heading)
2006 (point-marker))))
2007 (unless (save-excursion (re-search-forward prohibit end t))
2008 (while (re-search-forward from end t)
2009 (replace-match to)
2010 (beginning-of-line 2)))
2011 (move-marker end nil))))
2012
2013 ;;; Vertical tree motion, cutting and pasting of subtrees
2014
2015 (defun org-move-subtree-up (&optional arg)
2016 "Move the current subtree up past ARG headlines of the same level."
2017 (interactive "p")
2018 (org-move-subtree-down (- (prefix-numeric-value arg))))
2019
2020 (defun org-move-subtree-down (&optional arg)
2021 "Move the current subtree down past ARG headlines of the same level."
2022 (interactive "p")
2023 (setq arg (prefix-numeric-value arg))
2024 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2025 'outline-get-last-sibling))
2026 (ins-point (make-marker))
2027 (cnt (abs arg))
2028 beg end txt folded)
2029 ;; Select the tree
2030 (org-back-to-heading)
2031 (setq beg (point))
2032 (save-match-data
2033 (save-excursion (outline-end-of-heading)
2034 (setq folded (org-invisible-p)))
2035 (outline-end-of-subtree))
2036 (outline-next-heading)
2037 (setq end (point))
2038 ;; Find insertion point, with error handling
2039 (goto-char beg)
2040 (while (> cnt 0)
2041 (or (and (funcall movfunc) (looking-at outline-regexp))
2042 (progn (goto-char beg)
2043 (error "Cannot move past superior level or buffer limit")))
2044 (setq cnt (1- cnt)))
2045 (if (> arg 0)
2046 ;; Moving forward - still need to move over subtree
2047 (progn (outline-end-of-subtree)
2048 (outline-next-heading)
2049 (if (not (or (looking-at (concat "^" outline-regexp))
2050 (bolp)))
2051 (newline))))
2052 (move-marker ins-point (point))
2053 (setq txt (buffer-substring beg end))
2054 (delete-region beg end)
2055 (insert txt)
2056 (goto-char ins-point)
2057 (if folded (hide-subtree))
2058 (move-marker ins-point nil)))
2059
2060 (defvar org-subtree-clip ""
2061 "Clipboard for cut and paste of subtrees.
2062 This is actually only a copy of the kill, because we use the normal kill
2063 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2064
2065 (defvar org-subtree-clip-folded nil
2066 "Was the last copied subtree folded?
2067 This is used to fold the tree back after pasting.")
2068
2069 (defun org-cut-subtree (&optional arg)
2070 "Cut the current subtree into the clipboard.
2071 This is a short-hand for marking the subtree and then cutting it."
2072 (interactive "p")
2073 (org-copy-subtree arg 'cut))
2074
2075 (defun org-copy-subtree (&optional arg cut)
2076 "Cut the current subtree into the clipboard.
2077 This is a short-hand for marking the subtree and then copying it.
2078 If CUT is non nil, actually cut the subtree."
2079 (interactive "p")
2080 (let (beg end folded)
2081 (org-back-to-heading)
2082 (setq beg (point))
2083 (save-match-data
2084 (save-excursion (outline-end-of-heading)
2085 (setq folded (org-invisible-p)))
2086 (outline-end-of-subtree))
2087 (if (equal (char-after) ?\n) (forward-char 1))
2088 (setq end (point))
2089 (goto-char beg)
2090 (when (> end beg)
2091 (setq org-subtree-clip-folded folded)
2092 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2093 (setq org-subtree-clip (current-kill 0))
2094 (message "%s: Subtree with %d characters"
2095 (if cut "Cut" "Copied")
2096 (length org-subtree-clip)))))
2097
2098 (defun org-paste-subtree (&optional level tree)
2099 "Paste the clipboard as a subtree, with modification of headline level.
2100 The entire subtree is promoted or demoted in order to match a new headline
2101 level. By default, the new level is derived from the visible headings
2102 before and after the insertion point, and taken to be the inferior headline
2103 level of the two. So if the previous visible heading is level 3 and the
2104 next is level 4 (or vice versa), level 4 will be used for insertion.
2105 This makes sure that the subtree remains an independent subtree and does
2106 not swallow low level entries.
2107
2108 You can also force a different level, either by using a numeric prefix
2109 argument, or by inserting the heading marker by hand. For example, if the
2110 cursor is after \"*****\", then the tree will be shifted to level 5.
2111
2112 If you want to insert the tree as is, just use \\[yank].
2113
2114 If optional TREE is given, use this text instead of the kill ring."
2115 (interactive "P")
2116 (unless (org-kill-is-subtree-p tree)
2117 (error
2118 (substitute-command-keys
2119 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2120 (let* ((txt (or tree (current-kill 0)))
2121 (^re (concat "^\\(" outline-regexp "\\)"))
2122 (re (concat "\\(" outline-regexp "\\)"))
2123 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2124
2125 (old-level (if (string-match ^re txt)
2126 (- (match-end 0) (match-beginning 0))
2127 -1))
2128 (force-level (cond (level (prefix-numeric-value level))
2129 ((string-match
2130 ^re_ (buffer-substring (point-at-bol) (point)))
2131 (- (match-end 0) (match-beginning 0)))
2132 (t nil)))
2133 (previous-level (save-excursion
2134 (outline-previous-visible-heading 1)
2135 (if (looking-at re)
2136 (- (match-end 0) (match-beginning 0))
2137 1)))
2138 (next-level (save-excursion
2139 (outline-next-visible-heading 1)
2140 (if (looking-at re)
2141 (- (match-end 0) (match-beginning 0))
2142 1)))
2143 (new-level (or force-level (max previous-level next-level)))
2144 (shift (if (or (= old-level -1)
2145 (= new-level -1)
2146 (= old-level new-level))
2147 0
2148 (- new-level old-level)))
2149 (shift1 shift)
2150 (delta (if (> shift 0) -1 1))
2151 (func (if (> shift 0) 'org-demote 'org-promote))
2152 beg end)
2153 ;; Remove the forces level indicator
2154 (if force-level
2155 (delete-region (point-at-bol) (point)))
2156 ;; Make sure we start at the beginning of an empty line
2157 (if (not (bolp)) (insert "\n"))
2158 (if (not (looking-at "[ \t]*$"))
2159 (progn (insert "\n") (backward-char 1)))
2160 ;; Paste
2161 (setq beg (point))
2162 (insert txt)
2163 (setq end (point))
2164 (goto-char beg)
2165 ;; Shift if necessary
2166 (if (= shift 0)
2167 (message "Pasted at level %d, without shift" new-level)
2168 (save-restriction
2169 (narrow-to-region beg end)
2170 (while (not (= shift 0))
2171 (org-map-region func (point-min) (point-max))
2172 (setq shift (+ delta shift)))
2173 (goto-char (point-min))
2174 (message "Pasted at level %d, with shift by %d levels"
2175 new-level shift1)))
2176 (if (and (eq org-subtree-clip (current-kill 0))
2177 org-subtree-clip-folded)
2178 ;; The tree was folded before it was killed/copied
2179 (hide-subtree))))
2180
2181 (defun org-kill-is-subtree-p (&optional txt)
2182 "Check if the current kill is an outline subtree, or a set of trees.
2183 Returns nil if kill does not start with a headline, or if the first
2184 headline level is not the largest headline level in the tree.
2185 So this will actually accept several entries of equal levels as well,
2186 which is OK for `org-paste-subtree'.
2187 If optional TXT is given, check this string instead of the current kill."
2188 (let* ((kill (or txt (current-kill 0) ""))
2189 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2190 (- (match-end 0) (match-beginning 0))))
2191 (re (concat "^" outline-regexp))
2192 (start 1))
2193 (if (not start-level)
2194 nil ;; does not even start with a heading
2195 (catch 'exit
2196 (while (setq start (string-match re kill (1+ start)))
2197 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2198 (throw 'exit nil)))
2199 t))))
2200
2201 ;;; Completion
2202
2203 (defun org-complete (&optional arg)
2204 "Perform completion on word at point.
2205 At the beginning of a headline, this completes TODO keywords as given in
2206 `org-todo-keywords'.
2207 If the current word is preceded by a backslash, completes the TeX symbols
2208 that are supported for HTML support.
2209 If the current word is preceded by \"#+\", completes special words for
2210 setting file options.
2211 At all other locations, this simply calls `ispell-complete-word'."
2212 (interactive "P")
2213 (catch 'exit
2214 (let* ((end (point))
2215 (beg (save-excursion
2216 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2217 (skip-chars-backward "a-zA-Z0-9_:")
2218 (point)))
2219 (texp (equal (char-before beg) ?\\))
2220 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2221 beg)
2222 "#+"))
2223 (pattern (buffer-substring-no-properties beg end))
2224 (completion-ignore-case opt)
2225 (type nil)
2226 (table (cond
2227 (opt
2228 (setq type :opt)
2229 (mapcar (lambda (x)
2230 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2231 (cons (match-string 2 x) (match-string 1 x)))
2232 (org-split-string (org-get-current-options) "\n")))
2233 (texp
2234 (setq type :tex)
2235 org-html-entities)
2236 ((string-match "\\`\\*+[ \t]*\\'"
2237 (buffer-substring (point-at-bol) beg))
2238 (setq type :todo)
2239 (mapcar 'list org-todo-keywords))
2240 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2241 (completion (try-completion pattern table)))
2242 (cond ((eq completion t)
2243 (if (equal type :opt)
2244 (insert (substring (cdr (assoc (upcase pattern) table))
2245 (length pattern)))))
2246 ((null completion)
2247 (message "Can't find completion for \"%s\"" pattern)
2248 (ding))
2249 ((not (string= pattern completion))
2250 (delete-region beg end)
2251 (if (string-match " +$" completion)
2252 (setq completion (replace-match "" t t completion)))
2253 (insert completion)
2254 (if (get-buffer-window "*Completions*")
2255 (delete-window (get-buffer-window "*Completions*")))
2256 (if (and (eq type :todo)
2257 (assoc completion table))
2258 (insert " "))
2259 (if (and (equal type :opt) (assoc completion table))
2260 (message (substitute-command-keys
2261 "Press \\[org-complete] again to insert example settings"))))
2262 (t
2263 (message "Making completion list...")
2264 (let ((list (sort (all-completions pattern table) 'string<)))
2265 (with-output-to-temp-buffer "*Completions*"
2266 (display-completion-list list)))
2267 (message "Making completion list...%s" "done"))))))
2268
2269 ;;; Comments, TODO and DEADLINE
2270
2271 (defun org-toggle-comment ()
2272 "Change the COMMENT state of an entry."
2273 (interactive)
2274 (save-excursion
2275 (org-back-to-heading)
2276 (if (looking-at (concat outline-regexp
2277 "\\( +\\<" org-comment-string "\\>\\)"))
2278 (replace-match "" t t nil 1)
2279 (if (looking-at outline-regexp)
2280 (progn
2281 (goto-char (match-end 0))
2282 (insert " " org-comment-string))))))
2283
2284 (defvar org-last-todo-state-is-todo nil
2285 "This is non-nil when the last TODO state change led to a TODO state.
2286 If the last change removed the TODO tag or switched to DONE, then
2287 this is nil.")
2288
2289 (defun org-todo (&optional arg)
2290 "Change the TODO state of an item.
2291 The state of an item is given by a keyword at the start of the heading,
2292 like
2293 *** TODO Write paper
2294 *** DONE Call mom
2295
2296 The different keywords are specified in the variable `org-todo-keywords'. By
2297 default the available states are \"TODO\" and \"DONE\".
2298 So for this example: when the item starts with TODO, it is changed to DONE.
2299 When it starts with DONE, the DONE is removed. And when neither TODO nor
2300 DONE are present, add TODO at the beginning of the heading.
2301
2302 With prefix arg, use completion to determined the new state. With numeric
2303 prefix arg, switch to that state."
2304 (interactive "P")
2305 (save-excursion
2306 (org-back-to-heading)
2307 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2308 (or (looking-at (concat " +" org-todo-regexp " *"))
2309 (looking-at " *"))
2310 (let* ((this (match-string 1))
2311 (completion-ignore-case t)
2312 (member (member this org-todo-keywords))
2313 (tail (cdr member))
2314 (state (cond
2315 ((equal arg '(4))
2316 ;; Read a state with completion
2317 (completing-read "State: " (mapcar (lambda(x) (list x))
2318 org-todo-keywords)
2319 nil t))
2320 (arg
2321 ;; user requests a specific state
2322 (nth (1- (prefix-numeric-value arg))
2323 org-todo-keywords))
2324 ((null member) (car org-todo-keywords))
2325 ((null tail) nil) ;; -> first entry
2326 ((eq org-todo-interpretation 'sequence)
2327 (car tail))
2328 ((memq org-todo-interpretation '(type priority))
2329 (if (eq this-command last-command)
2330 (car tail)
2331 (if (> (length tail) 0) org-done-string nil)))
2332 (t nil)))
2333 (next (if state (concat " " state " ") " ")))
2334 (replace-match next t t)
2335 (setq org-last-todo-state-is-todo
2336 (not (equal state org-done-string)))
2337 (run-hooks 'org-after-todo-state-change-hook)))
2338 ;; Fixup cursor location if close to the keyword
2339 (if (and (outline-on-heading-p)
2340 (not (bolp))
2341 (save-excursion (goto-char (point-at-bol))
2342 (looking-at org-todo-line-regexp))
2343 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2344 (progn
2345 (goto-char (or (match-end 2) (match-end 1)))
2346 (just-one-space))))
2347
2348 (defun org-show-todo-tree (arg)
2349 "Make a compact tree which shows all headlines marked with TODO.
2350 The tree will show the lines where the regexp matches, and all higher
2351 headlines above the match."
2352 (interactive "P")
2353 (let ((case-fold-search nil)
2354 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2355 (message "%d TODO entries found"
2356 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2357
2358 (defun org-deadline ()
2359 "Insert the DEADLINE: string to make a deadline.
2360 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2361 to modify it to the correct date."
2362 (interactive)
2363 (insert
2364 org-deadline-string " "
2365 (format-time-string (car org-time-stamp-formats)
2366 (org-read-date nil 'to-time)))
2367 (message (substitute-command-keys
2368 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2369
2370 (defun org-schedule ()
2371 "Insert the SCHEDULED: string to schedule a TODO item.
2372 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2373 to modify it to the correct date."
2374 (interactive)
2375 (insert
2376 org-scheduled-string " "
2377 (format-time-string (car org-time-stamp-formats)
2378 (org-read-date nil 'to-time)))
2379 (message (substitute-command-keys
2380 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2381
2382
2383 (defun org-occur (regexp &optional callback)
2384 "Make a compact tree which shows all matches of REGEXP.
2385 The tree will show the lines where the regexp matches, and all higher
2386 headlines above the match. It will also show the heading after the match,
2387 to make sure editing the matching entry is easy.
2388 if CALLBACK is non-nil, it is a function which is called to confirm
2389 that the match should indeed be shown."
2390 (interactive "sRegexp: ")
2391 (setq regexp (org-check-occur-regexp regexp))
2392 (let ((cnt 0))
2393 (save-excursion
2394 (goto-char (point-min))
2395 (hide-sublevels 1)
2396 (while (re-search-forward regexp nil t)
2397 (when (or (not callback)
2398 (funcall callback))
2399 (setq cnt (1+ cnt))
2400 (org-show-hierarchy-above))))
2401 (run-hooks 'org-occur-hook)
2402 (if (interactive-p)
2403 (message "%d match(es) for regexp %s" cnt regexp))
2404 cnt))
2405
2406 (defun org-show-hierarchy-above ()
2407 "Make sure point and the headings hierarchy above is visible."
2408 (if (org-on-heading-p t)
2409 (org-flag-heading nil) ; only show the heading
2410 (org-show-hidden-entry)) ; show entire entry
2411 (save-excursion
2412 (and org-show-following-heading
2413 (outline-next-heading)
2414 (org-flag-heading nil))) ; show the next heading
2415 (save-excursion ; show all higher headings
2416 (while (condition-case nil
2417 (progn (org-up-heading-all 1) t)
2418 (error nil))
2419 (org-flag-heading nil))))
2420
2421 ;;; Priorities
2422
2423 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2424 "Regular expression matching the priority indicator.")
2425
2426 (defvar org-remove-priority-next-time nil)
2427
2428 (defun org-priority-up ()
2429 "Increase the priority of the current item."
2430 (interactive)
2431 (org-priority 'up))
2432
2433 (defun org-priority-down ()
2434 "Decrease the priority of the current item."
2435 (interactive)
2436 (org-priority 'down))
2437
2438 (defun org-priority (&optional action)
2439 "Change the priority of an item by ARG.
2440 ACTION can be set, up, or down."
2441 (interactive)
2442 (setq action (or action 'set))
2443 (let (current new news have remove)
2444 (save-excursion
2445 (org-back-to-heading)
2446 (if (looking-at org-priority-regexp)
2447 (setq current (string-to-char (match-string 2))
2448 have t)
2449 (setq current org-default-priority))
2450 (cond
2451 ((eq action 'set)
2452 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2453 (setq new (read-char-exclusive))
2454 (cond ((equal new ?\ ) (setq remove t))
2455 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2456 (error "Priority must be between `%c' and `%c'"
2457 ?A org-lowest-priority))))
2458 ((eq action 'up)
2459 (setq new (1- current)))
2460 ((eq action 'down)
2461 (setq new (1+ current)))
2462 (t (error "Invalid action")))
2463 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2464 (setq news (format "%c" new))
2465 (if have
2466 (if remove
2467 (replace-match "" t t nil 1)
2468 (replace-match news t t nil 2))
2469 (if remove
2470 (error "No priority cookie found in line")
2471 (looking-at org-todo-line-regexp)
2472 (if (match-end 2)
2473 (progn
2474 (goto-char (match-end 2))
2475 (insert " [#" news "]"))
2476 (goto-char (match-beginning 3))
2477 (insert "[#" news "] ")))))
2478 (if remove
2479 (message "Priority removed")
2480 (message "Priority of current item set to %s" news))))
2481
2482
2483 (defun org-get-priority (s)
2484 "Find priority cookie and return priority."
2485 (save-match-data
2486 (if (not (string-match org-priority-regexp s))
2487 (* 1000 (- org-lowest-priority org-default-priority))
2488 (* 1000 (- org-lowest-priority
2489 (string-to-char (match-string 2 s)))))))
2490
2491 ;;; Timestamps
2492
2493 (defvar org-last-changed-timestamp nil)
2494
2495 (defun org-time-stamp (arg)
2496 "Prompt for a date/time and insert a time stamp.
2497 If the user specifies a time like HH:MM, or if this command is called
2498 with a prefix argument, the time stamp will contain date and time.
2499 Otherwise, only the date will be included. All parts of a date not
2500 specified by the user will be filled in from the current date/time.
2501 So if you press just return without typing anything, the time stamp
2502 will represent the current date/time. If there is already a timestamp
2503 at the cursor, it will be modified."
2504 (interactive "P")
2505 (let ((fmt (if arg (cdr org-time-stamp-formats)
2506 (car org-time-stamp-formats)))
2507 (org-time-was-given nil)
2508 time)
2509 (cond
2510 ((and (org-at-timestamp-p)
2511 (eq last-command 'org-time-stamp)
2512 (eq this-command 'org-time-stamp))
2513 (insert "--")
2514 (setq time (let ((this-command this-command))
2515 (org-read-date arg 'totime)))
2516 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2517 (insert (format-time-string fmt time)))
2518 ((org-at-timestamp-p)
2519 (setq time (let ((this-command this-command))
2520 (org-read-date arg 'totime)))
2521 (and (org-at-timestamp-p) (replace-match
2522 (setq org-last-changed-timestamp
2523 (format-time-string fmt time))
2524 t t))
2525 (message "Timestamp updated"))
2526 (t
2527 (setq time (let ((this-command this-command))
2528 (org-read-date arg 'totime)))
2529 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
2530 (insert (format-time-string fmt time))))))
2531
2532 ;;; FIXME: Make the function take "Fri" as "next friday"
2533 (defun org-read-date (&optional with-time to-time)
2534 "Read a date and make things smooth for the user.
2535 The prompt will suggest to enter an ISO date, but you can also enter anything
2536 which will at least partially be understood by `parse-time-string'.
2537 Unrecognized parts of the date will default to the current day, month ,year,
2538 hour and minute. For example,
2539 3-2-5 --> 2003-02-05
2540 feb 15 --> currentyear-02-15
2541 sep 12 9 --> 2009-09-12
2542 12:45 --> today 12:45
2543 22 sept 0:34 --> currentyear-09-22 0:34
2544 12 --> currentyear-currentmonth-12
2545 etc.
2546 The function understands only English month and weekday abbreviations,
2547 but this can be configured with the variables `parse-time-months' and
2548 `parse-time-weekdays'.
2549
2550 While prompting, a calendar is popped up - you can also select the
2551 date with the mouse (button 1). The calendar shows a period of three
2552 month. To scroll it to other months, use the keys `>' and `<'.
2553 If you don't like the calendar, turn it off with
2554 \(setq org-popup-calendar-for-date-prompt nil).
2555
2556 With optional argument TO-TIME, the date will immediately be converted
2557 to an internal time.
2558 With an optional argument WITH-TIME, the prompt will suggest to also
2559 insert a time. Note that when WITH-TIME is not set, you can still
2560 enter a time, and this function will inform the calling routine about
2561 this change. The calling routine may then choose to change the format
2562 used to insert the time stamp into the buffer to include the time."
2563 (let* ((default-time
2564 ;; Default time is either today, or, when entering a range,
2565 ;; the range start.
2566 (if (save-excursion
2567 (re-search-backward
2568 (concat org-ts-regexp "--\\=")
2569 (- (point) 20) t))
2570 (apply
2571 'encode-time
2572 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
2573 (parse-time-string (match-string 1))))
2574 (current-time)))
2575 (timestr (format-time-string
2576 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
2577 (prompt (format "YYYY-MM-DD [%s]: " timestr))
2578 ans ans1 ans2
2579 second minute hour day month year tl)
2580
2581 (if org-popup-calendar-for-date-prompt
2582 ;; Also show a calendar for date selection
2583 ;; Copied (with modifications) from planner.el by John Wiegley
2584 (save-excursion
2585 (save-window-excursion
2586 (calendar)
2587 (calendar-forward-day (- (time-to-days default-time)
2588 (calendar-absolute-from-gregorian
2589 (calendar-current-date))))
2590 (let* ((old-map (current-local-map))
2591 (map (copy-keymap calendar-mode-map))
2592 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
2593 (define-key map (kbd "RET") 'org-calendar-select)
2594 (define-key map (if org-xemacs-p [button1] [mouse-1])
2595 'org-calendar-select)
2596 (define-key minibuffer-local-map [(meta shift left)]
2597 (lambda () (interactive)
2598 (org-eval-in-calendar '(calendar-backward-month 1))))
2599 (define-key minibuffer-local-map [(meta shift right)]
2600 (lambda () (interactive)
2601 (org-eval-in-calendar '(calendar-forward-month 1))))
2602 (define-key minibuffer-local-map [(shift up)]
2603 (lambda () (interactive)
2604 (org-eval-in-calendar '(calendar-backward-week 1))))
2605 (define-key minibuffer-local-map [(shift down)]
2606 (lambda () (interactive)
2607 (org-eval-in-calendar '(calendar-forward-week 1))))
2608 (define-key minibuffer-local-map [(shift left)]
2609 (lambda () (interactive)
2610 (org-eval-in-calendar '(calendar-backward-day 1))))
2611 (define-key minibuffer-local-map [(shift right)]
2612 (lambda () (interactive)
2613 (org-eval-in-calendar '(calendar-forward-day 1))))
2614 (define-key minibuffer-local-map ">"
2615 (lambda () (interactive)
2616 (org-eval-in-calendar '(scroll-calendar-left 1))))
2617 (define-key minibuffer-local-map "<"
2618 (lambda () (interactive)
2619 (org-eval-in-calendar '(scroll-calendar-right 1))))
2620 (unwind-protect
2621 (progn
2622 (use-local-map map)
2623 (setq ans (read-string prompt "" nil nil))
2624 (setq ans (or ans1 ans2 ans)))
2625 (use-local-map old-map)))))
2626 ;; Naked prompt only
2627 (setq ans (read-string prompt "" nil timestr)))
2628
2629 (if (string-match
2630 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
2631 (progn
2632 (setq year (if (match-end 2)
2633 (string-to-number (match-string 2 ans))
2634 (string-to-number (format-time-string "%Y")))
2635 month (string-to-number (match-string 3 ans))
2636 day (string-to-number (match-string 4 ans)))
2637 (if (< year 100) (setq year (+ 2000 year)))
2638 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
2639 t t ans))))
2640 (setq tl (parse-time-string ans)
2641 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
2642 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
2643 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
2644 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
2645 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
2646 second (or (nth 0 tl) 0))
2647 (if (and (boundp 'org-time-was-given)
2648 (nth 2 tl))
2649 (setq org-time-was-given t))
2650 (if (< year 100) (setq year (+ 2000 year)))
2651 (if to-time
2652 (encode-time second minute hour day month year)
2653 (if (or (nth 1 tl) (nth 2 tl))
2654 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
2655 (format "%04d-%02d-%02d" year month day)))))
2656
2657 (defun org-eval-in-calendar (form)
2658 "Eval FORM in the calendar window and return to current window.
2659 Also, store the cursor date in variable ans2."
2660 (let ((sw (selected-window)))
2661 (select-window (get-buffer-window "*Calendar*"))
2662 (eval form)
2663 (when (calendar-cursor-to-date)
2664 (let* ((date (calendar-cursor-to-date))
2665 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2666 (setq ans2 (format-time-string "%Y-%m-%d" time))))
2667 (select-window sw)))
2668
2669 (defun org-calendar-select ()
2670 "Return to `org-read-date' with the date currently selected.
2671 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
2672 (interactive)
2673 (when (calendar-cursor-to-date)
2674 (let* ((date (calendar-cursor-to-date))
2675 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
2676 (setq ans1 (format-time-string "%Y-%m-%d" time)))
2677 (if (active-minibuffer-window) (exit-minibuffer))))
2678
2679 (defun org-check-deadlines (ndays)
2680 "Check if there are any deadlines due or past due.
2681 A deadline is considered due if it happens within `org-deadline-warning-days'
2682 days from today's date. If the deadline appears in an entry marked DONE,
2683 it is not shown. The prefix arg NDAYS can be used to test that many
2684 days. If the prefix is a raw C-u prefix, all deadlines are shown."
2685 (interactive "P")
2686 (let* ((org-warn-days
2687 (cond
2688 ((equal ndays '(4)) 100000)
2689 (ndays (prefix-numeric-value ndays))
2690 (t org-deadline-warning-days)))
2691 (case-fold-search nil)
2692 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
2693 (callback
2694 (lambda ()
2695 (and (let ((d1 (time-to-days (current-time)))
2696 (d2 (time-to-days
2697 (org-time-string-to-time (match-string 1)))))
2698 (< (- d2 d1) org-warn-days))
2699 (not (org-entry-is-done-p))))))
2700 (message "%d deadlines past-due or due within %d days"
2701 (org-occur regexp callback)
2702 org-warn-days)))
2703
2704 (defun org-evaluate-time-range (&optional to-buffer)
2705 "Evaluate a time range by computing the difference between start and end.
2706 Normally the result is just printed in the echo area, but with prefix arg
2707 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
2708 If the time range is actually in a table, the result is inserted into the
2709 next column.
2710 For time difference computation, a year is assumed to be exactly 365
2711 days in order to avoid rounding problems."
2712 (interactive "P")
2713 (save-excursion
2714 (unless (org-at-date-range-p)
2715 (goto-char (point-at-bol))
2716 (re-search-forward org-tr-regexp (point-at-eol) t))
2717 (if (not (org-at-date-range-p))
2718 (error "Not at a time-stamp range, and none found in current line.")))
2719 (let* ((ts1 (match-string 1))
2720 (ts2 (match-string 2))
2721 (match-end (match-end 0))
2722 (time1 (org-time-string-to-time ts1))
2723 (time2 (org-time-string-to-time ts2))
2724 (t1 (time-to-seconds time1))
2725 (t2 (time-to-seconds time2))
2726 (diff (abs (- t2 t1)))
2727 (negative (< (- t2 t1) 0))
2728 (ys (floor (* 365 24 60 60)))
2729 (ds (* 24 60 60))
2730 (hs (* 60 60))
2731 (fy "%dy %dd %02d:%02d")
2732 (fd "%dd %02d:%02d")
2733 (fh "%02d:%02d")
2734 y d h m align)
2735 (setq y (floor (/ diff ys)) diff (mod diff ys)
2736 d (floor (/ diff ds)) diff (mod diff ds)
2737 h (floor (/ diff hs)) diff (mod diff hs)
2738 m (floor (/ diff 60)))
2739 (if (not to-buffer)
2740 (message (org-make-tdiff-string y d h m))
2741 (when (org-at-table-p)
2742 (goto-char match-end)
2743 (setq align t)
2744 (and (looking-at " *|") (goto-char (match-end 0))))
2745 (if (looking-at
2746 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
2747 (replace-match ""))
2748 (if negative (insert " -"))
2749 (if (> y 0) (insert " " (format fy y d h m))
2750 (if (> d 0) (insert " " (format fd d h m))
2751 (insert " " (format fh h m))))
2752 (if align (org-table-align))
2753 (message "Time difference inserted"))))
2754
2755 (defun org-make-tdiff-string (y d h m)
2756 (let ((fmt "")
2757 (l nil))
2758 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
2759 l (push y l)))
2760 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
2761 l (push d l)))
2762 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
2763 l (push h l)))
2764 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
2765 l (push m l)))
2766 (apply 'format fmt (nreverse l))))
2767
2768 (defun org-time-string-to-time (s)
2769 (apply 'encode-time (org-parse-time-string s)))
2770
2771 (defun org-parse-time-string (s)
2772 "Parse the standard Org-mode time string.
2773 This should be a lot faster than the normal parse-time-string."
2774 (if (string-match org-ts-regexp1 s)
2775 (list 0
2776 (string-to-number (or (match-string 8 s) "0"))
2777 (string-to-number (or (match-string 7 s) "0"))
2778 (string-to-number (match-string 4 s))
2779 (string-to-number (match-string 3 s))
2780 (string-to-number (match-string 2 s))
2781 nil nil nil)
2782 (make-list 9 0)))
2783
2784 (defun org-timestamp-up (&optional arg)
2785 "Increase the date item at the cursor by one.
2786 If the cursor is on the year, change the year. If it is on the month or
2787 the day, change that.
2788 With prefix ARG, change by that many units."
2789 (interactive "p")
2790 (org-timestamp-change (prefix-numeric-value arg)))
2791
2792 (defun org-timestamp-down (&optional arg)
2793 "Decrease the date item at the cursor by one.
2794 If the cursor is on the year, change the year. If it is on the month or
2795 the day, change that.
2796 With prefix ARG, change by that many units."
2797 (interactive "p")
2798 (org-timestamp-change (- (prefix-numeric-value arg))))
2799
2800 (defun org-timestamp-up-day (&optional arg)
2801 "Increase the date in the time stamp by one day.
2802 With prefix ARG, change that many days."
2803 (interactive "p")
2804 (org-timestamp-change (prefix-numeric-value arg) 'day))
2805
2806 (defun org-timestamp-down-day (&optional arg)
2807 "Decrease the date in the time stamp by one day.
2808 With prefix ARG, change that many days."
2809 (interactive "p")
2810 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
2811
2812 (defsubst org-pos-in-match-range (pos n)
2813 (and (match-beginning n)
2814 (<= (match-beginning n) pos)
2815 (>= (match-end n) pos)))
2816
2817 (defun org-at-timestamp-p ()
2818 "Determine if the cursor is or at a timestamp."
2819 (interactive)
2820 (let* ((tsr org-ts-regexp2)
2821 (pos (point))
2822 (ans (or (looking-at tsr)
2823 (save-excursion
2824 (skip-chars-backward "^<\n\r\t")
2825 (if (> (point) 1) (backward-char 1))
2826 (and (looking-at tsr)
2827 (> (- (match-end 0) pos) -1))))))
2828 (and (boundp 'org-ts-what)
2829 (setq org-ts-what
2830 (cond
2831 ((org-pos-in-match-range pos 2) 'year)
2832 ((org-pos-in-match-range pos 3) 'month)
2833 ((org-pos-in-match-range pos 7) 'hour)
2834 ((org-pos-in-match-range pos 8) 'minute)
2835 ((or (org-pos-in-match-range pos 4)
2836 (org-pos-in-match-range pos 5)) 'day)
2837 (t 'day))))
2838 ans))
2839
2840 (defun org-timestamp-change (n &optional what)
2841 "Change the date in the time stamp at point.
2842 The date will be changed by N times WHAT. WHAT can be `day', `month',
2843 `year', `minute', `second'. If WHAT is not given, the cursor position
2844 in the timestamp determines what will be changed."
2845 (let ((fmt (car org-time-stamp-formats))
2846 org-ts-what
2847 (pos (point))
2848 ts time time0)
2849 (if (not (org-at-timestamp-p))
2850 (error "Not at a timestamp"))
2851 (setq org-ts-what (or what org-ts-what))
2852 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
2853 (- (match-end 0) (match-beginning 0))))
2854 1)
2855 (cdr org-time-stamp-formats)
2856 (car org-time-stamp-formats)))
2857 (setq ts (match-string 0))
2858 (replace-match "")
2859 (setq time0 (org-parse-time-string ts))
2860 (setq time
2861 (apply 'encode-time
2862 (append
2863 (list (or (car time0) 0))
2864 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
2865 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
2866 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
2867 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
2868 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
2869 (nthcdr 6 time0))))
2870 (if (eq what 'calendar)
2871 (let ((cal-date
2872 (save-excursion
2873 (save-match-data
2874 (set-buffer "*Calendar*")
2875 (calendar-cursor-to-date)))))
2876 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
2877 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
2878 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
2879 (setcar time0 (or (car time0) 0))
2880 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
2881 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
2882 (setq time (apply 'encode-time time0))))
2883 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
2884 (goto-char pos)
2885 ;; Try to recenter the calendar window, if any
2886 (if (and org-calendar-follow-timestamp-change
2887 (get-buffer-window "*Calendar*" t)
2888 (memq org-ts-what '(day month year)))
2889 (org-recenter-calendar (time-to-days time)))))
2890
2891 (defun org-recenter-calendar (date)
2892 "If the calendar is visible, recenter it to DATE."
2893 (let* ((win (selected-window))
2894 (cwin (get-buffer-window "*Calendar*" t)))
2895 (when cwin
2896 (select-window cwin)
2897 (calendar-goto-date (if (listp date) date
2898 (calendar-gregorian-from-absolute date)))
2899 (select-window win))))
2900
2901 (defun org-goto-calendar (&optional arg)
2902 "Go to the Emacs calendar at the current date.
2903 If there is a time stamp in the current line, go to that date.
2904 A prefix ARG can be used force the current date."
2905 (interactive "P")
2906 (let ((tsr org-ts-regexp) diff)
2907 (if (or (org-at-timestamp-p)
2908 (save-excursion
2909 (beginning-of-line 1)
2910 (looking-at (concat ".*" tsr))))
2911 (let ((d1 (time-to-days (current-time)))
2912 (d2 (time-to-days
2913 (org-time-string-to-time (match-string 1)))))
2914 (setq diff (- d2 d1))))
2915 (calendar)
2916 (calendar-goto-today)
2917 (if (and diff (not arg)) (calendar-forward-day diff))))
2918
2919 (defun org-date-from-calendar ()
2920 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
2921 If there is already a time stamp at the cursor position, update it."
2922 (interactive)
2923 (org-timestamp-change 0 'calendar))
2924
2925 ;;; Agenda, and Diary Integration
2926
2927 ;;; Define the mode
2928
2929 (defvar org-agenda-mode-map (make-sparse-keymap)
2930 "Keymap for org-agenda-mode.")
2931
2932 (defvar org-agenda-menu)
2933 (defvar org-agenda-follow-mode nil)
2934 (defvar org-agenda-buffer-name "*Org Agenda*")
2935 (defvar org-agenda-redo-command nil)
2936
2937 ;;;###autoload
2938 (defun org-agenda-mode ()
2939 "Mode for time-sorted view on action items in Org-mode files.
2940
2941 The following commands are available:
2942
2943 \\{org-agenda-mode-map}"
2944 (interactive)
2945 (kill-all-local-variables)
2946 (setq major-mode 'org-agenda-mode)
2947 (setq mode-name "Org-Agenda")
2948 (use-local-map org-agenda-mode-map)
2949 (easy-menu-add org-agenda-menu)
2950 (if org-startup-truncated (setq truncate-lines t))
2951 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
2952 (setq org-agenda-follow-mode nil)
2953 (easy-menu-change
2954 '("Agenda") "Agenda Files"
2955 (append
2956 (list
2957 ["Edit File List" (customize-variable 'org-agenda-files) t]
2958 "--")
2959 (mapcar 'org-file-menu-entry org-agenda-files)))
2960 (org-agenda-set-mode-name)
2961 (run-hooks 'org-agenda-mode-hook))
2962
2963 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
2964 (define-key org-agenda-mode-map [(return)] 'org-agenda-switch-to)
2965 (define-key org-agenda-mode-map " " 'org-agenda-show)
2966 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
2967 (define-key org-agenda-mode-map "o" 'delete-other-windows)
2968 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
2969 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
2970 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
2971 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
2972 (define-key org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
2973 (define-key org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
2974
2975 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
2976 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2977 (while l (define-key org-agenda-mode-map
2978 (int-to-string (pop l)) 'digit-argument)))
2979
2980 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
2981 (define-key org-agenda-mode-map "d" 'org-agenda-toggle-diary)
2982 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
2983 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
2984 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
2985 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
2986 (define-key org-agenda-mode-map "n" 'next-line)
2987 (define-key org-agenda-mode-map "p" 'previous-line)
2988 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
2989 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
2990 (define-key org-agenda-mode-map "," 'org-agenda-priority)
2991 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
2992 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
2993 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
2994 (eval-after-load "calendar"
2995 '(define-key calendar-mode-map org-calendar-to-agenda-key
2996 'org-calendar-goto-agenda))
2997 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
2998 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
2999 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3000 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3001 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3002 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3003 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3004 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3005 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3006 (define-key org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
3007 (define-key org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
3008 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3009 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3010
3011 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3012 "Local keymap for agenda entries from Org-mode.")
3013
3014 (define-key org-agenda-keymap
3015 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3016 (define-key org-agenda-keymap
3017 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3018
3019 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3020 '("Agenda"
3021 ("Agenda Files")
3022 "--"
3023 ["Show" org-agenda-show t]
3024 ["Go To (other window)" org-agenda-goto t]
3025 ["Go To (one window)" org-agenda-switch-to t]
3026 ["Follow Mode" org-agenda-follow-mode
3027 :style toggle :selected org-agenda-follow-mode :active t]
3028 "--"
3029 ["Cycle TODO" org-agenda-todo t]
3030 ("Reschedule"
3031 ["Reschedule +1 day" org-agenda-date-later t]
3032 ["Reschedule -1 day" org-agenda-date-earlier t]
3033 "--"
3034 ["Reschedule to ..." org-agenda-date-prompt t])
3035 ("Priority"
3036 ["Set Priority" org-agenda-priority t]
3037 ["Increase Priority" org-agenda-priority-up t]
3038 ["Decrease Priority" org-agenda-priority-down t]
3039 ["Show Priority" org-agenda-show-priority t])
3040 "--"
3041 ["Rebuild" org-agenda-redo t]
3042 ["Goto Today" org-agenda-goto-today t]
3043 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3044 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3045 "--"
3046 ["Week/Day View" org-agenda-week-view (local-variable-p 'starting-day)]
3047 ["Include Diary" org-agenda-toggle-diary
3048 :style toggle :selected org-agenda-include-diary :active t]
3049 "--"
3050 ["New Diary Entry" org-agenda-diary-entry t]
3051 ("Calendar Commands"
3052 ["Goto Calendar" org-agenda-goto-calendar t]
3053 ["Phases of the Moon" org-agenda-phases-of-moon t]
3054 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3055 ["Holidays" org-agenda-holidays t]
3056 ["Convert" org-agenda-convert-date t])
3057 "--"
3058 ["Quit" org-agenda-quit t]
3059 ["Exit and Release Buffers" org-agenda-exit t]
3060 ))
3061
3062 (defvar org-agenda-markers nil
3063 "List of all currently active markers created by org-agenda")
3064 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3065 "Creation time of the last agenda marker.")
3066
3067 (defun org-agenda-new-marker (&optional pos)
3068 "Return a new agenda marker.
3069 Org-mode keeps a list of these markers and resets them when they are
3070 no longer in use."
3071 (let ((m (copy-marker (or pos (point)))))
3072 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3073 (push m org-agenda-markers)
3074 m))
3075
3076 (defun org-agenda-maybe-reset-markers (&optional force)
3077 "Reset markers created by org-agenda. But only if they are old enough."
3078 (if (or force
3079 (> (- (time-to-seconds (current-time))
3080 org-agenda-last-marker-time)
3081 5))
3082 (while org-agenda-markers
3083 (move-marker (pop org-agenda-markers) nil))))
3084
3085 (defvar org-agenda-new-buffers nil
3086 "Buffers created to visit agenda files.")
3087
3088 (defun org-get-agenda-file-buffer (file)
3089 "Get a buffer visiting FILE. If the buffer needs to be created, add
3090 it to the list of buffers which might be released later."
3091 (let ((buf (find-buffer-visiting file)))
3092 (if buf
3093 buf ; just return it
3094 ;; Make a new buffer and remember it
3095 (setq buf (find-file-noselect file))
3096 (if buf (push buf org-agenda-new-buffers))
3097 buf)))
3098
3099 (defun org-release-buffers (blist)
3100 "Release all buffers in list, asking the user for confirmation when needed.
3101 When a buffer is unmodified, it is just killed. When modified, it is saved
3102 \(if the user agrees) and then killed."
3103 (let (buf file)
3104 (while (setq buf (pop blist))
3105 (setq file (buffer-file-name buf))
3106 (when (and (buffer-modified-p buf)
3107 file
3108 (y-or-n-p (format "Save file %s? " file)))
3109 (save-excursion
3110 (set-buffer buf) (save-buffer)))
3111 (kill-buffer buf))))
3112
3113 (defun org-timeline (&optional include-all)
3114 "Show a time-sorted view of the entries in the current org file.
3115 Only entries with a time stamp of today or later will be listed. With
3116 one C-u prefix argument, past entries will also be listed.
3117 With two C-u prefixes, all unfinished TODO items will also be shown,
3118 under the current date.
3119 If the buffer contains an active region, only check the region for
3120 dates."
3121 (interactive "P")
3122 (require 'calendar)
3123 (org-agenda-maybe-reset-markers 'force)
3124 (let* ((dopast include-all)
3125 (dotodo (equal include-all '(16)))
3126 (entry (buffer-file-name))
3127 (org-agenda-files (list (buffer-file-name)))
3128 (date (calendar-current-date))
3129 (win (selected-window))
3130 (pos1 (point))
3131 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3132 (end (if (org-region-active-p) (region-end) (point-max)))
3133 (day-numbers (org-get-all-dates beg end 'no-ranges
3134 t)) ; always include today
3135 (today (time-to-days (current-time)))
3136 (org-respect-restriction t)
3137 (past t)
3138 s e rtn d pos)
3139 (setq org-agenda-redo-command
3140 (list 'progn
3141 (list 'switch-to-buffer-other-window (current-buffer))
3142 (list 'org-timeline include-all)))
3143 (if (not dopast)
3144 ;; Remove past dates from the list of dates.
3145 (setq day-numbers (delq nil (mapcar (lambda(x)
3146 (if (>= x today) x nil))
3147 day-numbers))))
3148 (switch-to-buffer-other-window
3149 (get-buffer-create org-agenda-buffer-name))
3150 (setq buffer-read-only nil)
3151 (erase-buffer)
3152 (org-agenda-mode) (setq buffer-read-only nil)
3153 (while (setq d (pop day-numbers))
3154 (if (and (>= d today)
3155 dopast
3156 past)
3157 (progn
3158 (setq past nil)
3159 (insert (make-string 79 ?-) "\n")))
3160 (setq date (calendar-gregorian-from-absolute d))
3161 (setq s (point))
3162 (if dotodo
3163 (setq rtn (org-agenda-get-day-entries
3164 entry date :todo :timestamp))
3165 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3166 (if (or rtn (equal d today))
3167 (progn
3168 (insert (calendar-day-name date) " "
3169 (number-to-string (extract-calendar-day date)) " "
3170 (calendar-month-name (extract-calendar-month date)) " "
3171 (number-to-string (extract-calendar-year date)) "\n")
3172 (put-text-property s (1- (point)) 'face
3173 'org-link-face)
3174 (if (equal d today)
3175 (put-text-property s (1- (point)) 'org-today t))
3176 (insert (org-finalize-agenda-entries rtn) "\n")
3177 (put-text-property s (1- (point)) 'day d))))
3178 (goto-char (point-min))
3179 (setq buffer-read-only t)
3180 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3181 (point-min)))
3182 (when (not org-select-timeline-window)
3183 (select-window win)
3184 (goto-char pos1))))
3185
3186 ;;;###autoload
3187 (defun org-agenda (&optional include-all start-day ndays)
3188 "Produce a weekly view from all files in variable `org-agenda-files'.
3189 The view will be for the current week, but from the overview buffer you
3190 will be able to go to other weeks.
3191 With one C-u prefix argument INCLUDE-ALL, all unfinished TODO items will
3192 also be shown, under the current date.
3193 START-DAY defaults to TODAY, or to the most recent match for the weekday
3194 given in `org-agenda-start-on-weekday'.
3195 NDAYS defaults to `org-agenda-ndays'."
3196 (interactive "P")
3197 (org-agenda-maybe-reset-markers 'force)
3198 (require 'calendar)
3199 (let* ((org-agenda-start-on-weekday
3200 (if (or (equal ndays 1)
3201 (and (null ndays) (equal 1 org-agenda-ndays)))
3202 nil org-agenda-start-on-weekday))
3203 (files (copy-sequence org-agenda-files))
3204 (win (selected-window))
3205 (today (time-to-days (current-time)))
3206 (sd (or start-day today))
3207 (start (if (or (null org-agenda-start-on-weekday)
3208 (< org-agenda-ndays 7))
3209 sd
3210 (let* ((nt (calendar-day-of-week
3211 (calendar-gregorian-from-absolute sd)))
3212 (n1 org-agenda-start-on-weekday)
3213 (d (- nt n1)))
3214 (- sd (+ (if (< d 0) 7 0) d)))))
3215 (day-numbers (list start))
3216 s e rtn rtnall file date d start-pos end-pos)
3217 (setq org-agenda-redo-command
3218 (list 'org-agenda include-all start-day ndays))
3219 ;; Make the list of days
3220 (setq ndays (or ndays org-agenda-ndays))
3221 (while (> ndays 1)
3222 (push (1+ (car day-numbers)) day-numbers)
3223 (setq ndays (1- ndays)))
3224 (setq day-numbers (nreverse day-numbers))
3225 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3226 (progn
3227 (delete-other-windows)
3228 (switch-to-buffer-other-window
3229 (get-buffer-create org-agenda-buffer-name))))
3230 (setq buffer-read-only nil)
3231 (erase-buffer)
3232 (org-agenda-mode) (setq buffer-read-only nil)
3233 (set (make-local-variable 'starting-day) (car day-numbers))
3234 (set (make-local-variable 'include-all-loc) include-all)
3235 (when (and (or include-all org-agenda-include-all-todo)
3236 (member today day-numbers))
3237 (setq files org-agenda-files
3238 rtnall nil)
3239 (while (setq file (pop files))
3240 (catch 'nextfile
3241 (org-check-agenda-file file)
3242 (setq date (calendar-gregorian-from-absolute today)
3243 rtn (org-agenda-get-day-entries
3244 file date :todo))
3245 (setq rtnall (append rtnall rtn))))
3246 (if rtnall (insert (org-finalize-agenda-entries rtnall) "\n")))
3247 (while (setq d (pop day-numbers))
3248 (setq date (calendar-gregorian-from-absolute d)
3249 s (point))
3250 (if (or (= d today)
3251 (and (not start-pos) (= d sd)))
3252 (setq start-pos (point))
3253 (if (and start-pos (not end-pos))
3254 (setq end-pos (point))))
3255 (setq files org-agenda-files
3256 rtnall nil)
3257 (while (setq file (pop files))
3258 (catch 'nextfile
3259 (org-check-agenda-file file)
3260 (setq rtn (org-agenda-get-day-entries file date))
3261 (setq rtnall (append rtnall rtn))))
3262 (if org-agenda-include-diary
3263 (progn
3264 (require 'diary-lib)
3265 (setq rtn (org-get-entries-from-diary date))
3266 (setq rtnall (append rtnall rtn))))
3267 (if (or rtnall org-agenda-show-all-dates)
3268 (progn
3269 (insert (format "%-9s %2d %-9s %4d\n"
3270 (calendar-day-name date)
3271 (extract-calendar-day date)
3272 (calendar-month-name (extract-calendar-month date))
3273 (extract-calendar-year date)))
3274 (put-text-property s (1- (point)) 'face
3275 'org-link-face)
3276 (if rtnall (insert (org-finalize-agenda-entries rtnall) "\n"))
3277 (put-text-property s (1- (point)) 'day d))))
3278 (goto-char (point-min))
3279 (setq buffer-read-only t)
3280 (if org-fit-agenda-window
3281 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3282 (/ (frame-height) 2)))
3283 (unless (and (pos-visible-in-window-p (point-min))
3284 (pos-visible-in-window-p (point-max)))
3285 (goto-char (1- (point-max)))
3286 (recenter -1)
3287 (if (not (pos-visible-in-window-p (or start-pos 1)))
3288 (progn
3289 (goto-char (or start-pos 1))
3290 (recenter 1))))
3291 (goto-char (or start-pos 1))
3292 (if (not org-select-agenda-window) (select-window win))
3293 (message "")))
3294
3295 (defun org-check-agenda-file (file)
3296 "Make sure FILE exists. If not, ask user what to do."
3297 ;; FIXME: this does not correctly change the menus
3298 ;; Could probably be fixed by explicitly going to the buffer.
3299 (when (not (file-exists-p file))
3300 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3301 file)
3302 (let ((r (downcase (read-char-exclusive))))
3303 (cond
3304 ((equal r ?r)
3305 (org-remove-file file)
3306 (throw 'nextfile t))
3307 (t (error "Abort"))))))
3308
3309 (defun org-agenda-quit (arg)
3310 "Exit agenda by removing the window or the buffer."
3311 (interactive "P")
3312 (let ((buf (current-buffer)))
3313 (if (not (one-window-p)) (delete-window))
3314 (kill-buffer buf)
3315 (org-agenda-maybe-reset-markers 'force)))
3316
3317 (defun org-agenda-exit (arg)
3318 "Exit agenda by removing the window or the buffer.
3319 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3320 Org-mode buffers visited directly by the user will not be touched."
3321 (interactive "P")
3322 (org-release-buffers org-agenda-new-buffers)
3323 (setq org-agenda-new-buffers nil)
3324 (org-agenda-quit arg))
3325
3326 (defun org-agenda-redo (&optional arg)
3327 "Rebuild Agenda"
3328 (interactive "P")
3329 (eval org-agenda-redo-command))
3330
3331 (defun org-agenda-goto-today (arg)
3332 "Go to today."
3333 (interactive "P")
3334 (if (boundp 'starting-day)
3335 (let ((cmd (car org-agenda-redo-command))
3336 (iall (nth 1 org-agenda-redo-command))
3337 (nday (nth 3 org-agenda-redo-command)))
3338 (eval (list cmd iall nil nday)))
3339 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3340 (point-min)))))
3341
3342 (defun org-agenda-later (arg)
3343 "Go forward in time by `org-agenda-ndays' days.
3344 With prefix ARG, go forward that many times `org-agenda-ndays'."
3345 (interactive "p")
3346 (unless (boundp 'starting-day)
3347 (error "Not allowed"))
3348 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3349 (+ starting-day (* arg org-agenda-ndays))))
3350
3351 (defun org-agenda-earlier (arg)
3352 "Go back in time by `org-agenda-ndays' days.
3353 With prefix ARG, go back that many times `org-agenda-ndays'."
3354 (interactive "p")
3355 (unless (boundp 'starting-day)
3356 (error "Not allowed"))
3357 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3358 (- starting-day (* arg org-agenda-ndays))))
3359
3360 (defun org-agenda-day-view (arg)
3361 "Switch agenda to single day view."
3362 (interactive "P")
3363 (unless (boundp 'starting-day)
3364 (error "Not allowed"))
3365 (setq org-agenda-ndays 1)
3366 (org-agenda include-all-loc starting-day 1))
3367
3368 (defun org-agenda-week-view (arg)
3369 "Switch agenda to week view."
3370 (interactive "P")
3371 (unless (boundp 'starting-day)
3372 (error "Not allowed"))
3373 (setq org-agenda-ndays
3374 (if (equal org-agenda-ndays 1) 7 1))
3375 (org-agenda include-all-loc
3376 (or (get-text-property (point) 'day)
3377 starting-day))
3378 (org-agenda-set-mode-name)
3379 (message "Switched to %s view"
3380 (if (equal org-agenda-ndays 1) "day" "week")))
3381
3382 (defun org-agenda-next-date-line (&optional arg)
3383 "Jump to the next line indicating a date in agenda buffer."
3384 (interactive "p")
3385 (beginning-of-line 1)
3386 (if (looking-at "^\\S-") (forward-char 1))
3387 (if (not (re-search-forward "^\\S-" nil t arg))
3388 (progn
3389 (backward-char 1)
3390 (error "No next date after this line in this buffer.")))
3391 (goto-char (match-beginning 0)))
3392
3393 (defun org-agenda-previous-date-line (&optional arg)
3394 "Jump to the next line indicating a date in agenda buffer."
3395 (interactive "p")
3396 (beginning-of-line 1)
3397 (if (not (re-search-backward "^\\S-" nil t arg))
3398 (error "No previous date before this line in this buffer.")))
3399
3400 (defun org-agenda-follow-mode ()
3401 "Toggle follow mode in an agenda buffer."
3402 (interactive)
3403 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3404 (org-agenda-set-mode-name)
3405 (message "Follow mode is %s"
3406 (if org-agenda-follow-mode "on" "off")))
3407
3408 (defun org-agenda-toggle-diary ()
3409 "Toggle follow mode in an agenda buffer."
3410 (interactive)
3411 (setq org-agenda-include-diary (not org-agenda-include-diary))
3412 (org-agenda-redo)
3413 (org-agenda-set-mode-name)
3414 (message "Diary inclusion turned %s"
3415 (if org-agenda-include-diary "on" "off")))
3416
3417 (defun org-agenda-set-mode-name ()
3418 "Set the mode name to indicate all the small mode settings."
3419 (setq mode-name
3420 (concat "Org-Agenda"
3421 (if (equal org-agenda-ndays 1) " Day" "")
3422 (if (equal org-agenda-ndays 7) " Week" "")
3423 (if org-agenda-follow-mode " Follow" "")
3424 (if org-agenda-include-diary " Diary" "")))
3425 (force-mode-line-update))
3426
3427 (defun org-agenda-post-command-hook ()
3428 (and (eolp) (not (bolp)) (backward-char 1))
3429 (if (and org-agenda-follow-mode
3430 (get-text-property (point) 'org-marker))
3431 (org-agenda-show)))
3432
3433 (defun org-get-entries-from-diary (date)
3434 "Get the (emacs calendar) diary entries for DATE."
3435 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
3436 (diary-display-hook '(fancy-diary-display))
3437 (list-diary-entries-hook
3438 (cons 'org-diary-default-entry list-diary-entries-hook))
3439 entries
3440 (disable-org-diary t))
3441 (save-excursion
3442 (save-window-excursion
3443 (list-diary-entries date 1)))
3444 (if (not (get-buffer fancy-diary-buffer))
3445 (setq entries nil)
3446 (save-excursion
3447 (switch-to-buffer fancy-diary-buffer)
3448 (setq buffer-read-only nil)
3449 (if (= (point-max) 1)
3450 ;; No entries
3451 (setq entries nil)
3452 ;; Omit the date and other unnecessary stuff
3453 (org-agenda-cleanup-fancy-diary)
3454 ;; Add prefix to each line and extend the text properties
3455 (goto-char (point-min))
3456 (while (and (re-search-forward "^" nil t) (not (eobp)))
3457 (replace-match " Diary: ")
3458 (add-text-properties (point-at-bol) (point)
3459 (text-properties-at (point))))
3460 (if (= (point-max) 1)
3461 (setq entries nil)
3462 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
3463 (set-buffer-modified-p nil)
3464 (kill-buffer fancy-diary-buffer)))
3465 (when entries
3466 (setq entries (org-split-string entries "\n"))
3467 (setq entries
3468 (mapcar
3469 (lambda (x)
3470 (if (string-match "\\<\\([012][0-9]\\):\\([0-6][0-9]\\)" x)
3471 (add-text-properties
3472 1 (length x)
3473 (list 'time-of-day
3474 (+ (* 100 (string-to-number
3475 (match-string 1 x)))
3476 (string-to-number (match-string 2 x))))
3477 x))
3478 x)
3479 entries)))))
3480
3481 (defun org-agenda-cleanup-fancy-diary ()
3482 "Remove unwanted stuff in buffer created by fancy-diary-display.
3483 This gets rid of the date, the underline under the date, and
3484 the dummy entry installed by org-mode to ensure non-empty diary for each
3485 date."
3486 (goto-char (point-min))
3487 (if (looking-at ".*?:[ \t]*")
3488 (progn
3489 (replace-match "")
3490 (re-search-forward "\n=+$" nil t)
3491 (replace-match "")
3492 (while (re-search-backward "^ +" nil t) (replace-match "")))
3493 (re-search-forward "\n=+$" nil t)
3494 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
3495 (if (re-search-forward "^Org-mode dummy\n?" nil t)
3496 (replace-match "")))
3497
3498 ;; Advise the add-to-diary-list function to allow org to jump to
3499 ;; diary entries. Wrapped into eval-after-load to avoid loading
3500 ;; advice unnecessarily
3501 (eval-after-load "diary-lib"
3502 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
3503 "Make the position visible."
3504 (if (and (boundp 'disable-org-diary) ;; called from org-agenda
3505 (stringp string)
3506 (buffer-file-name))
3507 (add-text-properties
3508 0 (length string)
3509 (list 'mouse-face 'highlight
3510 'keymap org-agenda-keymap
3511 'help-echo
3512 (format
3513 "mouse-2 or RET jump to diary file %s"
3514 (abbreviate-file-name (buffer-file-name)))
3515 'org-agenda-diary-link t
3516 'org-marker (org-agenda-new-marker (point-at-bol)))
3517 string))))
3518
3519 (defun org-diary-default-entry ()
3520 "Add a dummy entry to the diary.
3521 Needed to avoid empty dates which mess up holiday display."
3522 ;; Catch the error if dealing with the new add-to-diary-alist
3523 (condition-case nil
3524 (add-to-diary-list original-date "Org-mode dummy" "")
3525 (error
3526 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
3527
3528 (defun org-add-file (&optional file)
3529 "Add current file to the list of files in variable `org-agenda-files'.
3530 These are the files which are being checked for agenda entries.
3531 Optional argument FILE means, use this file instead of the current.
3532 It is possible (but not recommended) to add this function to the
3533 `org-mode-hook'."
3534 (interactive)
3535 (catch 'exit
3536 (let* ((file (or file (buffer-file-name)
3537 (if (interactive-p)
3538 (error "Buffer is not visiting a file")
3539 (throw 'exit nil))))
3540 (true-file (file-truename file))
3541 (afile (abbreviate-file-name file))
3542 (present (delq nil (mapcar
3543 (lambda (x)
3544 (equal true-file (file-truename x)))
3545 org-agenda-files))))
3546 (if (not present)
3547 (progn
3548 (setq org-agenda-files
3549 (cons afile org-agenda-files))
3550 ;; Make sure custom.el does not end up with Org-mode
3551 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
3552 (customize-save-variable 'org-agenda-files org-agenda-files))
3553 (org-install-agenda-files-menu)
3554 (message "Added file: %s" afile))
3555 (message "File was already in list: %s" afile)))))
3556
3557 (defun org-remove-file (&optional file)
3558 "Remove current file from the list of files in variable `org-agenda-files'.
3559 These are the files which are being checked for agenda entries.
3560 Optional argument FILE means, use this file instead of the current."
3561 (interactive)
3562 (let* ((file (or file (buffer-file-name)))
3563 (true-file (file-truename file))
3564 (afile (abbreviate-file-name file))
3565 (files (delq nil (mapcar
3566 (lambda (x)
3567 (if (equal true-file
3568 (file-truename x))
3569 nil x))
3570 org-agenda-files))))
3571 (if (not (= (length files) (length org-agenda-files)))
3572 (progn
3573 (setq org-agenda-files files)
3574 (customize-save-variable 'org-agenda-files org-agenda-files)
3575 (org-install-agenda-files-menu)
3576 (message "Removed file: %s" afile))
3577 (message "File was not in list: %s" afile))))
3578
3579 (defun org-file-menu-entry (file)
3580 (vector file (list 'find-file file) t))
3581
3582 (defun org-get-all-dates (beg end &optional no-ranges force-today)
3583 "Return a list of all relevant day numbers from BEG to END buffer positions.
3584 If NO-RANGES is non-nil, include only the start and end dates of a range,
3585 not every single day in the range. If FORCE-TODAY is non-nil, make
3586 sure that TODAY is included in the list."
3587 (let (dates date day day1 day2 ts1 ts2)
3588 (if force-today
3589 (setq dates (list (time-to-days (current-time)))))
3590 (save-excursion
3591 (goto-char beg)
3592 (while (re-search-forward org-ts-regexp end t)
3593 (setq day (time-to-days (org-time-string-to-time
3594 (substring (match-string 1) 0 10))))
3595 (or (memq day dates) (push day dates)))
3596 (unless no-ranges
3597 (goto-char beg)
3598 (while (re-search-forward org-tr-regexp end t)
3599 (setq ts1 (substring (match-string 1) 0 10)
3600 ts2 (substring (match-string 2) 0 10)
3601 day1 (time-to-days (org-time-string-to-time ts1))
3602 day2 (time-to-days (org-time-string-to-time ts2)))
3603 (while (< (setq day1 (1+ day1)) day2)
3604 (or (memq day1 dates) (push day1 dates)))))
3605 (sort dates '<))))
3606
3607 ;;;###autoload
3608 (defun org-diary (&rest args)
3609 "Returns diary information from org-files.
3610 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
3611 It accesses org files and extracts information from those files to be
3612 listed in the diary. The function accepts arguments specifying what
3613 items should be listed. The following arguments are allowed:
3614
3615 :timestamp List the headlines of items containing a date stamp or
3616 date range matching the selected date. Deadlines will
3617 also be listed, on the expiration day.
3618
3619 :deadline List any deadlines past due, or due within
3620 `org-deadline-warning-days'. The listing occurs only
3621 in the diary for *today*, not at any other date. If
3622 an entry is marked DONE, it is no longer listed.
3623
3624 :scheduled List all items which are scheduled for the given date.
3625 The diary for *today* also contains items which were
3626 scheduled earlier and are not yet marked DONE.
3627
3628 :todo List all TODO items from the org-file. This may be a
3629 long list - so this is not turned on by default.
3630 Like deadlines, these entries only show up in the
3631 diary for *today*, not at any other date.
3632
3633 The call in the diary file should look like this:
3634
3635 &%%(org-diary) ~/path/to/some/orgfile.org
3636
3637 Use a separate line for each org file to check. Or, if you omit the file name,
3638 all files listed in `org-agenda-files' will be checked automatically:
3639
3640 &%%(org-diary)
3641
3642 If you don't give any arguments (as in the example above), the default
3643 arguments (:deadline :scheduled :timestamp) are used. So the example above may
3644 also be written as
3645
3646 &%%(org-diary :deadline :timestamp :scheduled)
3647
3648 The function expects the lisp variables `entry' and `date' to be provided
3649 by the caller, because this is how the calendar works. Don't use this
3650 function from a program - use `org-agenda-get-day-entries' instead."
3651 (org-agenda-maybe-reset-markers)
3652 (setq args (or args '(:deadline :scheduled :timestamp)))
3653 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
3654 (list entry)
3655 org-agenda-files))
3656 file rtn results)
3657 ;; If this is called during org-agenda, don't return any entries to
3658 ;; the calendar. Org Agenda will list these entries itself.
3659 (if (boundp 'disable-org-diary) (setq files nil))
3660 (while (setq file (pop files))
3661 (setq rtn (apply 'org-agenda-get-day-entries file date args))
3662 (setq results (append results rtn)))
3663 (concat (org-finalize-agenda-entries results) "\n")))
3664
3665 (defun org-agenda-get-day-entries (file date &rest args)
3666 "Does the work for `org-diary' and `org-agenda'
3667 FILE is the path to a file to be checked for entries. DATE is date like
3668 the one returned by `calendar-current-date'. ARGS are symbols indicating
3669 which kind of entries should be extracted. For details about these, see
3670 the documentation of `org-diary'."
3671 (setq args (or args '(:deadline :scheduled :timestamp)))
3672 (let* ((org-startup-with-deadline-check nil)
3673 (org-startup-folded nil)
3674 (buffer (if (file-exists-p file)
3675 ; (find-file-noselect file)
3676 (org-get-agenda-file-buffer file)
3677 (error "No such file %s" file)))
3678 (respect-narrow-p (boundp 'org-respect-restriction))
3679 arg results rtn)
3680 (if (not buffer)
3681 ;; If file does not exist, make sure an error message ends up in diary
3682 (format "ORG-AGENDA-ERROR: No such org-file %s" file)
3683 (save-excursion
3684 (set-buffer buffer)
3685 (let ((case-fold-search nil))
3686 (save-excursion
3687 (save-restriction
3688 (if respect-narrow-p
3689 (if (org-region-active-p)
3690 ;; Respect a region to restrict search
3691 (narrow-to-region (region-beginning) (region-end)))
3692 ;; If we work for the calendar or many files,
3693 ;; get rid of any restriction
3694 (widen))
3695 (while (setq arg (pop args))
3696 (cond
3697 ((and (eq arg :todo)
3698 (equal date (calendar-current-date)))
3699 (setq rtn (org-agenda-get-todos))
3700 (setq results (append results rtn)))
3701 ((eq arg :timestamp)
3702 (setq rtn (org-agenda-get-blocks))
3703 (setq results (append results rtn))
3704 (setq rtn (org-agenda-get-timestamps))
3705 (setq results (append results rtn)))
3706 ((eq arg :scheduled)
3707 (setq rtn (org-agenda-get-scheduled))
3708 (setq results (append results rtn)))
3709 ((and (eq arg :deadline)
3710 (equal date (calendar-current-date)))
3711 (setq rtn (org-agenda-get-deadlines))
3712 (setq results (append results rtn))))))))))
3713 results))
3714
3715 (defun org-entry-is-done-p ()
3716 "Is the current entry marked DONE?"
3717 (save-excursion
3718 (and (re-search-backward "[\r\n]\\*" nil t)
3719 (looking-at org-nl-done-regexp))))
3720
3721 (defun org-at-date-range-p ()
3722 "Is the cursor inside a date range?"
3723 (interactive)
3724 (save-excursion
3725 (catch 'exit
3726 (let ((pos (point)))
3727 (skip-chars-backward "^<\r\n")
3728 (skip-chars-backward "<")
3729 (and (looking-at org-tr-regexp)
3730 (>= (match-end 0) pos)
3731 (throw 'exit t))
3732 (skip-chars-backward "^<\r\n")
3733 (skip-chars-backward "<")
3734 (and (looking-at org-tr-regexp)
3735 (>= (match-end 0) pos)
3736 (throw 'exit t)))
3737 nil)))
3738
3739 (defun org-agenda-get-todos ()
3740 "Return the TODO information for agenda display."
3741 (let* ((props (list 'face nil
3742 'done-face 'org-done-face
3743 'mouse-face 'highlight
3744 'keymap org-agenda-keymap
3745 'help-echo
3746 (format "mouse-2 or RET jump to org file %s"
3747 (abbreviate-file-name (buffer-file-name)))))
3748 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
3749 "[^\n\r]*\\)"))
3750 marker priority
3751 ee txt pl)
3752 (goto-char (point-min))
3753 (while (re-search-forward regexp nil t)
3754 (goto-char (match-beginning 1))
3755 (setq marker (org-agenda-new-marker (point-at-bol))
3756 txt (org-format-agenda-item "" (match-string 1))
3757 priority
3758 (+ (org-get-priority txt)
3759 (if org-todo-kwd-priority-p
3760 (- org-todo-kwd-max-priority -2
3761 (length
3762 (member (match-string 2) org-todo-keywords)))
3763 1)))
3764 (add-text-properties
3765 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
3766 'priority priority)
3767 props)
3768 txt)
3769 (push txt ee)
3770 (goto-char (match-end 1)))
3771 (nreverse ee)))
3772
3773 (defconst org-agenda-no-heading-message
3774 "No heading for this item in buffer or region")
3775
3776 (defun org-agenda-get-timestamps ()
3777 "Return the date stamp information for agenda display."
3778 (let* ((props (list 'face nil
3779 'mouse-face 'highlight
3780 'keymap org-agenda-keymap
3781 'help-echo
3782 (format "mouse-2 or RET jump to org file %s"
3783 (abbreviate-file-name (buffer-file-name)))))
3784 (regexp (regexp-quote
3785 (substring
3786 (format-time-string
3787 (car org-time-stamp-formats)
3788 (apply 'encode-time ; DATE bound by calendar
3789 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
3790 0 11)))
3791 marker hdmarker deadlinep scheduledp donep tmp priority
3792 ee txt)
3793 (goto-char (point-min))
3794 (while (re-search-forward regexp nil t)
3795 (if (not (save-match-data (org-at-date-range-p)))
3796 (progn
3797 (setq marker (org-agenda-new-marker (match-beginning 0))
3798 tmp (buffer-substring (max (point-min)
3799 (- (match-beginning 0)
3800 org-ds-keyword-length))
3801 (match-beginning 0))
3802 deadlinep (string-match org-deadline-regexp tmp)
3803 scheduledp (string-match org-scheduled-regexp tmp)
3804 donep (org-entry-is-done-p))
3805 (save-excursion
3806 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
3807 (progn
3808 (goto-char (match-end 1))
3809 (setq hdmarker (org-agenda-new-marker))
3810 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
3811 (setq txt (org-format-agenda-item
3812 (format "%s%s"
3813 (if deadlinep "Deadline: " "")
3814 (if scheduledp "Scheduled: " ""))
3815 (match-string 1))))
3816 (setq txt org-agenda-no-heading-message))
3817 (setq priority (org-get-priority txt))
3818 (add-text-properties
3819 0 (length txt) (append (list 'org-marker marker
3820 'org-hd-marker hdmarker) props)
3821 txt)
3822 (if deadlinep
3823 (add-text-properties
3824 0 (length txt)
3825 (list 'face
3826 (if donep 'org-done-face 'org-warning-face)
3827 'undone-face 'org-warning-face
3828 'done-face 'org-done-face
3829 'priority (+ 100 priority))
3830 txt)
3831 (if scheduledp
3832 (add-text-properties
3833 0 (length txt)
3834 (list 'face 'org-scheduled-today-face
3835 'undone-face 'org-scheduled-today-face
3836 'done-face 'org-done-face
3837 priority (+ 99 priority))
3838 txt)
3839 (add-text-properties
3840 0 (length txt)
3841 (list 'priority priority) txt)))
3842 (push txt ee))
3843 (outline-next-heading))))
3844 (nreverse ee)))
3845
3846 (defun org-agenda-get-deadlines ()
3847 "Return the deadline information for agenda display."
3848 (let* ((wdays org-deadline-warning-days)
3849 (props (list 'mouse-face 'highlight
3850 'keymap org-agenda-keymap
3851 'help-echo
3852 (format "mouse-2 or RET jump to org file %s"
3853 (abbreviate-file-name (buffer-file-name)))))
3854 (regexp org-deadline-time-regexp)
3855 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
3856 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
3857 d2 diff pos pos1
3858 ee txt head hdmarker)
3859 (goto-char (point-min))
3860 (while (re-search-forward regexp nil t)
3861 (setq pos (1- (match-beginning 1))
3862 d2 (time-to-days
3863 (org-time-string-to-time (match-string 1)))
3864 diff (- d2 d1))
3865 ;; When to show a deadline in the calendar:
3866 ;; If the expiration is within wdays warning time.
3867 ;; Past-due deadlines are only shown on the current date
3868 (if (and (< diff wdays) todayp (not (= diff 0)))
3869 (save-excursion
3870 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
3871 (progn
3872 (goto-char (match-end 0))
3873 (setq pos1 (match-end 1))
3874 (setq head (buffer-substring-no-properties
3875 (point)
3876 (progn (skip-chars-forward "^\r\n")
3877 (point))))
3878 (if (string-match org-looking-at-done-regexp head)
3879 (setq txt nil)
3880 (setq txt (org-format-agenda-item
3881 (format "In %3d d.: " diff) head))))
3882 (setq txt org-agenda-no-heading-message))
3883 (when txt
3884 (add-text-properties
3885 0 (length txt)
3886 (append
3887 (list 'org-marker (org-agenda-new-marker pos)
3888 'org-hd-marker (org-agenda-new-marker pos1)
3889 'priority (+ (- 10 diff) (org-get-priority txt))
3890 'face (cond ((<= diff 0) 'org-warning-face)
3891 ((<= diff 5) 'org-scheduled-previously-face)
3892 (t nil))
3893 'undone-face (cond
3894 ((<= diff 0) 'org-warning-face)
3895 ((<= diff 5) 'org-scheduled-previously-face)
3896 (t nil))
3897 'done-face 'org-done-face)
3898 props)
3899 txt)
3900 (push txt ee)))))
3901 ee))
3902
3903 (defun org-agenda-get-scheduled ()
3904 "Return the scheduled information for agenda display."
3905 (let* ((props (list 'face 'org-scheduled-previously-face
3906 'undone-face 'org-scheduled-previously-face
3907 'done-face 'org-done-face
3908 'mouse-face 'highlight
3909 'keymap org-agenda-keymap
3910 'help-echo
3911 (format "mouse-2 or RET jump to org file %s"
3912 (abbreviate-file-name (buffer-file-name)))))
3913 (regexp org-scheduled-time-regexp)
3914 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
3915 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
3916 d2 diff marker hdmarker pos pos1
3917 ee txt head)
3918 (goto-char (point-min))
3919 (while (re-search-forward regexp nil t)
3920 (setq pos (1- (match-beginning 1))
3921 d2 (time-to-days
3922 (org-time-string-to-time (match-string 1)))
3923 diff (- d2 d1))
3924 ;; When to show a scheduled item in the calendar:
3925 ;; If it is on or past the date.
3926 (if (and (< diff 0) todayp)
3927 (save-excursion
3928 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
3929 (progn
3930 (goto-char (match-end 0))
3931 (setq pos1 (match-end 1))
3932 (setq head (buffer-substring-no-properties
3933 (point)
3934 (progn (skip-chars-forward "^\r\n") (point))))
3935 (if (string-match org-looking-at-done-regexp head)
3936 (setq txt nil)
3937 (setq txt (org-format-agenda-item
3938 (format "Sched.%2dx: " (- 1 diff)) head))))
3939 (setq txt org-agenda-no-heading-message))
3940 (when txt
3941 (add-text-properties
3942 0 (length txt)
3943 (append (list 'org-marker (org-agenda-new-marker pos)
3944 'org-hd-marker (org-agenda-new-marker pos1)
3945 'priority (+ (- 5 diff) (org-get-priority txt)))
3946 props) txt)
3947 (push txt ee)))))
3948 ee))
3949
3950 (defun org-agenda-get-blocks ()
3951 "Return the date-range information for agenda display."
3952 (let* ((props (list 'face nil
3953 'mouse-face 'highlight
3954 'keymap org-agenda-keymap
3955 'help-echo
3956 (format "mouse-2 or RET jump to org file %s"
3957 (abbreviate-file-name (buffer-file-name)))))
3958 (regexp org-tr-regexp)
3959 (d0 (calendar-absolute-from-gregorian date))
3960 marker hdmarker ee txt d1 d2 s1 s2)
3961 (goto-char (point-min))
3962 (while (re-search-forward regexp nil t)
3963 (setq s1 (match-string 1)
3964 s2 (match-string 2)
3965 d1 (time-to-days (org-time-string-to-time s1))
3966 d2 (time-to-days (org-time-string-to-time s2)))
3967 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
3968 ;; Only allow days between the limits, because the normal
3969 ;; date stamps will catch the limits.
3970 (save-excursion
3971 (setq marker (org-agenda-new-marker (point)))
3972 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
3973 (progn
3974 (setq hdmarker (org-agenda-new-marker (match-end 1)))
3975 (goto-char (match-end 1))
3976 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
3977 (setq txt (org-format-agenda-item
3978 (format "(%d/%d): "
3979 (1+ (- d0 d1)) (1+ (- d2 d1)))
3980 (match-string 1))))
3981 (setq txt org-agenda-no-heading-message))
3982 (add-text-properties
3983 0 (length txt) (append (list 'org-marker marker
3984 'org-hd-marker hdmarker
3985 'priority (org-get-priority txt))
3986 props)
3987 txt)
3988 (push txt ee)))
3989 (outline-next-heading))
3990 ;; Sort the entries by expiration date.
3991 (nreverse ee)))
3992
3993
3994 (defun org-format-agenda-item (prefix txt)
3995 "Format TXT to be inserted into the agenda buffer.
3996 In particular, this indents the line and adds a category."
3997 (let ((cat (or org-category
3998 (file-name-sans-extension
3999 (file-name-nondirectory (buffer-file-name)))))
4000 time rtn)
4001 (if (symbolp cat) (setq cat (symbol-name cat)))
4002 (setq rtn (format " %-10s %s%s" (concat cat ":") prefix txt))
4003 (add-text-properties
4004 0 2 (list 'category (downcase cat)
4005 'prefix-length (- (length rtn) (length txt))
4006 'time-of-day (org-get-time-of-day rtn))
4007 rtn)
4008 rtn))
4009
4010 ;; FIXME: Should this be restricted to beginning of string?
4011 (defun org-get-time-of-day (s)
4012 "Check string S for a time of day."
4013 (save-match-data
4014 (when (and
4015 (string-match
4016 "\\<\\([012][0-9]\\)\\(:\\([0-6][0-9]\\)\\)?\\([AaPp][Mm]\\)?\\>" s)
4017 (or (match-beginning 2) (match-beginning 4)))
4018 (+ (* 100 (+ (string-to-number (match-string 1 s))
4019 (if (and (match-beginning 4)
4020 (equal (downcase (match-string 4 s)) "pm"))
4021 12 0)))
4022 (if (match-beginning 3)
4023 (string-to-number (match-string 3 s))
4024 0)))))
4025
4026 (defun org-finalize-agenda-entries (list)
4027 "Sort and concatenate the agenda items."
4028 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4029
4030 (defsubst org-cmp-priority (a b)
4031 "Compare the priorities of string a and b."
4032 (let ((pa (or (get-text-property 1 'priority a) 0))
4033 (pb (or (get-text-property 1 'priority b) 0)))
4034 (cond ((> pa pb) +1)
4035 ((< pa pb) -1)
4036 (t nil))))
4037
4038 (defsubst org-cmp-category (a b)
4039 "Compare the string values of categories of strings a and b."
4040 (let ((ca (or (get-text-property 1 'category a) ""))
4041 (cb (or (get-text-property 1 'category b) "")))
4042 (cond ((string-lessp ca cb) -1)
4043 ((string-lessp cb ca) +1)
4044 (t nil))))
4045
4046 (defsubst org-cmp-time (a b)
4047 "Compare the time-of-day values of strings a and b."
4048 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4049 (ta (or (get-text-property 1 'time-of-day a) def))
4050 (tb (or (get-text-property 1 'time-of-day b) def)))
4051 (cond ((< ta tb) -1)
4052 ((< tb ta) +1)
4053 (t nil))))
4054
4055 (defun org-entries-lessp (a b)
4056 "Predicate for sorting agenda entries."
4057 (let* ((time-up (org-cmp-time a b))
4058 (time-down (if time-up (- time-up) nil))
4059 (priority-up (org-cmp-priority a b))
4060 (priority-down (if priority-up (- priority-up) nil))
4061 (category-up (org-cmp-category a b))
4062 (category-down (if category-up (- category-up) nil))
4063 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4064 (cdr (assoc
4065 (eval (cons 'or org-agenda-sorting-strategy))
4066 '((-1 . t) (1 . nil) (nil . nil))))))
4067
4068 (defun org-agenda-show-priority ()
4069 "Show the priority of the current item.
4070 This priority is composed of the main priority given with the [#A] cookies,
4071 and by additional input from the age of a schedules or deadline entry."
4072 (interactive)
4073 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4074 (message "Priority is %d" (if pri pri -1000))))
4075
4076 (defun org-agenda-goto ()
4077 "Go to the Org-mode file which contains the item at point."
4078 (interactive)
4079 (let* ((marker (or (get-text-property (point) 'org-marker)
4080 (org-agenda-error)))
4081 (buffer (marker-buffer marker))
4082 (pos (marker-position marker)))
4083 (switch-to-buffer-other-window buffer)
4084 (widen)
4085 (goto-char pos)
4086 (when (eq major-mode 'org-mode)
4087 (org-show-hidden-entry)
4088 (save-excursion
4089 (and (outline-next-heading)
4090 (org-flag-heading nil)))))) ; show the next heading
4091
4092 (defun org-agenda-switch-to ()
4093 "Go to the Org-mode file which contains the item at point."
4094 (interactive)
4095 (let* ((marker (or (get-text-property (point) 'org-marker)
4096 (org-agenda-error)))
4097 (buffer (marker-buffer marker))
4098 (pos (marker-position marker)))
4099 (switch-to-buffer buffer)
4100 (delete-other-windows)
4101 (widen)
4102 (goto-char pos)
4103 (when (eq major-mode 'org-mode)
4104 (org-show-hidden-entry)
4105 (save-excursion
4106 (and (outline-next-heading)
4107 (org-flag-heading nil)))))) ; show the next heading
4108
4109 (defun org-agenda-goto-mouse (ev)
4110 "Go to the Org-mode file which contains the item at the mouse click."
4111 (interactive "e")
4112 (mouse-set-point ev)
4113 (org-agenda-goto))
4114
4115 (defun org-agenda-show ()
4116 "Display the Org-mode file which contains the item at point."
4117 (interactive)
4118 (let ((win (selected-window)))
4119 (org-agenda-goto)
4120 (select-window win)))
4121
4122 (defun org-agenda-recenter (arg)
4123 "Display the Org-mode file which contains the item at point and recenter."
4124 (interactive "P")
4125 (let ((win (selected-window)))
4126 (org-agenda-goto)
4127 (recenter arg)
4128 (select-window win)))
4129
4130 (defun org-agenda-show-mouse (ev)
4131 "Display the Org-mode file which contains the item at the mouse click."
4132 (interactive "e")
4133 (mouse-set-point ev)
4134 (org-agenda-show))
4135
4136 (defun org-agenda-check-no-diary ()
4137 "Check if the entry is a diary link and abort if yes."
4138 (if (get-text-property (point) 'org-agenda-diary-link)
4139 (org-agenda-error)))
4140
4141 (defun org-agenda-error ()
4142 (error "Command not allowed in this line."))
4143
4144 (defvar org-last-heading-marker (make-marker)
4145 "Marker pointing to the headline that last changed its TODO state
4146 by a remote command from the agenda.")
4147
4148 (defun org-agenda-todo ()
4149 "Cycle TODO state of line at point, also in Org-mode file.
4150 This changes the line at point, all other lines in the agenda referring to
4151 the same tree node, and the headline of the tree node in the Org-mode file."
4152 (interactive)
4153 (org-agenda-check-no-diary)
4154 (let* ((col (current-column))
4155 (marker (or (get-text-property (point) 'org-marker)
4156 (org-agenda-error)))
4157 (buffer (marker-buffer marker))
4158 (pos (marker-position marker))
4159 (hdmarker (get-text-property (point) 'org-hd-marker))
4160 (buffer-read-only nil)
4161 newhead)
4162 (save-excursion
4163 (set-buffer buffer)
4164 (widen)
4165 (goto-char pos)
4166 (org-show-hidden-entry)
4167 (save-excursion
4168 (and (outline-next-heading)
4169 (org-flag-heading nil))) ; show the next heading
4170 (org-todo)
4171 (forward-char 1)
4172 (setq newhead (org-get-heading))
4173 (save-excursion
4174 (org-back-to-heading)
4175 (move-marker org-last-heading-marker (point))))
4176 (beginning-of-line 1)
4177 (save-excursion
4178 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4179 (move-to-column col)))
4180
4181 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4182 "Change all lines in the agenda buffer which match hdmarker.
4183 The new content of the line will be NEWHEAD. HDMARKER is checked with
4184 `equal' against all `org-hd-marker' text properties in the file."
4185 (let* (props m pl undone-face done-face)
4186 (save-excursion
4187 (goto-char (point-max))
4188 (beginning-of-line 1)
4189 (while (not (bobp))
4190 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4191 (equal m hdmarker))
4192 (setq props (text-properties-at (point))
4193 pl (get-text-property (point) 'prefix-length)
4194 undone-face (get-text-property (point) 'undone-face)
4195 done-face (get-text-property (point) 'done-face))
4196 (move-to-column pl)
4197 (if (looking-at ".*")
4198 (progn
4199 (replace-match newhead t t)
4200 (beginning-of-line 1)
4201 (add-text-properties (point-at-bol) (point-at-eol) props)
4202 (if fixface
4203 (add-text-properties
4204 (point-at-bol) (point-at-eol)
4205 (list 'face
4206 (if org-last-todo-state-is-todo
4207 undone-face done-face))))
4208 (beginning-of-line 1))
4209 (error "Line update did not work")))
4210 (beginning-of-line 0)))))
4211
4212 (defun org-agenda-priority-up ()
4213 "Increase the priority of line at point, also in Org-mode file."
4214 (interactive)
4215 (org-agenda-priority 'up))
4216
4217 (defun org-agenda-priority-down ()
4218 "Decrease the priority of line at point, also in Org-mode file."
4219 (interactive)
4220 (org-agenda-priority 'down))
4221
4222 (defun org-agenda-priority (&optional force-direction)
4223 "Set the priority of line at point, also in Org-mode file.
4224 This changes the line at point, all other lines in the agenda referring to
4225 the same tree node, and the headline of the tree node in the Org-mode file."
4226 (interactive)
4227 (org-agenda-check-no-diary)
4228 (let* ((props (text-properties-at (point)))
4229 (col (current-column))
4230 (marker (or (get-text-property (point) 'org-marker)
4231 (org-agenda-error)))
4232 (pl (get-text-property (point-at-bol) 'prefix-length))
4233 (buffer (marker-buffer marker))
4234 (pos (marker-position marker))
4235 (hdmarker (get-text-property (point) 'org-hd-marker))
4236 (buffer-read-only nil)
4237 newhead)
4238 (save-excursion
4239 (set-buffer buffer)
4240 (widen)
4241 (goto-char pos)
4242 (org-show-hidden-entry)
4243 (save-excursion
4244 (and (outline-next-heading)
4245 (org-flag-heading nil))) ; show the next heading
4246 (funcall 'org-priority force-direction)
4247 (setq newhead (org-get-heading)))
4248 (org-agenda-change-all-lines newhead hdmarker)
4249 (beginning-of-line 1)))
4250
4251 (defun org-agenda-date-later (arg &optional what)
4252 "Change the date of this item to one day later."
4253 (interactive "p")
4254 (org-agenda-check-no-diary)
4255 (let* ((marker (or (get-text-property (point) 'org-marker)
4256 (org-agenda-error)))
4257 (buffer (marker-buffer marker))
4258 (pos (marker-position marker)))
4259 (save-excursion
4260 (set-buffer buffer)
4261 (widen)
4262 (goto-char pos)
4263 (if (not (org-at-timestamp-p))
4264 (error "Cannot find time stamp"))
4265 (org-timestamp-change arg (or what 'day))
4266 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4267
4268 (defun org-agenda-date-earlier (arg &optional what)
4269 "Change the date of this item to one day earlier."
4270 (interactive "p")
4271 (org-agenda-date-later (- arg) what))
4272
4273 (defun org-agenda-date-prompt (arg)
4274 "Change the date of this item. Date is prompted for, with default today."
4275 (interactive "p")
4276 (org-agenda-check-no-diary)
4277 (let* ((marker (or (get-text-property (point) 'org-marker)
4278 (org-agenda-error)))
4279 (buffer (marker-buffer marker))
4280 (pos (marker-position marker)))
4281 (save-excursion
4282 (set-buffer buffer)
4283 (widen)
4284 (goto-char pos)
4285 (if (not (org-at-timestamp-p))
4286 (error "Cannot find time stamp"))
4287 (org-time-stamp nil)
4288 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4289
4290 (defun org-get-heading ()
4291 "Return the heading of the current entry, without the stars."
4292 (save-excursion
4293 (if (and (re-search-backward "[\r\n]\\*" nil t)
4294 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
4295 (match-string 1)
4296 "")))
4297
4298 (defun org-agenda-diary-entry (arg)
4299 "Make a diary entry, like the `i' command from the calendar.
4300 All the standard commands work: block, weekly etc"
4301 (interactive "P")
4302 (require 'diary-lib)
4303 (let* ((char (progn
4304 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
4305 (read-char-exclusive)))
4306 (cmd (cdr (assoc char
4307 '((?d . insert-diary-entry)
4308 (?w . insert-weekly-diary-entry)
4309 (?m . insert-monthly-diary-entry)
4310 (?y . insert-yearly-diary-entry)
4311 (?a . insert-anniversary-diary-entry)
4312 (?b . insert-block-diary-entry)
4313 (?c . insert-cyclic-diary-entry)))))
4314 (oldf (symbol-function 'calendar-cursor-to-date))
4315 (point (point))
4316 (mark (or (mark t) (point))))
4317 (unless cmd
4318 (error "No command associated with <%c>" char))
4319 (unless (and (get-text-property point 'day)
4320 (or (not (equal ?b char))
4321 (get-text-property mark 'day)))
4322 (error "Don't know which date to use for diary entry"))
4323 ;; We implement this by hacking the `calendar-cursor-to-date' function
4324 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
4325 (let ((calendar-mark-ring
4326 (list (calendar-gregorian-from-absolute
4327 (or (get-text-property mark 'day)
4328 (get-text-property point 'day))))))
4329 (unwind-protect
4330 (progn
4331 (fset 'calendar-cursor-to-date
4332 (lambda (&optional error)
4333 (calendar-gregorian-from-absolute
4334 (get-text-property point 'day))))
4335 (call-interactively cmd))
4336 (fset 'calendar-cursor-to-date oldf)))))
4337
4338
4339 (defun org-agenda-execute-calendar-command (cmd)
4340 "Execute a calendar command from the agenda, with the date associated to
4341 the cursor position."
4342 (require 'diary-lib)
4343 (unless (get-text-property (point) 'day)
4344 (error "Don't know which date to use for calendar command"))
4345 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
4346 (point (point))
4347 (mark (or (mark t) (point)))
4348 (date (calendar-gregorian-from-absolute
4349 (get-text-property point 'day)))
4350 (displayed-day (extract-calendar-day date))
4351 (displayed-month (extract-calendar-month date))
4352 (displayed-year (extract-calendar-year date)))
4353 (unwind-protect
4354 (progn
4355 (fset 'calendar-cursor-to-date
4356 (lambda (&optional error)
4357 (calendar-gregorian-from-absolute
4358 (get-text-property point 'day))))
4359 (call-interactively cmd))
4360 (fset 'calendar-cursor-to-date oldf))))
4361
4362 (defun org-agenda-phases-of-moon ()
4363 "Display the phases of the moon for the 3 months around the cursor date."
4364 (interactive)
4365 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
4366
4367 (defun org-agenda-holidays ()
4368 "Display the holidays for the 3 months around the cursor date."
4369 (interactive)
4370 (org-agenda-execute-calendar-command 'list-calendar-holidays))
4371
4372 (defun org-agenda-sunrise-sunset (arg)
4373 "Display sunrise and sunset for the cursor date.
4374 Latitude and longitude can be specified with the variables
4375 `calendar-latitude' and `calendar-longitude'. When called with prefix
4376 argument, latitude and longitude will be prompted for."
4377 (interactive "P")
4378 (let ((calendar-longitude (if arg nil calendar-longitude))
4379 (calendar-latitude (if arg nil calendar-latitude))
4380 (calendar-location-name
4381 (if arg "the given coordinates" calendar-location-name)))
4382 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
4383
4384 (defun org-agenda-goto-calendar ()
4385 "Open the Emacs calendar with the date at the cursor."
4386 (interactive)
4387 (let* ((day (or (get-text-property (point) 'day)
4388 (error "Don't know which date to open in calendar")))
4389 (date (calendar-gregorian-from-absolute day)))
4390 (calendar)
4391 (calendar-goto-date date)))
4392
4393 (defun org-calendar-goto-agenda ()
4394 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
4395 This is a command that has to be installed in `calendar-mode-map'."
4396 (interactive)
4397 (org-agenda nil (calendar-absolute-from-gregorian
4398 (calendar-cursor-to-date))))
4399
4400 (defun org-agenda-convert-date ()
4401 (interactive)
4402 (let ((day (get-text-property (point) 'day))
4403 date s)
4404 (unless day
4405 (error "Don't know which date to convert"))
4406 (setq date (calendar-gregorian-from-absolute day))
4407 (setq s (concat
4408 "Gregorian: " (calendar-date-string date) "\n"
4409 "ISO: " (calendar-iso-date-string date) "\n"
4410 "Day of Yr: " (calendar-day-of-year-string date) "\n"
4411 "Julian: " (calendar-julian-date-string date) "\n"
4412 "Astronomic: " (calendar-astro-date-string date)
4413 " (Julian date number at noon UTC)\n"
4414 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
4415 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
4416 "French: " (calendar-french-date-string date) "\n"
4417 "Mayan: " (calendar-mayan-date-string date) "\n"
4418 "Coptic: " (calendar-coptic-date-string date) "\n"
4419 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
4420 "Persian: " (calendar-persian-date-string date) "\n"
4421 "Chinese: " (calendar-chinese-date-string date) "\n"))
4422 (with-output-to-temp-buffer "*Dates*"
4423 (princ s))
4424 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
4425
4426 ;;; Link Stuff
4427
4428 (defun org-find-file-at-mouse (ev)
4429 "Open file link or URL at mouse."
4430 (interactive "e")
4431 (mouse-set-point ev)
4432 (org-open-at-point 'in-emacs))
4433
4434 (defun org-open-at-mouse (ev)
4435 "Open file link or URL at mouse."
4436 (interactive "e")
4437 (mouse-set-point ev)
4438 (org-open-at-point))
4439
4440 (defun org-open-at-point (&optional in-emacs)
4441 "Open link at or after point.
4442 If there is no link at point, this function will search forward up to
4443 the end of the current subtree.
4444 Normally, files will be opened by an appropriate application. If the
4445 optional argument IN-EMACS is non-nil, Emacs will visit the file."
4446 (interactive "P")
4447 (if (org-at-timestamp-p)
4448 (org-agenda nil (time-to-days (org-time-string-to-time
4449 (substring (match-string 1) 0 10)))
4450 1)
4451 (let (type path line (pos (point)))
4452 (save-excursion
4453 (skip-chars-backward
4454 (if org-allow-space-in-links "^\t\n\r" "^ \t\n\r"))
4455 (if (re-search-forward
4456 org-link-regexp
4457 (save-excursion
4458 (condition-case nil
4459 (progn (outline-end-of-subtree) (max pos (point)))
4460 (error (end-of-line 1) (point))))
4461 t)
4462 (setq type (match-string 1)
4463 path (match-string 2)))
4464 (unless path
4465 (error "No link found."))
4466 ;; Remove any trailing spaces in path
4467 (if (string-match " +\\'" path)
4468 (setq path (replace-match "" t t path)))
4469
4470 (cond
4471
4472 ((string= type "file")
4473 (if (string-match ":\\([0-9]+\\)\\'" path)
4474 (setq line (string-to-number (match-string 1 path))
4475 path (substring path 0 (match-beginning 0))))
4476 (org-open-file path in-emacs line))
4477
4478 ((string= type "news")
4479 (org-follow-gnus-link path))
4480
4481 ((string= type "bbdb")
4482 (org-follow-bbdb-link path))
4483
4484 ((string= type "gnus")
4485 (let (group article)
4486 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4487 (error "Error in Gnus link"))
4488 (setq group (match-string 1 path)
4489 article (match-string 3 path))
4490 (org-follow-gnus-link group article)))
4491
4492 ((string= type "vm")
4493 (let (folder article)
4494 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4495 (error "Error in VM link"))
4496 (setq folder (match-string 1 path)
4497 article (match-string 3 path))
4498 ;; in-emacs is the prefix arg, will be interpreted as read-only
4499 (org-follow-vm-link folder article in-emacs)))
4500
4501 ((string= type "wl")
4502 (let (folder article)
4503 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4504 (error "Error in Wanderlust link"))
4505 (setq folder (match-string 1 path)
4506 article (match-string 3 path))
4507 (org-follow-wl-link folder article)))
4508
4509 ((string= type "rmail")
4510 (let (folder article)
4511 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
4512 (error "Error in RMAIL link"))
4513 (setq folder (match-string 1 path)
4514 article (match-string 3 path))
4515 (org-follow-rmail-link folder article)))
4516
4517 ((string= type "shell")
4518 (let ((cmd path))
4519 (if (or (not org-confirm-shell-links)
4520 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
4521 (shell-command cmd)
4522 (error "Abort"))))
4523
4524 (t
4525 (browse-url-at-point)))))))
4526
4527 (defun org-follow-bbdb-link (name)
4528 "Follow a BBDB link to NAME."
4529 (require 'bbdb)
4530 ;; First try an exact match
4531 (bbdb-name (concat "\\`" name "\\'") nil)
4532 (if (= 0 (buffer-size (get-buffer "*BBDB*")))
4533 ;; No exact match - try partial match
4534 (bbdb-name name nil)))
4535
4536 (defun org-follow-gnus-link (&optional group article)
4537 "Follow a Gnus link to GROUP and ARTICLE."
4538 (require 'gnus)
4539 (funcall (cdr (assq 'gnus org-link-frame-setup)))
4540 (if group (gnus-fetch-group group))
4541 (if article
4542 (or (gnus-summary-goto-article article nil 'force)
4543 (if (fboundp 'gnus-summary-insert-cached-articles)
4544 (progn
4545 (gnus-summary-insert-cached-articles)
4546 (gnus-summary-goto-article article nil 'force))
4547 (message "Message could not be found.")))))
4548 ;; (if article (gnus-summary-goto-article article nil 'force)))
4549
4550 (defun org-follow-vm-link (&optional folder article readonly)
4551 "Follow a VM link to FOLDER and ARTICLE."
4552 (require 'vm)
4553 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
4554 ;; ange-ftp or efs or tramp access
4555 (let ((user (or (match-string 1 folder) (user-login-name)))
4556 (host (match-string 2 folder))
4557 (file (match-string 3 folder)))
4558 (cond
4559 ((featurep 'tramp)
4560 ;; use tramp to access the file
4561 (if org-xemacs-p
4562 (setq folder (format "[%s@%s]%s" user host file))
4563 (setq folder (format "/%s@%s:%s" user host file))))
4564 (t
4565 ;; use ange-ftp or efs
4566 (require (if org-xemacs-p 'efs 'ange-ftp))
4567 (setq folder (format "/%s@%s:%s" user host file))))))
4568 (when folder
4569 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
4570 (sit-for 0.1)
4571 (when article
4572 (vm-select-folder-buffer)
4573 (widen)
4574 (let ((case-fold-search t))
4575 (goto-char (point-min))
4576 (if (not (re-search-forward
4577 (concat "^" "message-id: *" (regexp-quote article))))
4578 (error "Could not find the specified message in this folder"))
4579 (vm-isearch-update)
4580 (vm-isearch-narrow)
4581 (vm-beginning-of-message)
4582 (vm-summarize)))))
4583
4584 (defun org-follow-wl-link (folder article)
4585 "Follow a Wanderlust link to FOLDER and ARTICLE."
4586 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
4587 (if article (wl-summary-jump-to-msg-by-message-id article))
4588 (wl-summary-redisplay))
4589
4590 (defun org-follow-rmail-link (folder article)
4591 "Follow an RMAIL link to FOLDER and ARTICLE."
4592 (let (message-number)
4593 (save-excursion
4594 (save-window-excursion
4595 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4596 (setq message-number
4597 (save-restriction
4598 (widen)
4599 (goto-char (point-max))
4600 (if (re-search-backward
4601 (concat "^Message-ID:\\s-+" (regexp-quote
4602 (or article "")))
4603 nil t)
4604 (rmail-what-message))))))
4605 (if message-number
4606 (progn
4607 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
4608 (rmail-show-message message-number)
4609 message-number)
4610 (error "Message not found"))))
4611
4612 (defun org-open-file (path &optional in-emacs line)
4613 "Open the file at PATH.
4614 First, this expands any special file name abbreviations. Then the
4615 configuration variable `org-file-apps' is checked if it contains an
4616 entry for this file type, and if yes, the corresponding command is launched.
4617 If no application is found, Emacs simply visits the file.
4618 With optional argument IN-EMACS, Emacs will visit the file.
4619 If the file does not exist, an error is thrown."
4620 (let* ((file (convert-standard-filename (org-expand-file-name path)))
4621 (dfile (downcase file))
4622 ext cmd apps)
4623 (if (and (not (file-exists-p file))
4624 (not org-open-non-existing-files))
4625 (error "No such file: %s" file))
4626 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
4627 (setq ext (match-string 1 dfile))
4628 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
4629 (setq ext (match-string 1 dfile))))
4630 (setq apps (append org-file-apps (org-default-apps)))
4631 (if in-emacs
4632 (setq cmd 'emacs)
4633 (setq cmd (or (cdr (assoc ext apps))
4634 (cdr (assoc t apps)))))
4635 (cond
4636 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
4637 (setq cmd (format cmd file))
4638 (save-window-excursion
4639 (shell-command (concat cmd " & &"))))
4640 ((or (stringp cmd)
4641 (eq cmd 'emacs))
4642 (funcall (cdr (assq 'file org-link-frame-setup)) file)
4643 (if line (goto-line line)))
4644 ((consp cmd)
4645 (eval cmd))
4646 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
4647
4648 (defun org-default-apps ()
4649 "Return the default applications for this operating system."
4650 (cond
4651 ((eq system-type 'darwin)
4652 org-file-apps-defaults-macosx)
4653 ((eq system-type 'windows-nt)
4654 org-file-apps-defaults-windowsnt)
4655 ((eq system-type 'linux)
4656 org-file-apps-defaults-linux)
4657 (t org-file-apps-defaults-linux)))
4658
4659 (defun org-expand-file-name (path)
4660 "Replace special path abbreviations and expand the file name."
4661 (expand-file-name path))
4662
4663
4664 (defvar org-insert-link-history nil
4665 "Minibuffer history for links inserted with `org-insert-link'.")
4666
4667 (defvar org-stored-links nil
4668 "Contains the links stored with `org-store-link'.")
4669
4670 ;;;###autoload
4671 (defun org-store-link (arg)
4672 "\\<org-mode-map>Store an org-link to the current location.
4673 This link can later be inserted into an org-buffer with
4674 \\[org-insert-link].
4675 For some link types, a prefix arg is interpreted:
4676 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
4677 For file links, arg negates `org-line-numbers-in-file-links'."
4678 (interactive "P")
4679 (let (link cpltxt)
4680 (cond
4681
4682 ((eq major-mode 'bbdb-mode)
4683 (setq link (concat "bbdb:"
4684 (bbdb-record-name (bbdb-current-record)))))
4685
4686 ((eq major-mode 'calendar-mode)
4687 (let ((cd (calendar-cursor-to-date)))
4688 (setq link
4689 (format-time-string
4690 (car org-time-stamp-formats)
4691 (apply 'encode-time
4692 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
4693 nil nil nil))))))
4694
4695 ((or (eq major-mode 'vm-summary-mode)
4696 (eq major-mode 'vm-presentation-mode))
4697 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
4698 (vm-follow-summary-cursor)
4699 (save-excursion
4700 (vm-select-folder-buffer)
4701 (let* ((message (car vm-message-pointer))
4702 (folder (buffer-file-name))
4703 (subject (vm-su-subject message))
4704 (author (vm-su-full-name message))
4705 (address (vm-su-from message))
4706 (message-id (vm-su-message-id message)))
4707 (setq folder (abbreviate-file-name folder))
4708 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
4709 folder)
4710 (setq folder (replace-match "" t t folder)))
4711 (setq cpltxt (concat author " on: " subject))
4712 (setq link (concat cpltxt "\n " "vm:" folder
4713 "#" message-id)))))
4714
4715 ((eq major-mode 'wl-summary-mode)
4716 (let* ((msgnum (wl-summary-message-number))
4717 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
4718 msgnum 'message-id))
4719 (wl-message-entity (elmo-msgdb-overview-get-entity
4720 msgnum (wl-summary-buffer-msgdb)))
4721 (author (wl-summary-line-from)) ; FIXME: how to get author name?
4722 (subject "???")) ; FIXME: How to get subject of email?
4723 (setq cpltxt (concat author " on: " subject))
4724 (setq link (concat cpltxt "\n " "wl:" wl-summary-buffer-folder-name
4725 "#" message-id))))
4726
4727 ((eq major-mode 'rmail-mode)
4728 (save-excursion
4729 (save-restriction
4730 (rmail-narrow-to-non-pruned-header)
4731 (let ((folder (buffer-file-name))
4732 (message-id (mail-fetch-field "message-id"))
4733 (author (mail-fetch-field "from"))
4734 (subject (mail-fetch-field "subject")))
4735 (setq cpltxt (concat author " on: " subject))
4736 (setq link (concat cpltxt "\n " "rmail:" folder
4737 "#" message-id))))))
4738
4739 ((eq major-mode 'gnus-group-mode)
4740 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
4741 (gnus-group-group-name)) ; version
4742 ((fboundp 'gnus-group-name)
4743 (gnus-group-name))
4744 (t "???"))))
4745 (if (org-xor arg org-usenet-links-prefer-google)
4746 (setq link (format "http://groups.google.com/groups?group=%s"
4747 group))
4748 (setq link (concat "gnus:" group)))))
4749
4750 ((or (eq major-mode 'gnus-summary-mode)
4751 (eq major-mode 'gnus-article-mode))
4752 (gnus-article-show-summary)
4753 (gnus-summary-beginning-of-article)
4754 (let* ((group (car gnus-article-current))
4755 (article (cdr gnus-article-current))
4756 (header (gnus-summary-article-header article))
4757 (author (mail-header-from header))
4758 (message-id (mail-header-id header))
4759 (date (mail-header-date header))
4760 (subject (gnus-summary-subject-string)))
4761 (setq cpltxt (concat author " on: " subject))
4762 (if (org-xor arg org-usenet-links-prefer-google)
4763 (setq link
4764 (concat
4765 cpltxt "\n "
4766 (format "http://groups.google.com/groups?as_umsgid=%s"
4767 (org-fixup-message-id-for-http message-id))))
4768 (setq link (concat cpltxt "\n" "gnus:" group
4769 "#" (number-to-string article))))))
4770
4771 ((eq major-mode 'w3-mode)
4772 (setq link (url-view-url t)))
4773 ((eq major-mode 'w3m-mode)
4774 (setq link w3m-current-url))
4775
4776 ((buffer-file-name)
4777 ;; Just link to this file here.
4778 (setq link (concat "file:"
4779 (abbreviate-file-name (buffer-file-name))))
4780 ;; Add the line number?
4781 (if (org-xor org-line-numbers-in-file-links arg)
4782 (setq link
4783 (concat link
4784 ":" (int-to-string
4785 (+ (if (bolp) 1 0) (count-lines
4786 (point-min) (point))))))))
4787 ((interactive-p)
4788 (error "Cannot link to a buffer which is not visiting a file"))
4789 (t (setq link nil)))
4790
4791 (if (and (interactive-p) link)
4792 (progn
4793 (setq org-stored-links
4794 (cons (cons (or cpltxt link) link) org-stored-links))
4795 (message "Stored: %s" (or cpltxt link)))
4796 link)))
4797
4798 (defun org-xor (a b)
4799 "Exclusive or."
4800 (or (and a (not b))
4801 (and b (not a))))
4802
4803 (defun org-get-header (header)
4804 "Find a header field in the current buffer."
4805 (save-excursion
4806 (goto-char (point-min))
4807 (let ((case-fold-search t) s)
4808 (cond
4809 ((eq header 'from)
4810 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
4811 (setq s (match-string 1)))
4812 (while (string-match "\"" s)
4813 (setq s (replace-match "" t t s)))
4814 (if (string-match "[<(].*" s)
4815 (setq s (replace-match "" t t s))))
4816 ((eq header 'message-id)
4817 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
4818 (setq s (match-string 1))))
4819 ((eq header 'subject)
4820 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
4821 (setq s (match-string 1)))))
4822 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
4823 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
4824 s)))
4825
4826
4827 (defun org-fixup-message-id-for-http (s)
4828 "Replace special characters in a message id, so that it can be used
4829 in an http query."
4830 (while (string-match "<" s)
4831 (setq s (replace-match "%3C" t t s)))
4832 (while (string-match ">" s)
4833 (setq s (replace-match "%3E" t t s)))
4834 (while (string-match "@" s)
4835 (setq s (replace-match "%40" t t s)))
4836 s)
4837
4838 (defun org-insert-link (&optional complete-file)
4839 "Insert a link. At the prompt, enter the link.
4840
4841 Completion can be used to select a link previously stored with
4842 `org-store-link'. When the empty string is entered (i.e. if you just
4843 press RET at the prompt), the link defaults to the most recently
4844 stored link.
4845
4846 With a C-u prefix, prompts for a file to link to. The file name can be
4847 selected using completion. The path to the file will be relative to
4848 the current directory if the file is in the current directory or a
4849 subdirectory. Otherwise, the link will be the absolute path as
4850 completed in the minibuffer (i.e. normally ~/path/to/file).
4851
4852 With two C-u prefixes, enforce an absolute path even if the file
4853 is in the current directory or below."
4854 (interactive "P")
4855 (let ((link (if complete-file
4856 (read-file-name "File: ")
4857 (completing-read
4858 "Link: " org-stored-links nil nil nil
4859 org-insert-link-history
4860 (or (car (car org-stored-links))))))
4861 linktxt matched)
4862 (if (or (not link) (equal link ""))
4863 (error "No links available"))
4864 (if complete-file
4865 (let ((pwd (file-name-as-directory (expand-file-name "."))))
4866 (cond
4867 ((equal complete-file '(16))
4868 (insert "file:" (abbreviate-file-name (expand-file-name link))))
4869 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
4870 (expand-file-name link))
4871 (insert "file:" (match-string 1 (expand-file-name link))))
4872 (t (insert "file:" link))))
4873 (setq linktxt (cdr (assoc link org-stored-links)))
4874 (if (not org-keep-stored-link-after-insertion)
4875 (setq org-stored-links (delq (assoc link org-stored-links)
4876 org-stored-links)))
4877 (let ((lines (org-split-string (or linktxt link) "\n")))
4878 (insert (car lines))
4879 (setq matched (string-match org-link-regexp (car lines)))
4880 (setq lines (cdr lines))
4881 (while lines
4882 (insert "\n")
4883 (if (save-excursion
4884 (beginning-of-line 0)
4885 (looking-at "[ \t]+\\S-"))
4886 (indent-relative))
4887 (setq matched (or matched
4888 (string-match org-link-regexp (car lines))))
4889 (insert (car lines))
4890 (setq lines (cdr lines))))
4891 (unless matched
4892 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
4893
4894 ;;; Hooks for remember.el
4895 ;;;###autoload
4896 (defun org-remember-annotation ()
4897 "Return a link to the current location as an annotation for remember.el.
4898 If you are using Org-mode files as target for data storage with
4899 remember.el, then the annotations should include a link compatible with the
4900 conventions in Org-mode. This function returns such a link."
4901 (org-store-link nil))
4902
4903 (defconst org-remember-help
4904 "Select a destination location for the note.
4905 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
4906 RET at beg-of-buf -> Append to file as level 2 headline
4907 RET on headline -> Store as sublevel entry to current headline
4908 <left>/<right> -> before/after current headline, same headings level")
4909
4910 ;;;###autoload
4911 (defun org-remember-handler ()
4912 "Store stuff from remember.el into an org file.
4913 First prompts for an org file. If the user just presses return, the value
4914 of `org-default-notes-file' is used.
4915 Then the command offers the headings tree of the selected file in order to
4916 file the text at a specific location.
4917 You can either immediately press RET to get the note appended to the
4918 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
4919 find a better place. Then press RET or <left> or <right> in insert the note.
4920
4921 Key Cursor position Note gets inserted
4922 -----------------------------------------------------------------------------
4923 RET buffer-start as level 2 heading at end of file
4924 RET on headline as sublevel of the heading at cursor
4925 RET no heading at cursor position, level taken from context.
4926 Or use prefix arg to specify level manually.
4927 <left> on headline as same level, before current heading
4928 <right> on headline as same level, after current heading
4929
4930 So the fastest way to store the note is to press RET RET to append it to
4931 the default file. This way your current train of thought is not
4932 interrupted, in accordance with the principles of remember.el. But with
4933 little extra effort, you can push it directly to the correct location.
4934
4935 Before being stored away, the function ensures that the text has a
4936 headline, i.e. a first line that starts with a \"*\". If not, a headline
4937 is constructed from the current date and some additional data.
4938
4939 If the variable `org-adapt-indentation' is non-nil, the entire text is
4940 also indented so that it starts in the same column as the headline
4941 \(i.e. after the stars).
4942
4943 See also the variable `org-reverse-note-order'."
4944 (catch 'quit
4945 (let* ((txt (buffer-substring (point-min) (point-max)))
4946 (fastp current-prefix-arg)
4947 (file (if fastp org-default-notes-file (org-get-org-file)))
4948 (visiting (find-buffer-visiting file))
4949 (org-startup-with-deadline-check nil)
4950 (org-startup-folded nil)
4951 spos level indent reversed)
4952 ;; Modify text so that it becomes a nice subtree which can be inserted
4953 ;; into an org tree.
4954 (let* ((lines (split-string txt "\n"))
4955 (first (car lines))
4956 (lines (cdr lines)))
4957 (if (string-match "^\\*+" first)
4958 ;; Is already a headline
4959 (setq indent (make-string (- (match-end 0) (match-beginning 0)
4960 -1) ?\ ))
4961 ;; We need to add a headline: Use time and first buffer line
4962 (setq lines (cons first lines)
4963 first (concat "* " (current-time-string)
4964 " (" (remember-buffer-desc) ")")
4965 indent " "))
4966 (if org-adapt-indentation
4967 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
4968 (setq txt (concat first "\n"
4969 (mapconcat 'identity lines "\n"))))
4970 ;; Find the file
4971 (if (not visiting)
4972 (find-file-noselect file))
4973 (save-excursion
4974 (set-buffer (get-file-buffer file))
4975 (setq reversed (org-notes-order-reversed-p))
4976 (save-restriction
4977 (save-excursion
4978 (widen)
4979 ;; Ask the User for a location
4980 (setq spos (if fastp 1 (org-get-location
4981 (current-buffer)
4982 org-remember-help)))
4983 (if (not spos) (throw 'quit nil)) ; return nil to show we did
4984 ; not handle this note
4985 (goto-char spos)
4986 (cond ((bobp)
4987 ;; Put it at the start or end, as level 2
4988 (save-restriction
4989 (widen)
4990 (goto-char (if reversed (point-min) (point-max)))
4991 (if (not (bolp)) (newline))
4992 (org-paste-subtree (or current-prefix-arg 2) txt)))
4993 ((and (org-on-heading-p nil) (not current-prefix-arg))
4994 ;; Put it below this entry, at the beg/end of the subtree
4995 (org-back-to-heading)
4996 (setq level (outline-level))
4997 (if reversed
4998 (outline-end-of-heading)
4999 (outline-end-of-subtree))
5000 (if (not (bolp)) (newline))
5001 (beginning-of-line 1)
5002 (org-paste-subtree (1+ level) txt))
5003 (t
5004 ;; Put it right there, with automatic level determined by
5005 ;; org-paste-subtree or from prefix arg
5006 (org-paste-subtree current-prefix-arg txt)))
5007 (when remember-save-after-remembering
5008 (save-buffer)
5009 (if (not visiting) (kill-buffer (current-buffer)))))))))
5010 t) ;; return t to indicate that we took care of this note.
5011
5012 (defun org-get-org-file ()
5013 "Read a filename, with default directory `org-directory'."
5014 (let ((default (or org-default-notes-file remember-data-file)))
5015 (read-file-name (format "File name [%s]: " default)
5016 (file-name-as-directory org-directory)
5017 default)))
5018
5019 (defun org-notes-order-reversed-p ()
5020 "Check if the current file should receive notes in reversed order."
5021 (cond
5022 ((not org-reverse-note-order) nil)
5023 ((eq t org-reverse-note-order) t)
5024 ((not (listp org-reverse-note-order)) nil)
5025 (t (catch 'exit
5026 (let ((all org-reverse-note-order)
5027 entry)
5028 (while (setq entry (pop all))
5029 (if (string-match (car entry) (buffer-file-name))
5030 (throw 'exit (cdr entry))))
5031 nil)))))
5032
5033 ;;; Tables
5034
5035 ;; Watch out: Here we are talking about two different kind of tables.
5036 ;; Most of the code is for the tables created with the Org-mode table editor.
5037 ;; Sometimes, we talk about tables created and edited with the table.el
5038 ;; Emacs package. We call the former org-type tables, and the latter
5039 ;; table.el-type tables.
5040
5041 ;; We use a before-change function to check if a table might need
5042 ;; an update.
5043 (defvar org-table-may-need-update t
5044 "Indicates of a table might need an update.
5045 This variable is set by `org-before-change-function'. `org-table-align'
5046 sets it back to nil.")
5047
5048 (defun org-before-change-function (beg end)
5049 "Every change indicates that a table might need an update."
5050 (setq org-table-may-need-update t))
5051
5052 (defconst org-table-line-regexp "^[ \t]*|"
5053 "Detects an org-type table line.")
5054 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5055 "Detects an org-type table line.")
5056 (defconst org-table-hline-regexp "^[ \t]*|-"
5057 "Detects an org-type table hline.")
5058 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5059 "Detects a table-type table hline.")
5060 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5061 "Detects an org-type or table-type table")
5062 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5063 "Searching from within a table (any type) this finds the first line
5064 outside the table.")
5065 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5066 "Searching from within a table (any type) this finds the first line
5067 outside the table.")
5068
5069 (defun org-table-create-with-table.el ()
5070 "Use the table.el package to insert a new table.
5071 If there is already a table at point, convert between Org-mode tables
5072 and table.el tables."
5073 (interactive)
5074 (require 'table)
5075 (cond
5076 ((org-at-table.el-p)
5077 (if (y-or-n-p "Convert table to Org-mode table? ")
5078 (org-table-convert)))
5079 ((org-at-table-p)
5080 (if (y-or-n-p "Convert table to table.el table? ")
5081 (org-table-convert)))
5082 (t (call-interactively 'table-insert))))
5083
5084 (defun org-table-create (&optional size)
5085 "Query for a size and insert a table skeleton.
5086 SIZE is a string Columns x Rows like for example \"3x2\"."
5087 (interactive "P")
5088 (unless size
5089 (setq size (read-string
5090 (concat "Table size Columns x Rows [e.g. "
5091 org-table-default-size "]: ")
5092 "" nil org-table-default-size)))
5093
5094 (let* ((pos (point))
5095 (indent (make-string (current-column) ?\ ))
5096 (split (org-split-string size " *x *"))
5097 (rows (string-to-number (nth 1 split)))
5098 (columns (string-to-number (car split)))
5099 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5100 "\n")))
5101 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5102 (point-at-bol) (point)))
5103 (beginning-of-line 1)
5104 (newline))
5105 (mapcar (lambda (x) (insert line)) (make-list rows t))
5106 (goto-char pos)
5107 (if (> rows 1)
5108 ;; Insert a hline after the first row.
5109 (progn
5110 (end-of-line 1)
5111 (insert "\n|-")
5112 (goto-char pos)))
5113 (org-table-align)))
5114
5115 (defun org-table-convert-region (beg0 end0 nspace)
5116 "Convert region to a table.
5117 The region goes from BEG0 to END0, but these borders will be moved
5118 slightly, to make sure a beginning of line in the first line is included.
5119 When NSPACE is non-nil, it indicates the minimum number of spaces that
5120 separate columns (default: just one space)"
5121 (let* ((beg (min beg0 end0))
5122 (end (max beg0 end0))
5123 (tabsep t)
5124 re)
5125 (goto-char beg)
5126 (beginning-of-line 1)
5127 (setq beg (move-marker (make-marker) (point)))
5128 (goto-char end)
5129 (if (bolp) (backward-char 1) (end-of-line 1))
5130 (setq end (move-marker (make-marker) (point)))
5131 ;; Lets see if this is tab-separated material. If every nonempty line
5132 ;; contains a tab, we will assume that it is tab-separated material
5133 (if nspace
5134 (setq tabsep nil)
5135 (goto-char beg)
5136 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5137 (if nspace (setq tabsep nil))
5138 (if tabsep
5139 (setq re "^\\|\t")
5140 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5141 (max 1 (prefix-numeric-value nspace)))))
5142 (goto-char beg)
5143 (while (re-search-forward re end t)
5144 (replace-match "|" t t))
5145 (goto-char beg)
5146 (insert " ")
5147 (org-table-align)))
5148
5149 (defun org-table-import (file arg)
5150 "Import FILE as a table.
5151 The file is assumed to be tab-separated. Such files can be produced by most
5152 spreadsheet and database applications. If no tabs (at least one per line)
5153 are found, lines will be split on whitespace into fields."
5154 (interactive "f\nP")
5155 (or (bolp) (newline))
5156 (let ((beg (point))
5157 (pm (point-max)))
5158 (insert-file-contents file)
5159 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5160
5161 (defun org-table-export ()
5162 "Export table as a tab-separated file.
5163 Such a file can be imported into a spreadsheet program like Excel."
5164 (interactive)
5165 (let* ((beg (org-table-begin))
5166 (end (org-table-end))
5167 (table (buffer-substring beg end))
5168 (file (read-file-name "Export table to: "))
5169 buf)
5170 (unless (or (not (file-exists-p file))
5171 (y-or-n-p (format "Overwrite file %s? " file)))
5172 (error "Abort"))
5173 (save-excursion
5174 (find-file file)
5175 (setq buf (current-buffer))
5176 (erase-buffer)
5177 (fundamental-mode)
5178 (insert table)
5179 (goto-char (point-min))
5180 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5181 (replace-match "" t t)
5182 (end-of-line 1))
5183 (goto-char (point-min))
5184 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5185 (replace-match "" t t)
5186 (goto-char (min (1+ (point)) (point-max))))
5187 (goto-char (point-min))
5188 (while (re-search-forward "^-[-+]*$" nil t)
5189 (replace-match "")
5190 (if (looking-at "\n")
5191 (delete-char 1)))
5192 (goto-char (point-min))
5193 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5194 (replace-match "\t" t t))
5195 (save-buffer))
5196 (kill-buffer buf)))
5197
5198 (defvar org-table-aligned-begin-marker (make-marker)
5199 "Marker at the beginning of the table last aligned.
5200 Used to check if cursor still is in that table, to minimize realignment.")
5201 (defvar org-table-aligned-end-marker (make-marker)
5202 "Marker at the end of the table last aligned.
5203 Used to check if cursor still is in that table, to minimize realignment.")
5204 (defvar org-table-last-alignment nil
5205 "List of flags for flushright alignment, from the last re-alignment.
5206 This is being used to correctly align a single field after TAB or RET.")
5207 ;; FIXME: The following is currently not used.
5208 (defvar org-table-last-column-widths nil
5209 "List of max width of fields in each column.
5210 This is being used to correctly align a single field after TAB or RET.")
5211
5212
5213 (defun org-table-align (&optional arg)
5214 "Align the table at point by aligning all vertical bars."
5215 (interactive "P")
5216 (let* (
5217 ;; Limits of table
5218 (beg (org-table-begin))
5219 (end (org-table-end))
5220 ;; Current cursor position
5221 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5222 (colpos (org-table-current-column))
5223 (winstart (window-start))
5224 text lines (new "") lengths l typenums ty fields maxfields i
5225 column
5226 (indent "") cnt frac
5227 rfmt hfmt
5228 (spaces (if (org-in-invisibility-spec-p '(org-table))
5229 org-table-spaces-around-invisible-separators
5230 org-table-spaces-around-separators))
5231 (sp1 (car spaces))
5232 (sp2 (cdr spaces))
5233 (rfmt1 (concat
5234 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5235 (hfmt1 (concat
5236 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5237 emptystrings)
5238 (untabify beg end)
5239 ;; (message "Aligning table...")
5240 ;; Get the rows
5241 (setq lines (org-split-string
5242 (buffer-substring-no-properties beg end) "\n"))
5243 ;; Store the indentation of the first line
5244 (if (string-match "^ *" (car lines))
5245 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5246 ;; Mark the hlines
5247 (setq lines (mapcar (lambda (l) (if (string-match "^ *|-" l) nil l))
5248 lines))
5249 ;; Get the data fields
5250 (setq fields (mapcar
5251 (lambda (l)
5252 (org-split-string l " *| *"))
5253 (delq nil (copy-sequence lines))))
5254 ;; How many fields in the longest line?
5255 (condition-case nil
5256 (setq maxfields (apply 'max (mapcar 'length fields)))
5257 (error
5258 (kill-region beg end)
5259 (org-table-create org-table-default-size)
5260 (error "Empty table - created default table")))
5261 ;; A list of empty string to fill any short rows on output
5262 (setq emptystrings (make-list maxfields ""))
5263 ;; Get the maximum length of a field and the most common datatype
5264 ;; for each column
5265 (setq i -1)
5266 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5267 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5268 ;; maximum length
5269 (push (apply 'max 1 (mapcar 'length column)) lengths)
5270 ;; compute the fraction stepwise, ignoring empty fields
5271 (setq cnt 0 frac 0.0)
5272 (mapcar
5273 (lambda (x)
5274 (if (equal x "")
5275 nil
5276 (setq frac ( / (+ (* frac cnt)
5277 (if (string-match org-table-number-regexp x) 1 0))
5278 (setq cnt (1+ cnt))))))
5279 column)
5280 (push (>= frac org-table-number-fraction) typenums))
5281 (setq lengths (nreverse lengths)
5282 typenums (nreverse typenums))
5283 (setq org-table-last-alignment typenums
5284 org-table-last-column-widths lengths)
5285 ;; Compute the formats needed for output of the table
5286 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
5287 (while (setq l (pop lengths))
5288 (setq ty (if (pop typenums) "" "-")) ; number types flushright
5289 (setq rfmt (concat rfmt (format rfmt1 ty l))
5290 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
5291 (setq rfmt (concat rfmt "\n")
5292 hfmt (concat (substring hfmt 0 -1) "|\n"))
5293 ;; Produce the new table
5294 (while lines
5295 (setq l (pop lines))
5296 (if l
5297 (setq new (concat new (apply 'format rfmt
5298 (append (pop fields) emptystrings))))
5299 (setq new (concat new hfmt))))
5300 ;; Replace the old one
5301 (delete-region beg end)
5302 (move-marker end nil)
5303 (move-marker org-table-aligned-begin-marker (point))
5304 (insert new)
5305 (move-marker org-table-aligned-end-marker (point))
5306 ;; Try to move to the old location (approximately)
5307 (goto-line linepos)
5308 (set-window-start (selected-window) winstart 'noforce)
5309 (org-table-goto-column colpos)
5310 (setq org-table-may-need-update nil)
5311 (if (org-in-invisibility-spec-p '(org-table))
5312 (org-table-add-invisible-to-vertical-lines))
5313 ))
5314
5315 (defun org-table-begin (&optional table-type)
5316 "Find the beginning of the table and return its position.
5317 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
5318 (save-excursion
5319 (if (not (re-search-backward
5320 (if table-type org-table-any-border-regexp
5321 org-table-border-regexp)
5322 nil t))
5323 (error "Can't find beginning of table")
5324 (goto-char (match-beginning 0))
5325 (beginning-of-line 2)
5326 (point))))
5327
5328 (defun org-table-end (&optional table-type)
5329 "Find the end of the table and return its position.
5330 With argument TABLE-TYPE, go to the end of a table.el-type table."
5331 (save-excursion
5332 (if (not (re-search-forward
5333 (if table-type org-table-any-border-regexp
5334 org-table-border-regexp)
5335 nil t))
5336 (goto-char (point-max))
5337 (goto-char (match-beginning 0)))
5338 (point-marker)))
5339
5340 (defun org-table-justify-field-maybe ()
5341 "Justify the current field, text to left, number to right."
5342 (cond
5343 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
5344 ((org-at-table-hline-p)
5345 ;; This is pretty stupid, but I don't know how to deal with hlines
5346 (setq org-table-may-need-update t))
5347 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
5348 (current-buffer)))
5349 (< (point) org-table-aligned-begin-marker)
5350 (>= (point) org-table-aligned-end-marker))
5351 ;; This is not the same table, force a full re-align
5352 (setq org-table-may-need-update t))
5353 (t ;; realign the current field, based on previous full realign
5354 (let* ((pos (point)) s org-table-may-need-update
5355 (col (org-table-current-column))
5356 (num (nth (1- col) org-table-last-alignment))
5357 l f)
5358 (when (> col 0)
5359 (skip-chars-backward "^|\n")
5360 (if (looking-at " *\\([^|\n]*?\\) *|")
5361 (progn
5362 (setq s (match-string 1)
5363 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
5364 (setq f (format (if num " %%%ds |" " %%-%ds |") l))
5365 (replace-match (format f s t t)))
5366 (setq org-table-may-need-update t))
5367 (goto-char pos))))))
5368
5369 (defun org-table-next-field (&optional arg)
5370 "Go to the next field in the current table.
5371 Before doing so, re-align the table if necessary."
5372 (interactive "P")
5373 (if (and org-table-automatic-realign
5374 org-table-may-need-update)
5375 (org-table-align))
5376 (if (org-at-table-hline-p)
5377 (end-of-line 1))
5378 (condition-case nil
5379 (progn
5380 (re-search-forward "|" (org-table-end))
5381 (if (looking-at "[ \t]*$")
5382 (re-search-forward "|" (org-table-end)))
5383 (if (looking-at "-")
5384 (progn
5385 (beginning-of-line 0)
5386 (org-table-insert-row 'below))
5387 (if (looking-at " ") (forward-char 1))))
5388 (error
5389 (org-table-insert-row 'below))))
5390
5391 (defun org-table-previous-field (&optional arg)
5392 "Go to the previous field in the table.
5393 Before doing so, re-align the table if necessary."
5394 (interactive "P")
5395 (if (and org-table-automatic-realign
5396 org-table-may-need-update)
5397 (org-table-align))
5398 (if (org-at-table-hline-p)
5399 (end-of-line 1))
5400 (re-search-backward "|" (org-table-begin))
5401 (re-search-backward "|" (org-table-begin))
5402 (while (looking-at "|\\(-\\|[ \t]*$\\)")
5403 (re-search-backward "|" (org-table-begin)))
5404 (if (looking-at "| ?")
5405 (goto-char (match-end 0))))
5406
5407 (defun org-table-next-row (&optional arg)
5408 "Go to the next row (same column) in the current table.
5409 Before doing so, re-align the table if necessary."
5410 (interactive "P")
5411 (if (or (looking-at "[ \t]*$")
5412 (save-excursion (skip-chars-backward " \t") (bolp)))
5413 (newline)
5414 (if (and org-table-automatic-realign
5415 org-table-may-need-update)
5416 (org-table-align))
5417 (let ((col (org-table-current-column)))
5418 (beginning-of-line 2)
5419 (if (or (not (org-at-table-p))
5420 (org-at-table-hline-p))
5421 (progn
5422 (beginning-of-line 0)
5423 (org-table-insert-row 'below)))
5424 (org-table-goto-column col)
5425 (skip-chars-backward "^|\n\r")
5426 (if (looking-at " ") (forward-char 1)))))
5427
5428 (defun org-table-copy-down (n)
5429 "Copy a field down in the current column.
5430 If the field at the cursor is empty, copy into it the content of the nearest
5431 non-empty field above. With argument N, use the Nth non-empty field.
5432 If the current field is not empty, it is copied down to the next row, and
5433 the cursor is moved with it. Therefore, repeating this command causes the
5434 column to be filled row-by-row.
5435 If the variable `org-table-copy-increment' is non-nil and the field is an
5436 integer, it will be incremented while copying."
5437 (interactive "p")
5438 (let* ((colpos (org-table-current-column))
5439 (field (org-table-get-field))
5440 (non-empty (string-match "[^ \t]" field))
5441 (beg (org-table-begin))
5442 txt)
5443 (org-table-check-inside-data-field)
5444 (if non-empty (progn (org-table-next-row) (org-table-blank-field)))
5445 (if (save-excursion
5446 (setq txt
5447 (catch 'exit
5448 (while (progn (beginning-of-line 1)
5449 (re-search-backward org-table-dataline-regexp
5450 beg t))
5451 (org-table-goto-column colpos t)
5452 (if (and (looking-at
5453 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
5454 (= (setq n (1- n)) 0))
5455 (throw 'exit (match-string 1)))))))
5456 (progn
5457 (if (and org-table-copy-increment
5458 (string-match "^[0-9]+$" txt))
5459 (setq txt (format "%d" (+ (string-to-int txt) 1))))
5460 (insert txt)
5461 (org-table-align))
5462 (error "No non-empty field found"))))
5463
5464 (defun org-table-check-inside-data-field ()
5465 "Is point inside a table data field?
5466 I.e. not on a hline or before the first or after the last column?"
5467 (if (or (not (org-at-table-p))
5468 (= (org-table-current-column) 0)
5469 (org-at-table-hline-p)
5470 (looking-at "[ \t]*$"))
5471 (error "Not in table data field")))
5472
5473 (defun org-table-blank-field ()
5474 "Blank the current table field or active region."
5475 (interactive)
5476 (org-table-check-inside-data-field)
5477 (if (and (interactive-p) (org-region-active-p))
5478 (let (org-table-clip)
5479 (org-table-cut-region))
5480 (skip-chars-backward "^|")
5481 (backward-char 1)
5482 (if (looking-at "|[^|]+")
5483 (let* ((pos (match-beginning 0))
5484 (match (match-string 0))
5485 (len (length match)))
5486 (replace-match (concat "|" (make-string (1- len) ?\ )))
5487 (goto-char (+ 2 pos))
5488 (substring match 1)))))
5489
5490 (defun org-table-get-field (&optional n replace)
5491 "Return the value of the field in column N of current row.
5492 N defaults to current field.
5493 If REPLACE is a string, replace field with this value. The return value
5494 is always the old value."
5495 (and n (org-table-goto-column n))
5496 (skip-chars-backward "^|")
5497 (backward-char 1)
5498 (if (looking-at "|[^|\r\n]*")
5499 (let* ((pos (match-beginning 0))
5500 (len (length (match-string 0)))
5501 (val (buffer-substring (1+ pos) (match-end 0))))
5502 (if replace
5503 (replace-match (concat "|" replace)))
5504 (goto-char (+ 2 pos))
5505 val)))
5506
5507 (defun org-table-current-column ()
5508 "Find out which column we are in.
5509 When called interactively, column is also displayed in echo area."
5510 (interactive)
5511 (if (interactive-p) (org-table-check-inside-data-field))
5512 (save-excursion
5513 (let ((cnt 0) (pos (point)))
5514 (beginning-of-line 1)
5515 (while (search-forward "|" pos t)
5516 (setq cnt (1+ cnt)))
5517 (if (interactive-p) (message "This is table column %d" cnt))
5518 cnt)))
5519
5520 (defun org-table-goto-column (n &optional on-delim force)
5521 "Move the cursor to the Nth column in the current table line.
5522 With optional argument ON-DELIM, stop with point before the left delimiter
5523 of the field.
5524 If there are less than N fields, just go to after the last delimiter.
5525 However, when FORCE is non-nil, create new columns if necessary."
5526 (let ((pos (point-at-eol)))
5527 (beginning-of-line 1)
5528 (when (> n 0)
5529 (while (and (> (setq n (1- n)) -1)
5530 (or (search-forward "|" pos t)
5531 (and force
5532 (progn (end-of-line 1)
5533 (skip-chars-backward "^|")
5534 (insert " |")
5535 (backward-char 2) t)))))
5536 (when (and force (not (looking-at ".*|")))
5537 (save-excursion (end-of-line 1) (insert "|")))
5538 (if on-delim
5539 (backward-char 1)
5540 (if (looking-at " ") (forward-char 1))))))
5541
5542 (defun org-at-table-p (&optional table-type)
5543 "Return t if the cursor is inside an org-type table."
5544 (if org-enable-table-editor
5545 (save-excursion
5546 (beginning-of-line 1)
5547 (looking-at (if table-type org-table-any-line-regexp
5548 org-table-line-regexp)))
5549 nil))
5550
5551 (defun org-table-recognize-table.el ()
5552 "If there is a table.el table nearby, recognize it and move into it."
5553 (if org-table-tab-recognizes-table.el
5554 (if (org-at-table.el-p)
5555 (progn
5556 (beginning-of-line 1)
5557 (if (looking-at org-table-dataline-regexp)
5558 nil
5559 (if (looking-at org-table1-hline-regexp)
5560 (progn
5561 (beginning-of-line 2)
5562 (if (looking-at org-table-any-border-regexp)
5563 (beginning-of-line -1)))))
5564 (if (re-search-forward "|" (org-table-end t) t)
5565 (progn
5566 (require 'table)
5567 (if (table--at-cell-p (point))
5568 t
5569 (message "recognizing table.el table...")
5570 (table-recognize-table)
5571 (message "recognizing table.el table...done")))
5572 (error "This should not happen..."))
5573 t)
5574 nil)
5575 nil))
5576
5577 (defun org-at-table.el-p ()
5578 "Return t if the cursor is inside a table.el-type table."
5579 (save-excursion
5580 (if (org-at-table-p 'any)
5581 (progn
5582 (goto-char (org-table-begin 'any))
5583 (looking-at org-table1-hline-regexp))
5584 nil)))
5585
5586 (defun org-at-table-hline-p ()
5587 "Return t if the cursor is inside a hline in a table."
5588 (if org-enable-table-editor
5589 (save-excursion
5590 (beginning-of-line 1)
5591 (looking-at org-table-hline-regexp))
5592 nil))
5593
5594 (defun org-table-insert-column (&optional arg)
5595 "Insert a new column into the table."
5596 (interactive "P")
5597 (if (not (org-at-table-p))
5598 (error "Not at a table"))
5599 (org-table-find-dataline)
5600 (let* ((col (max 1 (org-table-current-column)))
5601 (beg (org-table-begin))
5602 (end (org-table-end))
5603 ;; Current cursor position
5604 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5605 (colpos col))
5606 (goto-char beg)
5607 (while (< (point) end)
5608 (if (org-at-table-hline-p)
5609 nil
5610 (org-table-goto-column col t)
5611 (insert "| "))
5612 (beginning-of-line 2))
5613 (move-marker end nil)
5614 (goto-line linepos)
5615 (org-table-goto-column colpos))
5616 (org-table-align))
5617
5618 (defun org-table-find-dataline ()
5619 "Find a dataline in the current table, which is needed for column commands."
5620 (if (and (org-at-table-p)
5621 (not (org-at-table-hline-p)))
5622 t
5623 (let ((col (current-column))
5624 (end (org-table-end)))
5625 (move-to-column col)
5626 (while (and (< (point) end)
5627 (or (not (= (current-column) col))
5628 (org-at-table-hline-p)))
5629 (beginning-of-line 2)
5630 (move-to-column col))
5631 (if (and (org-at-table-p)
5632 (not (org-at-table-hline-p)))
5633 t
5634 (error
5635 "Please position cursor in a data line for column operations")))))
5636
5637 (defun org-table-delete-column (&optional arg)
5638 "Delete a column into the table."
5639 (interactive "P")
5640 (if (not (org-at-table-p))
5641 (error "Not at a table"))
5642 (org-table-find-dataline)
5643 (org-table-check-inside-data-field)
5644 (let* ((col (org-table-current-column))
5645 (beg (org-table-begin))
5646 (end (org-table-end))
5647 ;; Current cursor position
5648 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5649 (colpos col))
5650 (goto-char beg)
5651 (while (< (point) end)
5652 (if (org-at-table-hline-p)
5653 nil
5654 (org-table-goto-column col t)
5655 (and (looking-at "|[^|\n]+|")
5656 (replace-match "|")))
5657 (beginning-of-line 2))
5658 (move-marker end nil)
5659 (goto-line linepos)
5660 (org-table-goto-column colpos))
5661 (org-table-align))
5662
5663 (defun org-table-move-column-right ()
5664 "Move column to the right."
5665 (interactive)
5666 (org-table-move-column nil))
5667 (defun org-table-move-column-left ()
5668 "Move column to the left."
5669 (interactive)
5670 (org-table-move-column 'left))
5671
5672 (defun org-table-move-column (&optional left)
5673 "Move the current column to the right. With arg LEFT, move to the left."
5674 (interactive "P")
5675 (if (not (org-at-table-p))
5676 (error "Not at a table"))
5677 (org-table-find-dataline)
5678 (org-table-check-inside-data-field)
5679 (let* ((col (org-table-current-column))
5680 (col1 (if left (1- col) col))
5681 (beg (org-table-begin))
5682 (end (org-table-end))
5683 ;; Current cursor position
5684 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5685 (colpos (if left (1- col) (1+ col))))
5686 (if (and left (= col 1))
5687 (error "Cannot move column further left"))
5688 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
5689 (error "Cannot move column further right"))
5690 (goto-char beg)
5691 (while (< (point) end)
5692 (if (org-at-table-hline-p)
5693 nil
5694 (org-table-goto-column col1 t)
5695 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
5696 (replace-match "|\\2|\\1|")))
5697 (beginning-of-line 2))
5698 (move-marker end nil)
5699 (goto-line linepos)
5700 (org-table-goto-column colpos))
5701 (org-table-align))
5702
5703 (defun org-table-move-row-down ()
5704 "Move table row down."
5705 (interactive)
5706 (org-table-move-row nil))
5707 (defun org-table-move-row-up ()
5708 "Move table row up."
5709 (interactive)
5710 (org-table-move-row 'up))
5711
5712 (defun org-table-move-row (&optional up)
5713 "Move the current table line down. With arg UP, move it up."
5714 (interactive "P")
5715 (let ((col (current-column))
5716 (pos (point))
5717 (tonew (if up 0 2))
5718 txt)
5719 (beginning-of-line tonew)
5720 (if (not (org-at-table-p))
5721 (progn
5722 (goto-char pos)
5723 (error "Cannot move row further.")))
5724 (goto-char pos)
5725 (beginning-of-line 1)
5726 (setq pos (point))
5727 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
5728 (delete-region (point) (1+ (point-at-eol)))
5729 (beginning-of-line tonew)
5730 (insert txt)
5731 (beginning-of-line 0)
5732 (move-to-column col)))
5733
5734 (defun org-table-insert-row (&optional arg)
5735 "Insert a new row above the current line into the table.
5736 With prefix ARG, insert below the current line."
5737 (interactive "P")
5738 (if (not (org-at-table-p))
5739 (error "Not at a table"))
5740 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
5741 (if (string-match "^[ \t]*|-" line)
5742 (setq line (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
5743 (setq line (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
5744 (beginning-of-line (if arg 2 1))
5745 (let (org-table-may-need-update)
5746 (apply 'insert-before-markers line)
5747 (insert-before-markers "\n"))
5748 (beginning-of-line 0)
5749 (re-search-forward "| ?" (point-at-eol) t)
5750 (and org-table-may-need-update (org-table-align))))
5751
5752 (defun org-table-insert-hline (&optional arg)
5753 "Insert a horizontal-line below the current line into the table.
5754 With prefix ARG, insert above the current line."
5755 (interactive "P")
5756 (if (not (org-at-table-p))
5757 (error "Not at a table"))
5758 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
5759 (col (current-column))
5760 start)
5761 (if (string-match "^[ \t]*|-" line)
5762 (setq line
5763 (mapcar (lambda (x) (if (member x '(?| ?+))
5764 (prog1 (if start ?+ ?|) (setq start t))
5765 (if start ?- ?\ )))
5766 line))
5767 (setq line
5768 (mapcar (lambda (x) (if (equal x ?|)
5769 (prog1 (if start ?+ ?|) (setq start t))
5770 (if start ?- ?\ )))
5771 line)))
5772 (beginning-of-line (if arg 1 2))
5773 (apply 'insert line)
5774 (if (equal (char-before (point)) ?+)
5775 (progn (backward-delete-char 1) (insert "|")))
5776 (insert "\n")
5777 (beginning-of-line 0)
5778 (move-to-column col)))
5779
5780 (defun org-table-kill-row (&optional arg)
5781 "Delete the current row or horizontal line from the table."
5782 (interactive "P")
5783 (if (not (org-at-table-p))
5784 (error "Not at a table"))
5785 (let ((col (current-column)))
5786 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
5787 (if (not (org-at-table-p)) (beginning-of-line 0))
5788 (move-to-column col)))
5789
5790
5791 (defun org-table-cut-region (&optional arg)
5792 "Copy region in table to the clipboard and blank all relevant fields."
5793 (interactive "P")
5794 (org-table-copy-region 'cut))
5795
5796 (defvar org-table-clip nil
5797 "Clipboard for table regions")
5798
5799 (defun org-table-copy-region (&optional cut)
5800 "Copy rectangular region in table to clipboard.
5801 A special clipboard is used which can only be accessed
5802 with `org-table-paste-rectangle'"
5803 (interactive "P")
5804 (unless (org-region-active-p) (error "No active region"))
5805 (let* ((beg (region-beginning))
5806 (end (region-end))
5807 l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
5808 region cols
5809 (rpl (if cut " " nil)))
5810 (goto-char beg)
5811 (org-table-check-inside-data-field)
5812 (setq l01 (count-lines (point-min) (point))
5813 c01 (org-table-current-column))
5814 (goto-char end)
5815 (org-table-check-inside-data-field)
5816 (setq l02 (count-lines (point-min) (point))
5817 c02 (org-table-current-column))
5818 (setq l1 (min l01 l02) l2 (max l01 l02)
5819 c1 (min c01 c02) c2 (max c01 c02))
5820 (catch 'exit
5821 (while t
5822 (catch 'nextline
5823 (if (> l1 l2) (throw 'exit t))
5824 (goto-line l1)
5825 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
5826 (setq cols nil ic1 c1 ic2 c2)
5827 (while (< ic1 (1+ ic2))
5828 (push (org-table-get-field ic1 rpl) cols)
5829 (setq ic1 (1+ ic1)))
5830 (push (nreverse cols) region)
5831 (setq l1 (1+ l1)))))
5832 (setq org-table-clip (nreverse region))
5833 (if cut (org-table-align))))
5834
5835 (defun org-table-paste-rectangle (&optional arg)
5836 "Paste a rectangular region into a table.
5837 The upper right corner ends up in the current field. All involved fields
5838 will be overwritten. If the rectangle does not fit into the present table,
5839 the table is enlarged as needed. The process ignores horizontal separator
5840 lines."
5841 (interactive "P")
5842 (unless (and org-table-clip (listp org-table-clip))
5843 (error "First cut/copy a region to paste!"))
5844 (org-table-check-inside-data-field)
5845 (let* ((clip org-table-clip)
5846 (line (count-lines (point-min) (point)))
5847 (col (org-table-current-column))
5848 (l line)
5849 (org-enable-table-editor t)
5850 (org-table-automatic-realign nil)
5851 c cols field)
5852 (while (setq cols (pop clip))
5853 (while (org-at-table-hline-p) (beginning-of-line 2))
5854 (if (not (org-at-table-p))
5855 (progn (end-of-line 0) (org-table-next-field)))
5856 (setq c col)
5857 (while (setq field (pop cols))
5858 (org-table-goto-column c nil 'force)
5859 (org-table-get-field nil field)
5860 (setq c (1+ c)))
5861 (beginning-of-line 2))
5862 (goto-line line)
5863 (org-table-goto-column col)
5864 (org-table-align)))
5865
5866 (defun org-table-convert ()
5867 "Convert from org-mode table to table.el and back.
5868 Obviously, this only works within limits. When an Org-mode table is
5869 converted to table.el, all horizontal separator lines get lost, because
5870 table.el uses these as cell boundaries and has no notion of horizontal lines.
5871 A table.el table can be converted to an Org-mode table only if it does not
5872 do row or column spanning. Multiline cells will become multiple cells.
5873 Beware, Org-mode does not test if the table can be successfully converted - it
5874 blindly applies a recipe that works for simple tables."
5875 (interactive)
5876 (require 'table)
5877 (if (org-at-table.el-p)
5878 ;; convert to Org-mode table
5879 (let ((beg (move-marker (make-marker) (org-table-begin t)))
5880 (end (move-marker (make-marker) (org-table-end t))))
5881 (table-unrecognize-region beg end)
5882 (goto-char beg)
5883 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
5884 (replace-match ""))
5885 (goto-char beg))
5886 (if (org-at-table-p)
5887 ;; convert to table.el table
5888 (let ((beg (move-marker (make-marker) (org-table-begin)))
5889 (end (move-marker (make-marker) (org-table-end))))
5890 ;; first, get rid of all horizontal lines
5891 (goto-char beg)
5892 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
5893 (replace-match ""))
5894 ;; insert a hline before first
5895 (goto-char beg)
5896 (org-table-insert-hline 'above)
5897 ;; insert a hline after each line
5898 (while (progn (beginning-of-line 2) (< (point) end))
5899 (org-table-insert-hline))
5900 (goto-char beg)
5901 (setq end (move-marker end (org-table-end)))
5902 ;; replace "+" at beginning and ending of hlines
5903 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
5904 (replace-match "\\1+-"))
5905 (goto-char beg)
5906 (while (re-search-forward "-|[ \t]*$" end t)
5907 (replace-match "-+"))
5908 (goto-char beg)))))
5909
5910 (defun org-table-wrap-region (arg)
5911 "Wrap several fields in a column like a paragraph.
5912 This is useful if you'd like to spread the contents of a field over several
5913 lines, in order to keep the table compact.
5914
5915 If there is an active region, and both point and mark are in the same column,
5916 the text in the column is wrapped to minimum width for the given number of
5917 lines. Generally, this makes the table more compact. A prefix ARG may be
5918 used to change the number of desired lines. For example, `C-2 C-c C-q'
5919 formats the selected text to two lines. If the region was longer than 2
5920 lines, the remaining lines remain empty. A negative prefix argument reduces
5921 the current number of lines by that amount. The wrapped text is pasted back
5922 into the table. If you formatted it to more lines than it was before, fields
5923 further down in the table get overwritten - so you might need to make space in
5924 the table first.
5925
5926 If there is no region, the current field is split at the cursor position and
5927 the text fragment to the right of the cursor is prepended to the field one
5928 line down.
5929
5930 If there is no region, but you specify a prefix ARG, the current field gets
5931 blank, and the content is appended to the field above."
5932 (interactive "P")
5933 (org-table-check-inside-data-field)
5934 (if (org-region-active-p)
5935 ;; There is a region: fill as a paragraph
5936 (let ((beg (region-beginning))
5937 nlines)
5938 (org-table-cut-region)
5939 (if (> (length (car org-table-clip)) 1)
5940 (error "Region must be limited to single column"))
5941 (setq nlines (if arg
5942 (if (< arg 1)
5943 (+ (length org-table-clip) arg)
5944 arg)
5945 (length org-table-clip)))
5946 (setq org-table-clip
5947 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
5948 nil nlines)))
5949 (goto-char beg)
5950 (org-table-paste-rectangle))
5951 ;; No region, split the current field at point
5952 (if arg
5953 ;; combine with field above
5954 (let ((s (org-table-blank-field))
5955 (col (org-table-current-column)))
5956 (beginning-of-line 0)
5957 (while (org-at-table-hline-p) (beginning-of-line 0))
5958 (org-table-goto-column col)
5959 (skip-chars-forward "^|")
5960 (skip-chars-backward " ")
5961 (insert " " (org-trim s))
5962 (org-table-align))
5963 ;; split field
5964 (when (looking-at "\\([^|]+\\)+|")
5965 (let ((s (match-string 1)))
5966 (replace-match " |")
5967 (goto-char (match-beginning 0))
5968 (org-table-next-row)
5969 (insert (org-trim s) " ")
5970 (org-table-align))))))
5971
5972 (defun org-trim (s)
5973 "Remove whitespace at beginning and end of string."
5974 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
5975 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s))))
5976
5977 (defun org-wrap (string &optional width lines)
5978 "Wrap string to either a number of lines, or a width in characters.
5979 If WIDTH is non-nil, the string is wrapped to that width, however many lines
5980 that costs. If there is a word longer than WIDTH, the text is actually
5981 wrapped to the length of that word.
5982 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
5983 many lines, whatever width that takes.
5984 The return value is a list of lines, without newlines at the end."
5985 (let* ((words (org-split-string string "[ \t\n]+"))
5986 (maxword (apply 'max (mapcar 'length words)))
5987 (black (apply '+ (mapcar 'length words)))
5988 (total (+ black (length words)))
5989 w ll)
5990 (cond (width
5991 (org-do-wrap words (max maxword width)))
5992 (lines
5993 (setq w maxword)
5994 (setq ll (org-do-wrap words maxword))
5995 (if (<= (length ll) lines)
5996 ll
5997 (setq ll words)
5998 (while (> (length ll) lines)
5999 (setq w (1+ w))
6000 (setq ll (org-do-wrap words w)))
6001 ll))
6002 (t (error "Cannot wrap this")))))
6003
6004
6005 (defun org-do-wrap (words width)
6006 "Creates lines of maximum width WIDTH (in characters) from word list WORDS."
6007 (let (lines line)
6008 (while words
6009 (setq line (pop words))
6010 (while (and words (< (+ (length line) (length (car words))) width))
6011 (setq line (concat line " " (pop words))))
6012 (setq lines (push line lines)))
6013 (nreverse lines)))
6014
6015 ;; FIXME: I think I can make this more efficient
6016 (defun org-split-string (string &optional separators)
6017 "Splits STRING into substrings at SEPARATORS.
6018 No empty strings are returned if there are matches at the beginning
6019 and end of string."
6020 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6021 (start 0)
6022 notfirst
6023 (list nil))
6024 (while (and (string-match rexp string
6025 (if (and notfirst
6026 (= start (match-beginning 0))
6027 (< start (length string)))
6028 (1+ start) start))
6029 (< (match-beginning 0) (length string)))
6030 (setq notfirst t)
6031 (or (eq (match-beginning 0) 0)
6032 (and (eq (match-beginning 0) (match-end 0))
6033 (eq (match-beginning 0) start))
6034 (setq list
6035 (cons (substring string start (match-beginning 0))
6036 list)))
6037 (setq start (match-end 0)))
6038 (or (eq start (length string))
6039 (setq list
6040 (cons (substring string start)
6041 list)))
6042 (nreverse list)))
6043
6044 (defun org-table-add-invisible-to-vertical-lines ()
6045 "Add an `invisible' property to vertical lines of current table."
6046 (interactive)
6047 (let* ((beg (org-table-begin))
6048 (end (org-table-end))
6049 (end1))
6050 (save-excursion
6051 (goto-char beg)
6052 (while (< (point) end)
6053 (setq end1 (point-at-eol))
6054 (if (looking-at org-table-dataline-regexp)
6055 (while (re-search-forward "|" end1 t)
6056 (add-text-properties (1- (point)) (point)
6057 '(invisible org-table)))
6058 (while (re-search-forward "[+|]" end1 t)
6059 (add-text-properties (1- (point)) (point)
6060 '(invisible org-table))))
6061 (beginning-of-line 2)))))
6062
6063 (defun org-table-toggle-vline-visibility (&optional arg)
6064 "Toggle the visibility of table vertical lines.
6065 The effect is immediate and on all tables in the file.
6066 With prefix ARG, make lines invisible when ARG is positive, make lines
6067 visible when ARG is not positive"
6068 (interactive "P")
6069 (let ((action (cond
6070 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6071 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6072 (t (if (org-in-invisibility-spec-p '(org-table))
6073 'off
6074 'on)))))
6075 (if (eq action 'off)
6076 (progn
6077 (org-remove-from-invisibility-spec '(org-table))
6078 (org-table-map-tables 'org-table-align)
6079 (message "Vertical table lines visible")
6080 (if (org-at-table-p)
6081 (org-table-align)))
6082 (org-add-to-invisibility-spec '(org-table))
6083 (org-table-map-tables 'org-table-align)
6084 (message "Vertical table lines invisible"))
6085 (redraw-frame (selected-frame))))
6086
6087 (defun org-table-map-tables (function)
6088 "Apply FUNCTION to the start of all tables in the buffer."
6089 (save-excursion
6090 (save-restriction
6091 (widen)
6092 (goto-char (point-min))
6093 (while (re-search-forward org-table-any-line-regexp nil t)
6094 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6095 (beginning-of-line 1)
6096 (if (looking-at org-table-line-regexp)
6097 (save-excursion (funcall function)))
6098 (re-search-forward org-table-any-border-regexp nil 1)))))
6099
6100 (defun org-table-sum ()
6101 "Sum numbers in region of current table column.
6102 The result will be displayed in the echo area, and will be available
6103 as kill to be inserted with \\[yank].
6104
6105 If there is an active region, it is interpreted as a rectangle and all
6106 numbers in that rectangle will be summed. If there is no active
6107 region and point is located in a table column, sum all numbers in that
6108 column.
6109
6110 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6111 numbers are assumed to be times as well (in decimal hours) and the
6112 numbers are added as such."
6113 (interactive)
6114 (save-excursion
6115 (let (beg end col (timecnt 0) diff h m s)
6116 (if (org-region-active-p)
6117 (setq beg (region-beginning) end (region-end))
6118 (setq col (org-table-current-column))
6119 (goto-char (org-table-begin))
6120 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6121 (error "No table data"))
6122 (org-table-goto-column col)
6123 (skip-chars-backward "^|")
6124 (setq beg (point))
6125 (goto-char (org-table-end))
6126 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6127 (error "No table data"))
6128 (org-table-goto-column col)
6129 (skip-chars-forward "^|")
6130 (setq end (point)))
6131 (let* ((l1 (progn (goto-char beg)
6132 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6133 (l2 (progn (goto-char end)
6134 (+ (if (bolp) 1 0) (count-lines (point-min) (point)))))
6135 (items (if (= l1 l2)
6136 (split-string (buffer-substring beg end))
6137 (split-string
6138 (mapconcat 'identity (extract-rectangle beg end) " "))))
6139 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6140 items)))
6141 (res (apply '+ numbers))
6142 (sres (if (= timecnt 0)
6143 (format "%g" res)
6144 (setq diff (* 3600 res)
6145 h (floor (/ diff 3600)) diff (mod diff 3600)
6146 m (floor (/ diff 60)) diff (mod diff 60)
6147 s diff)
6148 (format "%d:%02d:%02d" h m s))))
6149 (kill-new sres)
6150 (message (substitute-command-keys
6151 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6152 (length numbers) sres)))))))
6153
6154 (defun org-table-get-number-for-summing (s)
6155 (let (n)
6156 (if (string-match "^ *|? *" s)
6157 (setq s (replace-match "" nil nil s)))
6158 (if (string-match " *|? *$" s)
6159 (setq s (replace-match "" nil nil s)))
6160 (setq n (string-to-number s))
6161 (cond
6162 ((and (string-match "0" s)
6163 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6164 ((string-match "\\`[ \t]+\\'" s) nil)
6165 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6166 (let ((h (string-to-number (or (match-string 1 s) "0")))
6167 (m (string-to-number (or (match-string 2 s) "0")))
6168 (s (string-to-number (or (match-string 4 s) "0"))))
6169 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6170 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6171 ((equal n 0) nil)
6172 (t n))))
6173
6174 (defvar org-table-current-formula nil)
6175 (defvar org-table-formula-history nil)
6176 (defun org-table-get-formula (current)
6177 (if (and current (not (equal "" org-table-current-formula)))
6178 org-table-current-formula
6179 (setq org-table-current-formula
6180 (read-string
6181 "Formula [last]: " "" 'org-table-formula-history
6182 org-table-current-formula))))
6183
6184 (defun org-this-word ()
6185 ;; Get the current word
6186 (save-excursion
6187 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
6188 (end (progn (skip-chars-forward "^ \t\n") (point))))
6189 (buffer-substring-no-properties beg end))))
6190
6191 (defun org-table-eval-formula (&optional ndown)
6192 "Replace the table field value at the cursor by the result of a calculation.
6193
6194 This function makes use of Dave Gillespie's calc package, arguably the most
6195 exciting program ever written for GNU Emacs. So you need to have calc
6196 installed in order to use this function.
6197
6198 In a table, this command replaces the value in the current field with the
6199 result of a formula. While nowhere near the computation options of a
6200 spreadsheet program, this is still very useful. Note that there is no
6201 automatic updating of a calculated field, nor will the field remember the
6202 formula. The command needs to be applied again after changing input
6203 fields.
6204
6205 When called, the command first prompts for a formula, which is read in the
6206 minibuffer. Previously entered formulae are available through the history
6207 list, and the last used formula is the default, reachable by simply
6208 pressing RET.
6209
6210 The formula can be any algebraic expression understood by the calc package.
6211 Before evaluation, variable substitution takes place: \"$\" is replaced by
6212 the field the cursor is currently in, and $1..$n reference the fields in
6213 the current row. Values from a *different* row can *not* be referenced
6214 here, so the command supports only horizontal computing. The formula can
6215 contain an optional printf format specifier after a semicolon, to reformat
6216 the result.
6217
6218 A few examples for formulae:
6219 $1+$2 Sum of first and second field
6220 $1+$2;%.2f Same, and format result to two digits after dec.point
6221 exp($2)+exp($1) Math functions can be used
6222 $;%.1f Reformat current cell to 1 digit after dec.point
6223 ($3-32)*5/9 degrees F -> C conversion
6224
6225 When called with a raw C-u prefix, the formula is applied to the current
6226 field, and to the same same column in all following rows, until reaching a
6227 horizontal line or the end of the table. When the command is called with a
6228 numeric prefix argument (like M-3 or C-7 or C-u 24), the formula is applied
6229 to the current row, and to the following n-1 rows (but not beyond a
6230 separator line)."
6231 (interactive "P")
6232 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
6233 (require 'calc)
6234 (org-table-check-inside-data-field)
6235 (let* (fields
6236 (org-table-automatic-realign nil)
6237 (down (> ndown 1))
6238 (formula (org-table-get-formula nil))
6239 (n0 (org-table-current-column))
6240 n form fmt x ev)
6241 (if (string-match ";" formula)
6242 (let ((tmp (org-split-string formula ";")))
6243 (setq formula (car tmp) fmt (nth 1 tmp))))
6244 (while (> ndown 0)
6245 (setq fields (org-split-string
6246 (concat " " (buffer-substring
6247 (point-at-bol) (point-at-eol))) "|"))
6248 (setq ndown (1- ndown))
6249 (setq form (copy-sequence formula))
6250 (while (string-match "\\$\\([0-9]+\\)?" form)
6251 (setq n (if (match-beginning 1)
6252 (string-to-int (match-string 1 form))
6253 n0)
6254 x (nth n fields))
6255 (unless x (error "Invalid field specifier \"%s\""
6256 (match-string 0 form)))
6257 (if (equal (string-to-number x) 0) (setq x "0"))
6258 (setq form (replace-match x t t form)))
6259 (setq ev (calc-eval (list form) 'num))
6260 (if (listp ev)
6261 (error "Invalid expression: %s (%s at %d)" form (nth 1 ev) (car ev)))
6262 (org-table-blank-field)
6263 (if fmt
6264 (insert (format fmt (string-to-number ev)))
6265 (insert ev))
6266 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
6267 (call-interactively 'org-return)
6268 (setq ndown 0)))
6269 (org-table-align)))
6270
6271 ;;; The orgtbl minor mode
6272
6273 ;; Define a minor mode which can be used in other modes in order to
6274 ;; integrate the org-mode table editor.
6275
6276 ;; This is really a hack, because the org-mode table editor uses several
6277 ;; keys which normally belong to the major mode, for example the TAB and
6278 ;; RET keys. Here is how it works: The minor mode defines all the keys
6279 ;; necessary to operate the table editor, but wraps the commands into a
6280 ;; function which tests if the cursor is currently inside a table. If that
6281 ;; is the case, the table editor command is executed. However, when any of
6282 ;; those keys is used outside a table, the function uses `key-binding' to
6283 ;; look up if the key has an associated command in another currently active
6284 ;; keymap (minor modes, major mode, global), and executes that command.
6285 ;; There might be problems if any of the keys used by the table editor is
6286 ;; otherwise used as a prefix key.
6287
6288 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6289 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6290 ;; addresses this by checking explicitly for both bindings.
6291
6292 ;; The optimized version (see variable `orgtbl-optimized') takes over
6293 ;; all keys which are bound to `self-insert-command' in the *global map*.
6294 ;; Some modes bind other commands to simple characters, for example
6295 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
6296 ;; active, this binding is ignored inside tables and replaced with a
6297 ;; modified self-insert.
6298
6299 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
6300 "Non-nil means, use the optimized table editor version for orgtbl-mode.
6301 In the optimized version, the table editor takes over all simple keys that
6302 normally just insert a character. In tables, the characters are inserted
6303 in a way to minimize disturbing the table structure (i.e. in overwrite mode
6304 for empty fields). Outside tables, the correct binding of the keys is
6305 restored.
6306
6307 The default for this option is t if the optimized version is also used in
6308 Org-mode. See the variable `org-enable-table-editor' for details. Changing
6309 this variable requires a restart of Emacs to become effective."
6310 :group 'org-table
6311 :type 'boolean)
6312
6313 (defvar orgtbl-mode nil
6314 "Variable controlling orgtbl-mode, a minor mode enabling the org-mode
6315 table editor in arbitrary modes.")
6316 (make-variable-buffer-local 'orgtbl-mode)
6317
6318 (defvar orgtbl-mode-map (make-sparse-keymap)
6319 "Keymap for orgtbl-mode.")
6320
6321 ;;;###autoload
6322 (defun turn-on-orgtbl ()
6323 "Unconditionally turn on orgtbl-mode."
6324 (orgtbl-mode 1))
6325
6326 ;;;###autoload
6327 (defun orgtbl-mode (&optional arg)
6328 "The org-mode table editor as a minor mode for use in other modes."
6329 (interactive)
6330 (setq orgtbl-mode
6331 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
6332 (if orgtbl-mode
6333 (progn
6334 (set (make-local-variable (quote org-table-may-need-update)) t)
6335 (make-local-hook (quote before-change-functions))
6336 (add-hook 'before-change-functions 'org-before-change-function
6337 nil 'local)
6338 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
6339 auto-fill-inhibit-regexp)
6340 (set (make-local-variable 'auto-fill-inhibit-regexp)
6341 (if auto-fill-inhibit-regexp
6342 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
6343 "[ \t]*|"))
6344 (easy-menu-add orgtbl-mode-menu)
6345 (run-hooks (quote orgtbl-mode-hook)))
6346 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
6347 (remove-hook 'before-change-functions 'org-before-change-function t)
6348 (easy-menu-remove orgtbl-mode-menu)
6349 (force-mode-line-update 'all)))
6350
6351 ;; Install it as a minor mode.
6352 (put 'orgtbl-mode :included t)
6353 (put 'orgtbl-mode :menu-tag "Org Table Mode")
6354 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
6355
6356 (defun orgtbl-make-binding (fun &rest keys)
6357 "Create a function for binding in the table minor mode."
6358 (list 'lambda '(arg) '(interactive "p")
6359 (list 'if
6360 '(org-at-table-p)
6361 (list 'call-interactively (list 'quote fun))
6362 (list 'let '(orgtbl-mode)
6363 (list 'call-interactively
6364 (append '(or)
6365 (mapcar (lambda (k)
6366 (list 'key-binding k))
6367 keys)
6368 '('orgtbl-error)))))))
6369
6370 (defun orgtbl-error ()
6371 "Error when there is no default binding for a table key."
6372 (interactive)
6373 (error "This key is has no function outside tables"))
6374
6375 ;; Keybindings for the minor mode
6376 (let ((bindings
6377 '(([(meta shift left)] org-table-delete-column)
6378 ([(meta left)] org-table-move-column-left)
6379 ([(meta right)] org-table-move-column-right)
6380 ([(meta shift right)] org-table-insert-column)
6381 ([(meta shift up)] org-table-kill-row)
6382 ([(meta shift down)] org-table-insert-row)
6383 ([(meta up)] org-table-move-row-up)
6384 ([(meta down)] org-table-move-row-down)
6385 ("\C-c\C-w" org-table-cut-region)
6386 ("\C-c\M-w" org-table-copy-region)
6387 ("\C-c\C-y" org-table-paste-rectangle)
6388 ("\C-c-" org-table-insert-hline)
6389 ([(shift tab)] org-table-previous-field)
6390 ("\C-c\C-c" org-table-align)
6391 ([(return)] org-table-next-row)
6392 ([(shift return)] org-table-copy-down)
6393 ([(meta return)] org-table-wrap-region)
6394 ("\C-c\C-q" org-table-wrap-region)
6395 ("\C-c?" org-table-current-column)
6396 ("\C-c " org-table-blank-field)
6397 ("\C-c+" org-table-sum)
6398 ("\C-c|" org-table-toggle-vline-visibility)
6399 ("\C-c=" org-table-eval-formula)))
6400 elt key fun cmd)
6401 (while (setq elt (pop bindings))
6402 (setq key (car elt)
6403 fun (nth 1 elt)
6404 cmd (orgtbl-make-binding fun key))
6405 (define-key orgtbl-mode-map key cmd)))
6406
6407 ;; Special treatment needed for TAB and RET
6408 ;(define-key orgtbl-mode-map [(return)]
6409 ; (orgtbl-make-binding 'org-table-next-row [(return)] "\C-m"))
6410 ;(define-key orgtbl-mode-map "\C-m"
6411 ; (orgtbl-make-binding 'org-table-next-row "\C-m" [(return)]))
6412 ;(define-key orgtbl-mode-map [(tab)]
6413 ; (orgtbl-make-binding 'org-table-next-field [(tab)] "\C-i"))
6414 ;(define-key orgtbl-mode-map "\C-i"
6415 ; (orgtbl-make-binding 'org-table-next-field "\C-i" [(tab)]))
6416
6417 (define-key orgtbl-mode-map [(return)]
6418 (orgtbl-make-binding 'orgtbl-ret [(return)] "\C-m"))
6419 (define-key orgtbl-mode-map "\C-m"
6420 (orgtbl-make-binding 'orgtbl-ret "\C-m" [(return)]))
6421 (define-key orgtbl-mode-map [(tab)]
6422 (orgtbl-make-binding 'orgtbl-tab [(tab)] "\C-i"))
6423 (define-key orgtbl-mode-map "\C-i"
6424 (orgtbl-make-binding 'orgtbl-tab "\C-i" [(tab)]))
6425
6426 (when orgtbl-optimized
6427 ;; If the user wants maximum table support, we need to hijack
6428 ;; some standard editing functions
6429 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
6430 orgtbl-mode-map global-map)
6431 (substitute-key-definition 'delete-char 'orgtbl-delete-char
6432 orgtbl-mode-map global-map)
6433 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
6434 orgtbl-mode-map global-map)
6435 (define-key org-mode-map "|" 'self-insert-command))
6436
6437 (defun orgtbl-tab ()
6438 "Justification and field motion for orgtbl-mode."
6439 (interactive)
6440 (org-table-justify-field-maybe)
6441 (org-table-next-field))
6442
6443 (defun orgtbl-ret ()
6444 "Justification and field motion for orgtbl-mode."
6445 (interactive)
6446 (org-table-justify-field-maybe)
6447 (org-table-next-row))
6448
6449 (defun orgtbl-self-insert-command (N)
6450 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
6451 If the cursor is in a table looking at whitespace, the whitespace is
6452 overwritten, and the table is not marked as requiring realignment."
6453 (interactive "p")
6454 (if (and (org-at-table-p)
6455 (eq N 1)
6456 (looking-at "[^|\n]* +|"))
6457 (let (org-table-may-need-update (pos (point)))
6458 (goto-char (1- (match-end 0)))
6459 (delete-backward-char 1)
6460 (goto-char (match-beginning 0))
6461 (self-insert-command N))
6462 (setq org-table-may-need-update t)
6463 (let (orgtbl-mode)
6464 (call-interactively (key-binding (vector last-input-event))))))
6465
6466 (defun orgtbl-delete-backward-char (N)
6467 "Like `delete-backward-char', insert whitespace at field end in tables.
6468 When deleting backwards, in tables this function will insert whitespace in
6469 front of the next \"|\" separator, to keep the table aligned. The table will
6470 still be marked for re-alignment, because a narrow field may lead to a
6471 reduced column width."
6472 (interactive "p")
6473 (if (and (org-at-table-p)
6474 (eq N 1)
6475 (looking-at ".*?|"))
6476 (let ((pos (point)))
6477 (backward-delete-char N)
6478 (skip-chars-forward "^|")
6479 (insert " ")
6480 (goto-char (1- pos)))
6481 (message "%s" last-input-event) (sit-for 1)
6482 (delete-backward-char N)))
6483
6484 (defun orgtbl-delete-char (N)
6485 "Like `delete-char', but insert whitespace at field end in tables.
6486 When deleting characters, in tables this function will insert whitespace in
6487 front of the next \"|\" separator, to keep the table aligned. The table
6488 will still be marked for re-alignment, because a narrow field may lead to
6489 a reduced column width."
6490 (interactive "p")
6491 (if (and (org-at-table-p)
6492 (eq N 1))
6493 (if (looking-at ".*?|")
6494 (let ((pos (point)))
6495 (replace-match (concat
6496 (substring (match-string 0) 1 -1)
6497 " |"))
6498 (goto-char pos)))
6499 (delete-char N)))
6500
6501 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
6502 '("Tbl"
6503 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
6504 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
6505 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
6506 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
6507 "--"
6508 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
6509 ["Copy Field from Above"
6510 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
6511 "--"
6512 ("Column"
6513 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
6514 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
6515 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
6516 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
6517 ("Row"
6518 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
6519 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
6520 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
6521 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
6522 "--"
6523 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
6524 ("Rectangle"
6525 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
6526 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
6527 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
6528 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
6529 "--"
6530 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
6531 ["Sum Column/Rectangle" org-table-sum
6532 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
6533 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
6534 ))
6535
6536 ;;; Exporting
6537
6538 (defconst org-level-max 20)
6539
6540 (defun org-export-find-first-heading-line (list)
6541 "Remove all lines from LIST which are before the first headline."
6542 (let ((orig-list list)
6543 (re (concat "^" outline-regexp)))
6544 (while (and list
6545 (not (string-match re (car list))))
6546 (pop list))
6547 (or list orig-list)))
6548
6549 (defun org-skip-comments (lines)
6550 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
6551 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
6552 (re2 "^\\(\\*+\\)[ \t\n\r]")
6553 rtn line level)
6554 (while (setq line (pop lines))
6555 (cond
6556 ((and (string-match re1 line)
6557 (setq level (- (match-end 1) (match-beginning 1))))
6558 ;; Beginning of a COMMENT subtree. Skip it.
6559 (while (and (setq line (pop lines))
6560 (or (not (string-match re2 line))
6561 (> (- (match-end 1) (match-beginning 1)) level))))
6562 (setq lines (cons line lines)))
6563 ((string-match "^#" line)
6564 ;; an ordinary comment line
6565 )
6566 (t (setq rtn (cons line rtn)))))
6567 (nreverse rtn)))
6568
6569 ;; ASCII
6570
6571 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
6572 "Characters for underlining headings in ASCII export.")
6573
6574 (defconst org-html-entities
6575 '(("nbsp")
6576 ("iexcl")
6577 ("cent")
6578 ("pound")
6579 ("curren")
6580 ("yen")
6581 ("brvbar")
6582 ("sect")
6583 ("uml")
6584 ("copy")
6585 ("ordf")
6586 ("laquo")
6587 ("not")
6588 ("shy")
6589 ("reg")
6590 ("macr")
6591 ("deg")
6592 ("plusmn")
6593 ("sup2")
6594 ("sup3")
6595 ("acute")
6596 ("micro")
6597 ("para")
6598 ("middot")
6599 ("odot"."o")
6600 ("star"."*")
6601 ("cedil")
6602 ("sup1")
6603 ("ordm")
6604 ("raquo")
6605 ("frac14")
6606 ("frac12")
6607 ("frac34")
6608 ("iquest")
6609 ("Agrave")
6610 ("Aacute")
6611 ("Acirc")
6612 ("Atilde")
6613 ("Auml")
6614 ("Aring") ("AA"."&Aring;")
6615 ("AElig")
6616 ("Ccedil")
6617 ("Egrave")
6618 ("Eacute")
6619 ("Ecirc")
6620 ("Euml")
6621 ("Igrave")
6622 ("Iacute")
6623 ("Icirc")
6624 ("Iuml")
6625 ("ETH")
6626 ("Ntilde")
6627 ("Ograve")
6628 ("Oacute")
6629 ("Ocirc")
6630 ("Otilde")
6631 ("Ouml")
6632 ("times")
6633 ("Oslash")
6634 ("Ugrave")
6635 ("Uacute")
6636 ("Ucirc")
6637 ("Uuml")
6638 ("Yacute")
6639 ("THORN")
6640 ("szlig")
6641 ("agrave")
6642 ("aacute")
6643 ("acirc")
6644 ("atilde")
6645 ("auml")
6646 ("aring")
6647 ("aelig")
6648 ("ccedil")
6649 ("egrave")
6650 ("eacute")
6651 ("ecirc")
6652 ("euml")
6653 ("igrave")
6654 ("iacute")
6655 ("icirc")
6656 ("iuml")
6657 ("eth")
6658 ("ntilde")
6659 ("ograve")
6660 ("oacute")
6661 ("ocirc")
6662 ("otilde")
6663 ("ouml")
6664 ("divide")
6665 ("oslash")
6666 ("ugrave")
6667 ("uacute")
6668 ("ucirc")
6669 ("uuml")
6670 ("yacute")
6671 ("thorn")
6672 ("yuml")
6673 ("fnof")
6674 ("Alpha")
6675 ("Beta")
6676 ("Gamma")
6677 ("Delta")
6678 ("Epsilon")
6679 ("Zeta")
6680 ("Eta")
6681 ("Theta")
6682 ("Iota")
6683 ("Kappa")
6684 ("Lambda")
6685 ("Mu")
6686 ("Nu")
6687 ("Xi")
6688 ("Omicron")
6689 ("Pi")
6690 ("Rho")
6691 ("Sigma")
6692 ("Tau")
6693 ("Upsilon")
6694 ("Phi")
6695 ("Chi")
6696 ("Psi")
6697 ("Omega")
6698 ("alpha")
6699 ("beta")
6700 ("gamma")
6701 ("delta")
6702 ("epsilon")
6703 ("varepsilon"."&epsilon;")
6704 ("zeta")
6705 ("eta")
6706 ("theta")
6707 ("iota")
6708 ("kappa")
6709 ("lambda")
6710 ("mu")
6711 ("nu")
6712 ("xi")
6713 ("omicron")
6714 ("pi")
6715 ("rho")
6716 ("sigmaf") ("varsigma"."&sigmaf;")
6717 ("sigma")
6718 ("tau")
6719 ("upsilon")
6720 ("phi")
6721 ("chi")
6722 ("psi")
6723 ("omega")
6724 ("thetasym") ("vartheta"."&thetasym;")
6725 ("upsih")
6726 ("piv")
6727 ("bull") ("bullet"."&bull;")
6728 ("hellip") ("dots"."&hellip;")
6729 ("prime")
6730 ("Prime")
6731 ("oline")
6732 ("frasl")
6733 ("weierp")
6734 ("image")
6735 ("real")
6736 ("trade")
6737 ("alefsym")
6738 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
6739 ("uarr") ("uparrow"."&uarr;")
6740 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
6741 ("darr")("downarrow"."&darr;")
6742 ("harr") ("leftrightarrow"."&harr;")
6743 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
6744 ("lArr") ("Leftarrow"."&lArr;")
6745 ("uArr") ("Uparrow"."&uArr;")
6746 ("rArr") ("Rightarrow"."&rArr;")
6747 ("dArr") ("Downarrow"."&dArr;")
6748 ("hArr") ("Leftrightarrow"."&hArr;")
6749 ("forall")
6750 ("part") ("partial"."&part;")
6751 ("exist") ("exists"."&exist;")
6752 ("empty") ("emptyset"."&empty;")
6753 ("nabla")
6754 ("isin") ("in"."&isin;")
6755 ("notin")
6756 ("ni")
6757 ("prod")
6758 ("sum")
6759 ("minus")
6760 ("lowast") ("ast"."&lowast;")
6761 ("radic")
6762 ("prop") ("proptp"."&prop;")
6763 ("infin") ("infty"."&infin;")
6764 ("ang") ("angle"."&ang;")
6765 ("and") ("vee"."&and;")
6766 ("or") ("wedge"."&or;")
6767 ("cap")
6768 ("cup")
6769 ("int")
6770 ("there4")
6771 ("sim")
6772 ("cong") ("simeq"."&cong;")
6773 ("asymp")("approx"."&asymp;")
6774 ("ne") ("neq"."&ne;")
6775 ("equiv")
6776 ("le")
6777 ("ge")
6778 ("sub") ("subset"."&sub;")
6779 ("sup") ("supset"."&sup;")
6780 ("nsub")
6781 ("sube")
6782 ("supe")
6783 ("oplus")
6784 ("otimes")
6785 ("perp")
6786 ("sdot") ("cdot"."&sdot;")
6787 ("lceil")
6788 ("rceil")
6789 ("lfloor")
6790 ("rfloor")
6791 ("lang")
6792 ("rang")
6793 ("loz") ("Diamond"."&loz;")
6794 ("spades") ("spadesuit"."&spades;")
6795 ("clubs") ("clubsuit"."&clubs;")
6796 ("hearts") ("diamondsuit"."&hearts;")
6797 ("diams") ("diamondsuit"."&diams;")
6798 ("quot")
6799 ("amp")
6800 ("lt")
6801 ("gt")
6802 ("OElig")
6803 ("oelig")
6804 ("Scaron")
6805 ("scaron")
6806 ("Yuml")
6807 ("circ")
6808 ("tilde")
6809 ("ensp")
6810 ("emsp")
6811 ("thinsp")
6812 ("zwnj")
6813 ("zwj")
6814 ("lrm")
6815 ("rlm")
6816 ("ndash")
6817 ("mdash")
6818 ("lsquo")
6819 ("rsquo")
6820 ("sbquo")
6821 ("ldquo")
6822 ("rdquo")
6823 ("bdquo")
6824 ("dagger")
6825 ("Dagger")
6826 ("permil")
6827 ("lsaquo")
6828 ("rsaquo")
6829 ("euro")
6830
6831 ("arccos"."arccos")
6832 ("arcsin"."arcsin")
6833 ("arctan"."arctan")
6834 ("arg"."arg")
6835 ("cos"."cos")
6836 ("cosh"."cosh")
6837 ("cot"."cot")
6838 ("coth"."coth")
6839 ("csc"."csc")
6840 ("deg"."deg")
6841 ("det"."det")
6842 ("dim"."dim")
6843 ("exp"."exp")
6844 ("gcd"."gcd")
6845 ("hom"."hom")
6846 ("inf"."inf")
6847 ("ker"."ker")
6848 ("lg"."lg")
6849 ("lim"."lim")
6850 ("liminf"."liminf")
6851 ("limsup"."limsup")
6852 ("ln"."ln")
6853 ("log"."log")
6854 ("max"."max")
6855 ("min"."min")
6856 ("Pr"."Pr")
6857 ("sec"."sec")
6858 ("sin"."sin")
6859 ("sinh"."sinh")
6860 ("sup"."sup")
6861 ("tan"."tan")
6862 ("tanh"."tanh")
6863 )
6864 "Entities for TeX->HTML translation.
6865 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
6866 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
6867 In that case, \"\\ent\" will be translated to \"&other;\".
6868 The list contains HTML entities for Latin-1, Greek and other symbols.
6869 It is supplemented by a number of commonly used TeX macros with appropriate
6870 translations.")
6871
6872 (defun org-export-as-ascii (arg)
6873 "Export the outline as a pretty ASCII file.
6874 If there is an active region, export only the region.
6875 The prefix ARG specifies how many levels of the outline should become
6876 underlined headlines. The default is 3."
6877 (interactive "P")
6878 (setq-default org-todo-line-regexp org-todo-line-regexp)
6879 (let* ((region
6880 (buffer-substring
6881 (if (org-region-active-p) (region-beginning) (point-min))
6882 (if (org-region-active-p) (region-end) (point-max))))
6883 (lines (org-export-find-first-heading-line
6884 (org-skip-comments (org-split-string region "[\r\n]"))))
6885 (org-startup-with-deadline-check nil)
6886 (level 0) line txt
6887 (umax nil)
6888 (case-fold-search nil)
6889 (filename (concat (file-name-sans-extension (buffer-file-name))
6890 ".txt"))
6891 (buffer (find-file-noselect filename))
6892 (levels-open (make-vector org-level-max nil))
6893 (date (format-time-string "%Y/%m/%d" (current-time)))
6894 (time (format-time-string "%X" (current-time)))
6895 (author user-full-name)
6896 (title (buffer-name))
6897 (options nil)
6898 (email user-mail-address)
6899 (language org-export-default-language)
6900 (text nil)
6901 (last-level 1)
6902 (todo nil)
6903 (lang-words nil))
6904
6905 (org-init-section-numbers)
6906
6907 (find-file-noselect filename)
6908
6909 ;; Search for the export key lines
6910 (org-parse-key-lines)
6911
6912 (setq lang-words (or (assoc language org-export-language-setup)
6913 (assoc "en" org-export-language-setup)))
6914 (if org-export-ascii-show-new-buffer
6915 (switch-to-buffer-other-window buffer)
6916 (set-buffer buffer))
6917 (erase-buffer)
6918 (fundamental-mode)
6919 (if options (org-parse-export-options options))
6920 (setq umax (if arg (prefix-numeric-value arg)
6921 org-export-headline-levels))
6922
6923 ;; File header
6924 (if title (org-insert-centered title ?=))
6925 (insert "\n")
6926 (if (or author email)
6927 (insert (concat (nth 1 lang-words) ": " (or author "")
6928 (if email (concat " <" email ">") "")
6929 "\n")))
6930 (if (and date time)
6931 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
6932 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
6933
6934 (insert "\n\n")
6935
6936 (if org-export-with-toc
6937 (progn
6938 (insert (nth 3 lang-words) "\n"
6939 (make-string (length (nth 3 lang-words)) ?=) "\n")
6940 (mapcar '(lambda (line)
6941 (if (string-match org-todo-line-regexp
6942 line)
6943 ;; This is a headline
6944 (progn
6945 (setq level (- (match-end 1) (match-beginning 1))
6946 txt (match-string 3 line)
6947 todo
6948 (or (and (match-beginning 2)
6949 (not (equal (match-string 2 line)
6950 org-done-string)))
6951 ; TODO, not DONE
6952 (and (= level umax)
6953 (org-search-todo-below
6954 line lines level))))
6955 (setq txt (org-html-expand-for-ascii txt))
6956
6957 (if org-export-with-section-numbers
6958 (setq txt (concat (org-section-number level)
6959 " " txt)))
6960 (if (<= level umax)
6961 (progn
6962 (insert
6963 (make-string (* (1- level) 4) ?\ )
6964 (format (if todo "%s (*)\n" "%s\n") txt))
6965 (setq last-level level))
6966 ))))
6967 lines)))
6968
6969 (org-init-section-numbers)
6970 (while (setq line (pop lines))
6971 ;; Remove the quoted HTML tags.
6972 (setq line (org-html-expand-for-ascii line))
6973 (cond
6974 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
6975 ;; a Headline
6976 (setq level (- (match-end 1) (match-beginning 1))
6977 txt (match-string 2 line))
6978 (org-ascii-level-start level txt umax))
6979 (t (insert line "\n"))))
6980 (normal-mode)
6981 (save-buffer)
6982 (goto-char (point-min))))
6983
6984 (defun org-search-todo-below (line lines level)
6985 "Search the subtree below LINE for any TODO entries."
6986 (let ((rest (cdr (memq line lines)))
6987 (re org-todo-line-regexp)
6988 line lv todo)
6989 (catch 'exit
6990 (while (setq line (pop rest))
6991 (if (string-match re line)
6992 (progn
6993 (setq lv (- (match-end 1) (match-beginning 1))
6994 todo (and (match-beginning 2)
6995 (not (equal (match-string 2 line)
6996 org-done-string))))
6997 ; TODO, not DONE
6998 (if (<= lv level) (throw 'exit nil))
6999 (if todo (throw 'exit t))))))))
7000
7001 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
7002 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
7003 (defun org-html-expand-for-ascii (line)
7004 "Handle quoted HTML for ASCII export."
7005 (if org-export-html-expand
7006 (while (string-match "@<[^<>\n]*>" line)
7007 ;; We just remove the tags for now.
7008 (setq line (replace-match "" nil nil line))))
7009 line)
7010
7011 (defun org-insert-centered (s &optional underline)
7012 "Insert the string S centered and underline it with character UNDERLINE."
7013 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
7014 (insert (make-string ind ?\ ) s "\n")
7015 (if underline
7016 (insert (make-string ind ?\ )
7017 (make-string (length s) underline)
7018 "\n"))))
7019
7020 (defun org-ascii-level-start (level title umax)
7021 "Insert a new level in ASCII export."
7022 (let (char)
7023 (if (> level umax)
7024 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
7025 (if (or (not (equal (char-before) ?\n))
7026 (not (equal (char-before (1- (point))) ?\n)))
7027 (insert "\n"))
7028 (setq char (nth (- umax level) (reverse org-ascii-underline)))
7029 (if org-export-with-section-numbers
7030 (setq title (concat (org-section-number level) " " title)))
7031 (insert title "\n" (make-string (string-width title) char) "\n"))))
7032
7033 (defun org-export-copy-visible (&optional arg)
7034 "Copy the visible part of the buffer to another buffer, for printing.
7035 Also removes the first line of the buffer if it specifies a mode,
7036 and all options lines."
7037 (interactive "P")
7038 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
7039 ".txt"))
7040 (buffer (find-file-noselect filename))
7041 (ore (concat
7042 (org-make-options-regexp
7043 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "STARTUP"
7044 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
7045 (if org-noutline-p "\\(\n\\|$\\)" "")))
7046 s e)
7047 (save-excursion
7048 (set-buffer buffer)
7049 (erase-buffer)
7050 (text-mode))
7051 (save-excursion
7052 (setq s (goto-char (point-min)))
7053 (while (not (= (point) (point-max)))
7054 (goto-char (org-find-invisible))
7055 (append-to-buffer buffer s (point))
7056 (setq s (goto-char (org-find-visible)))))
7057 (switch-to-buffer-other-window buffer)
7058 (newline)
7059 (goto-char (point-min))
7060 (if (looking-at ".*-\\*- mode:.*\n")
7061 (replace-match ""))
7062 (while (re-search-forward ore nil t)
7063 (replace-match ""))
7064 (goto-char (point-min))))
7065
7066 (defun org-find-visible ()
7067 (if (featurep 'noutline)
7068 (let ((s (point)))
7069 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7070 (get-char-property s 'invisible)))
7071 s)
7072 (skip-chars-forward "^\n")
7073 (point)))
7074 (defun org-find-invisible ()
7075 (if (featurep 'noutline)
7076 (let ((s (point)))
7077 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
7078 (not (get-char-property s 'invisible))))
7079 s)
7080 (skip-chars-forward "^\r")
7081 (point)))
7082
7083 ;; HTML
7084
7085 (defun org-get-current-options ()
7086 "Return a string with current options as keyword options.
7087 Does include HTML export options as well as TODO and CATEGORY stuff."
7088 (format
7089 "#+TITLE: %s
7090 #+AUTHOR: %s
7091 #+EMAIL: %s
7092 #+LANGUAGE: %s
7093 #+TEXT: Some descriptive text to be emitted. Several lines OK.
7094 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
7095 #+CATEGORY: %s
7096 #+SEQ_TODO: %s
7097 #+TYP_TODO: %s
7098 #+STARTUP: %s %s
7099 "
7100 (buffer-name) (user-full-name) user-mail-address org-export-default-language
7101 org-export-headline-levels
7102 org-export-with-section-numbers
7103 org-export-with-toc
7104 org-export-preserve-breaks
7105 org-export-html-expand
7106 org-export-with-fixed-width
7107 org-export-with-tables
7108 org-export-with-sub-superscripts
7109 org-export-with-emphasize
7110 org-export-with-TeX-macros
7111 (file-name-nondirectory (buffer-file-name))
7112 (if (equal org-todo-interpretation 'sequence)
7113 (mapconcat 'identity org-todo-keywords " ")
7114 "TODO FEEDBACK VERIFY DONE")
7115 (if (equal org-todo-interpretation 'type)
7116 (mapconcat 'identity org-todo-keywords " ")
7117 "Me Jason Marie DONE")
7118 (cdr (assoc org-startup-folded
7119 '((nil . "nofold")(t . "fold")(content . "content"))))
7120 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
7121 ))
7122
7123 (defun org-insert-export-options-template ()
7124 "Insert into the buffer a template with information for exporting."
7125 (interactive)
7126 (if (not (bolp)) (newline))
7127 (let ((s (org-get-current-options)))
7128 (and (string-match "#\\+CATEGORY" s)
7129 (setq s (substring s 0 (match-beginning 0))))
7130 (insert s)))
7131
7132 (defun org-toggle-fixed-width-section (arg)
7133 "Toggle the fixed-width indicator at the beginning of lines in the region.
7134 If there is no active region, only acts on the current line.
7135 If the first non-white character in the first line of the region is a
7136 vertical bar \"|\", then the command removes the bar from all lines in
7137 the region. If the first character is not a bar, the command adds a
7138 bar to all lines, in the column given by the beginning of the region.
7139
7140 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
7141 (interactive "P")
7142 (let* ((cc 0)
7143 (regionp (org-region-active-p))
7144 (beg (if regionp (region-beginning) (point)))
7145 (end (if regionp (region-end)))
7146 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
7147 (re "[ \t]*\\(:\\)")
7148 off)
7149 (save-excursion
7150 (goto-char beg)
7151 (setq cc (current-column))
7152 (beginning-of-line 1)
7153 (setq off (looking-at re))
7154 (while (> nlines 0)
7155 (setq nlines (1- nlines))
7156 (beginning-of-line 1)
7157 (cond
7158 (arg
7159 (move-to-column cc t)
7160 (insert ":\n")
7161 (forward-line -1))
7162 ((and off (looking-at re))
7163 (replace-match "" t t nil 1))
7164 ((not off) (move-to-column cc t) (insert ":")))
7165 (forward-line 1)))))
7166
7167 (defun org-export-as-html-and-open (arg)
7168 "Export the outline as HTML and immediately open it with a browser.
7169 If there is an active region, export only the region.
7170 The prefix ARG specifies how many levels of the outline should become
7171 headlines. The default is 3. Lower levels will become bulleted lists."
7172 (interactive "P")
7173 (org-export-as-html arg 'hidden)
7174 (org-open-file (buffer-file-name)))
7175
7176 (defun org-export-as-html-batch ()
7177 "Call org-export-as-html, may be used in batch processing as
7178 emacs --batch
7179 --load=$HOME/lib/emacs/org.el
7180 --eval \"(setq org-export-headline-levels 2)\"
7181 --visit=MyFile --funcall org-export-as-html-batch"
7182 (org-export-as-html org-export-headline-levels 'hidden))
7183
7184 (defun org-export-as-html (arg &optional hidden)
7185 "Export the outline as a pretty HTML file.
7186 If there is an active region, export only the region.
7187 The prefix ARG specifies how many levels of the outline should become
7188 headlines. The default is 3. Lower levels will become bulleted lists."
7189 (interactive "P")
7190 (setq-default org-todo-line-regexp org-todo-line-regexp)
7191 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
7192 (setq-default org-done-string org-done-string)
7193 (let* ((region-p (org-region-active-p))
7194 (region
7195 (buffer-substring
7196 (if region-p (region-beginning) (point-min))
7197 (if region-p (region-end) (point-max))))
7198 (all_lines
7199 (org-skip-comments (org-split-string region "[\r\n]")))
7200 (lines (org-export-find-first-heading-line all_lines))
7201 (level 0) (line "") (origline "") txt todo
7202 (last-level 1)
7203 (umax nil)
7204 (filename (concat (file-name-sans-extension (buffer-file-name))
7205 ".html"))
7206 (buffer (find-file-noselect filename))
7207 (levels-open (make-vector org-level-max nil))
7208 (date (format-time-string "%Y/%m/%d" (current-time)))
7209 (time (format-time-string "%X" (current-time)))
7210 (author user-full-name)
7211 (title (buffer-name))
7212 (options nil)
7213 (email user-mail-address)
7214 (language org-export-default-language)
7215 (text nil)
7216 (lang-words nil)
7217 (head-count 0) cnt
7218 table-open type
7219 table-buffer table-orig-buffer
7220 )
7221 (message "Exporting...")
7222
7223 (org-init-section-numbers)
7224
7225 ;; Search for the export key lines
7226 (org-parse-key-lines)
7227 (setq lang-words (or (assoc language org-export-language-setup)
7228 (assoc "en" org-export-language-setup)))
7229
7230 ;; Switch to the output buffer
7231 (if (or hidden (not org-export-html-show-new-buffer))
7232 (set-buffer buffer)
7233 (switch-to-buffer-other-window buffer))
7234 (erase-buffer)
7235 (fundamental-mode)
7236 (let ((case-fold-search nil))
7237 (if options (org-parse-export-options options))
7238 (setq umax (if arg (prefix-numeric-value arg)
7239 org-export-headline-levels))
7240
7241 ;; File header
7242 (insert (format
7243 "<html lang=\"%s\"><head>
7244 <title>%s</title>
7245 <meta http-equiv=\"Content-Type\" content=\"text/html\">
7246 <meta name=generator content=\"Org-mode\">
7247 <meta name=generated content=\"%s %s\">
7248 <meta name=author content=\"%s\">
7249 </head><body>
7250 "
7251 language (org-html-expand title) date time author))
7252 (if title (insert (concat "<H1 align=\"center\">"
7253 (org-html-expand title) "</H1>\n")))
7254 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
7255 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
7256 email "&gt;</a>\n")))
7257 (if (or author email) (insert "<br>\n"))
7258 (if (and date time) (insert (concat (nth 2 lang-words) ": "
7259 date " " time "<br>\n")))
7260 (if text (insert (concat "<p>\n" (org-html-expand text))))
7261 (if org-export-with-toc
7262 (progn
7263 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
7264 (insert "<ul>\n")
7265 (mapcar '(lambda (line)
7266 (if (string-match org-todo-line-regexp line)
7267 ;; This is a headline
7268 (progn
7269 (setq level (- (match-end 1) (match-beginning 1))
7270 txt (save-match-data
7271 (org-html-expand
7272 (match-string 3 line)))
7273 todo
7274 (or (and (match-beginning 2)
7275 (not (equal (match-string 2 line)
7276 org-done-string)))
7277 ; TODO, not DONE
7278 (and (= level umax)
7279 (org-search-todo-below
7280 line lines level))))
7281 (if org-export-with-section-numbers
7282 (setq txt (concat (org-section-number level)
7283 " " txt)))
7284 (if (<= level umax)
7285 (progn
7286 (setq head-count (+ head-count 1))
7287 (if (> level last-level)
7288 (progn
7289 (setq cnt (- level last-level))
7290 (while (>= (setq cnt (1- cnt)) 0)
7291 (insert "<ul>"))
7292 (insert "\n")))
7293 (if (< level last-level)
7294 (progn
7295 (setq cnt (- last-level level))
7296 (while (>= (setq cnt (1- cnt)) 0)
7297 (insert "</ul>"))
7298 (insert "\n")))
7299 (insert
7300 (format
7301 (if todo
7302 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
7303 "<li><a href=\"#sec-%d\">%s</a></li>\n")
7304 head-count txt))
7305 (setq last-level level))
7306 ))))
7307 lines)
7308 (while (> last-level 0)
7309 (setq last-level (1- last-level))
7310 (insert "</ul>\n"))
7311 ))
7312 (setq head-count 0)
7313 (org-init-section-numbers)
7314
7315 (while (setq line (pop lines) origline line)
7316 ;; replace "<" and ">" by "&lt;" and "&gt;"
7317 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
7318 (setq line (org-html-expand line))
7319
7320 ;; Verbatim lines
7321 (if (and org-export-with-fixed-width
7322 (string-match "^[ \t]*:\\(.*\\)" line))
7323 (progn
7324 (let ((l (match-string 1 line)))
7325 (while (string-match " " l)
7326 (setq l (replace-match "&nbsp;" t t l)))
7327 (insert "\n<span style='font-family:Courier'>"
7328 l "</span>"
7329 (if (and lines
7330 (not (string-match "^[ \t]+\\(:.*\\)"
7331 (car lines))))
7332 "<br>\n" "\n"))))
7333
7334 (when (string-match org-link-regexp line)
7335 (setq type (match-string 1 line))
7336 (cond
7337 ((member type '("http" "https" "ftp" "mailto" "news"))
7338 ;; standard URL
7339 (setq line (replace-match
7340 "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
7341 nil nil line)))
7342 ((string= type "file")
7343 ;; FILE link
7344
7345 (let* ((filename (match-string 2 line))
7346 (file-is-image-p
7347 (save-match-data
7348 (string-match (org-image-file-name-regexp) filename))))
7349 (setq line (replace-match
7350 (if (and org-export-html-inline-images
7351 file-is-image-p)
7352 "<img src=\"\\2\"/>"
7353 "<a href=\"\\2\">\\1:\\2</a>")
7354 nil nil line))))
7355
7356 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
7357 (setq line (replace-match
7358 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
7359
7360 ;; TODO items
7361 (if (and (string-match org-todo-line-regexp line)
7362 (match-beginning 2))
7363 (if (equal (match-string 2 line) org-done-string)
7364 (setq line (replace-match
7365 "<span style='color:green'>\\2</span>"
7366 nil nil line 2))
7367 (setq line (replace-match "<span style='color:red'>\\2</span>"
7368 nil nil line 2))))
7369
7370 ;; DEADLINES
7371 (if (string-match org-deadline-line-regexp line)
7372 (progn
7373 (if (save-match-data
7374 (string-match "<a href"
7375 (substring line 0 (match-beginning 0))))
7376 nil ; Don't do the replacement - it is inside a link
7377 (setq line (replace-match "<span style='color:red'>\\&</span>"
7378 nil nil line 1)))))
7379
7380 (cond
7381 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
7382 ;; This is a headline
7383 (setq level (- (match-end 1) (match-beginning 1))
7384 txt (match-string 2 line))
7385 (if (<= level umax) (setq head-count (+ head-count 1)))
7386 (org-html-level-start level txt umax
7387 (and org-export-with-toc (<= level umax))
7388 head-count))
7389
7390 ((and org-export-with-tables
7391 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
7392 (if (not table-open)
7393 ;; New table starts
7394 (setq table-open t table-buffer nil table-orig-buffer nil))
7395 ;; Accumulate lines
7396 (setq table-buffer (cons line table-buffer)
7397 table-orig-buffer (cons origline table-orig-buffer))
7398 (when (or (not lines)
7399 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
7400 (car lines))))
7401 (setq table-open nil
7402 table-buffer (nreverse table-buffer)
7403 table-orig-buffer (nreverse table-orig-buffer))
7404 (insert (org-format-table-html table-buffer table-orig-buffer))))
7405 (t
7406 ;; Normal lines
7407 ;; Lines starting with "-", and empty lines make new paragraph.
7408 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
7409 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
7410 ))
7411 (if org-export-html-with-timestamp
7412 (insert org-export-html-html-helper-timestamp))
7413 (insert "</body>\n</html>\n")
7414 (normal-mode)
7415 (save-buffer)
7416 (goto-char (point-min)))))
7417
7418 (defun org-format-table-html (lines olines)
7419 "Find out which HTML converter to use and return the HTML code."
7420 (if (string-match "^[ \t]*|" (car lines))
7421 ;; A normal org table
7422 (org-format-org-table-html lines)
7423 ;; Table made by table.el - test for spanning
7424 (let* ((hlines (delq nil (mapcar
7425 (lambda (x)
7426 (if (string-match "^[ \t]*\\+-" x) x
7427 nil))
7428 lines)))
7429 (first (car hlines))
7430 (ll (and (string-match "\\S-+" first)
7431 (match-string 0 first)))
7432 (re (concat "^[ \t]*" (regexp-quote ll)))
7433 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
7434 hlines))))
7435 (if (and (not spanning)
7436 (not org-export-prefer-native-exporter-for-tables))
7437 ;; We can use my own converter with HTML conversions
7438 (org-format-table-table-html lines)
7439 ;; Need to use the code generator in table.el, with the original text.
7440 (org-format-table-table-html-using-table-generate-source olines)))))
7441
7442 (defun org-format-org-table-html (lines)
7443 "Format a table into html."
7444 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7445 (setq lines (nreverse lines))
7446 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
7447 (setq lines (nreverse lines))
7448 (let ((head (and org-export-highlight-first-table-line
7449 (delq nil (mapcar
7450 (lambda (x) (string-match "^[ \t]*|-" x))
7451 lines))))
7452 lastline line fields html empty)
7453 (setq html (concat org-export-html-table-tag "\n"))
7454 (while (setq lastline line
7455 line (pop lines))
7456 (setq empty "&nbsp")
7457 (catch 'next-line
7458 (if (string-match "^[ \t]*|-" line)
7459 (if lastline
7460 ;; A hline: simulate an empty table row instead.
7461 (setq line (org-fake-empty-table-line lastline)
7462 head nil
7463 empty "")
7464 ;; Ignore this line
7465 (throw 'next-line t)))
7466 ;; Break the line into fields
7467 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7468 (setq html (concat
7469 html
7470 "<tr>"
7471 (mapconcat (lambda (x)
7472 (if (equal x "") (setq x empty))
7473 (if head
7474 (concat "<th>" x "</th>")
7475 (concat "<td valign=\"top\">" x "</td>")))
7476 fields "")
7477 "</tr>\n"))))
7478 (setq html (concat html "</table>\n"))
7479 html))
7480
7481 (defun org-fake-empty-table-line (line)
7482 "Replace everything except \"|\" with spaces."
7483 (let ((i (length line))
7484 (newstr (copy-sequence line)))
7485 (while (> i 0)
7486 (setq i (1- i))
7487 (if (not (eq (aref newstr i) ?|))
7488 (aset newstr i ?\ )))
7489 newstr))
7490
7491 (defun org-format-table-table-html (lines)
7492 "Format a table generated by table.el into html.
7493 This conversion does *not* use `table-generate-source' from table.el.
7494 This has the advantage that Org-mode's HTML conversions can be used.
7495 But it has the disadvantage, that no cell- or row-spanning is allowed."
7496 (let (line field-buffer
7497 (head org-export-highlight-first-table-line)
7498 fields html empty)
7499 (setq html (concat org-export-html-table-tag "\n"))
7500 (while (setq line (pop lines))
7501 (setq empty "&nbsp")
7502 (catch 'next-line
7503 (if (string-match "^[ \t]*\\+-" line)
7504 (progn
7505 (if field-buffer
7506 (progn
7507 (setq html (concat
7508 html
7509 "<tr>"
7510 (mapconcat
7511 (lambda (x)
7512 (if (equal x "") (setq x empty))
7513 (if head
7514 (concat "<th valign=\"top\">" x
7515 "</th>\n")
7516 (concat "<td valign=\"top\">" x
7517 "</td>\n")))
7518 field-buffer "\n")
7519 "</tr>\n"))
7520 (setq head nil)
7521 (setq field-buffer nil)))
7522 ;; Ignore this line
7523 (throw 'next-line t)))
7524 ;; Break the line into fields and store the fields
7525 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
7526 (if field-buffer
7527 (setq field-buffer (mapcar
7528 (lambda (x)
7529 (concat x "<br>" (pop fields)))
7530 field-buffer))
7531 (setq field-buffer fields))))
7532 (setq html (concat html "</table>\n"))
7533 html))
7534
7535 (defun org-format-table-table-html-using-table-generate-source (lines)
7536 "Format a table into html, using `table-generate-source' from table.el.
7537 This has the advantage that cell- or row-spanning is allowed.
7538 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
7539 (require 'table)
7540 (save-excursion
7541 (set-buffer (get-buffer-create " org-tmp1 "))
7542 (erase-buffer)
7543 (insert (mapconcat 'identity lines "\n"))
7544 (goto-char (point-min))
7545 (if (not (re-search-forward "|[^+]" nil t))
7546 (error "Error processing table."))
7547 (table-recognize-table)
7548 (save-excursion
7549 (set-buffer (get-buffer-create " org-tmp2 "))
7550 (erase-buffer))
7551 (table-generate-source 'html " org-tmp2 ")
7552 (set-buffer " org-tmp2 ")
7553 (buffer-substring (point-min) (point-max))))
7554
7555 (defun org-html-expand (string)
7556 "Prepare STRING for HTML export. Applies all active conversions."
7557 ;; First check if there is a link in the line - if yes, apply conversions
7558 ;; only before the start of the link.
7559 (let* ((m (string-match org-link-regexp string))
7560 (s (if m (substring string 0 m) string))
7561 (r (if m (substring string m) "")))
7562 ;; convert < to &lt; and > to &gt;
7563 (while (string-match "<" s)
7564 (setq s (replace-match "&lt;" nil nil s)))
7565 (while (string-match ">" s)
7566 (setq s (replace-match "&gt;" nil nil s)))
7567 (if org-export-html-expand
7568 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
7569 (setq s (replace-match "<\\1>" nil nil s))))
7570 (if org-export-with-emphasize
7571 (setq s (org-export-html-convert-emphasize s)))
7572 (if org-export-with-sub-superscripts
7573 (setq s (org-export-html-convert-sub-super s)))
7574 (if org-export-with-TeX-macros
7575 (let ((start 0) wd ass)
7576 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
7577 (setq wd (match-string 1 s))
7578 (if (setq ass (assoc wd org-html-entities))
7579 (setq s (replace-match (or (cdr ass)
7580 (concat "&" (car ass) ";"))
7581 t t s))
7582 (setq start (+ start (length wd)))))))
7583 (concat s r)))
7584
7585 (defun org-create-multibrace-regexp (left right n)
7586 "Create a regular expression which will match a balanced sexp.
7587 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
7588 as single character strings.
7589 The regexp returned will match the entire expression including the
7590 delimiters. It will also define a single group which contains the
7591 match except for the outermost delimiters. The maximum depth of
7592 stacked delimiters is N. Escaping delimiters is not possible."
7593 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
7594 (or "\\|")
7595 (re nothing)
7596 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
7597 (while (> n 1)
7598 (setq n (1- n)
7599 re (concat re or next)
7600 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
7601 (concat left "\\(" re "\\)" right)))
7602
7603 (defvar org-match-substring-regexp
7604 (concat
7605 "\\([^\\]\\)\\([_^]\\)\\("
7606 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
7607 "\\|"
7608 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
7609 "\\|"
7610 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
7611 "The regular expression matching a sub- or superscript.")
7612
7613 (defun org-export-html-convert-sub-super (string)
7614 "Convert sub- and superscripts in STRING to HTML."
7615 (let (key c)
7616 (while (string-match org-match-substring-regexp string)
7617 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
7618 (setq c (or (match-string 8 string)
7619 (match-string 6 string)
7620 (match-string 5 string)))
7621 (setq string (replace-match
7622 (concat (match-string 1 string)
7623 "<" key ">" c "</" key ">")
7624 t t string)))
7625 (while (string-match "\\\\\\([_^]\\)" string)
7626 (setq string (replace-match (match-string 1 string) t t string))))
7627 string)
7628
7629 (defun org-export-html-convert-emphasize (string)
7630 (while (string-match
7631 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
7632 string)
7633 (setq string (replace-match
7634 (concat "<b>" (match-string 3 string) "</b>")
7635 t t string 2)))
7636 (while (string-match
7637 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
7638 string)
7639 (setq string (replace-match
7640 (concat "<i>" (match-string 3 string) "</i>")
7641 t t string 2)))
7642 (while (string-match
7643 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
7644 string)
7645 (setq string (replace-match
7646 (concat "<u>" (match-string 3 string) "</u>")
7647 t t string 2)))
7648 string)
7649
7650 (defun org-parse-key-lines ()
7651 "Find the special key lines with the information for exporters."
7652 (save-excursion
7653 (goto-char 0)
7654 (let ((re (org-make-options-regexp
7655 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
7656 key)
7657 (while (re-search-forward re nil t)
7658 (setq key (match-string 1))
7659 (cond ((string-equal key "TITLE")
7660 (setq title (match-string 2)))
7661 ((string-equal key "AUTHOR")
7662 (setq author (match-string 2)))
7663 ((string-equal key "EMAIL")
7664 (setq email (match-string 2)))
7665 ((string-equal key "LANGUAGE")
7666 (setq language (match-string 2)))
7667 ((string-equal key "TEXT")
7668 (setq text (concat text "\n" (match-string 2))))
7669 ((string-equal key "OPTIONS")
7670 (setq options (match-string 2))))))))
7671
7672 (defun org-parse-export-options (s)
7673 "Parse the export options line."
7674 (let ((op '(("H" . org-export-headline-levels)
7675 ("num" . org-export-with-section-numbers)
7676 ("toc" . org-export-with-toc)
7677 ("\\n" . org-export-preserve-breaks)
7678 ("@" . org-export-html-expand)
7679 (":" . org-export-with-fixed-width)
7680 ("|" . org-export-with-tables)
7681 ("^" . org-export-with-sub-superscripts)
7682 ("*" . org-export-with-emphasize)
7683 ("TeX" . org-export-with-TeX-macros)))
7684 o)
7685 (while (setq o (pop op))
7686 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
7687 s)
7688 (set (make-local-variable (cdr o))
7689 (car (read-from-string (match-string 1 s))))))))
7690
7691 (defun org-html-level-start (level title umax with-toc head-count)
7692 "Insert a new level in HTML export."
7693 (let ((l (1+ (max level umax))))
7694 (while (<= l org-level-max)
7695 (if (aref levels-open (1- l))
7696 (progn
7697 (org-html-level-close l)
7698 (aset levels-open (1- l) nil)))
7699 (setq l (1+ l)))
7700 (if (> level umax)
7701 (progn
7702 (if (aref levels-open (1- level))
7703 (insert "<li>" title "<p>\n")
7704 (aset levels-open (1- level) t)
7705 (insert "<ul><li>" title "<p>\n")))
7706 (if org-export-with-section-numbers
7707 (setq title (concat (org-section-number level) " " title)))
7708 (setq level (+ level 1))
7709 (if with-toc
7710 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
7711 level head-count title level))
7712 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
7713
7714 (defun org-html-level-close (level)
7715 "Terminate one level in HTML export."
7716 (insert "</ul>"))
7717
7718
7719 ;; Variable holding the vector with section numbers
7720 (defvar org-section-numbers (make-vector org-level-max 0))
7721
7722 (defun org-init-section-numbers ()
7723 "Initialize the vector for the section numbers."
7724 (let* ((level -1)
7725 (numbers (nreverse (org-split-string "" "\\.")))
7726 (depth (1- (length org-section-numbers)))
7727 (i depth) number-string)
7728 (while (>= i 0)
7729 (if (> i level)
7730 (aset org-section-numbers i 0)
7731 (setq number-string (or (car numbers) "0"))
7732 (if (string-match "\\`[A-Z]\\'" number-string)
7733 (aset org-section-numbers i
7734 (- (string-to-char number-string) ?A -1))
7735 (aset org-section-numbers i (string-to-int number-string)))
7736 (pop numbers))
7737 (setq i (1- i)))))
7738
7739 (defun org-section-number (&optional level)
7740 "Return a string with the current section number.
7741 When LEVEL is non-nil, increase section numbers on that level."
7742 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
7743 (when level
7744 (when (> level -1)
7745 (aset org-section-numbers
7746 level (1+ (aref org-section-numbers level))))
7747 (setq idx (1+ level))
7748 (while (<= idx depth)
7749 (if (not (= idx 1))
7750 (aset org-section-numbers idx 0))
7751 (setq idx (1+ idx))))
7752 (setq idx 0)
7753 (while (<= idx depth)
7754 (setq n (aref org-section-numbers idx))
7755 (setq string (concat string (if (not (string= string "")) "." "")
7756 (int-to-string n)))
7757 (setq idx (1+ idx)))
7758 (save-match-data
7759 (if (string-match "\\`\\([@0]\\.\\)+" string)
7760 (setq string (replace-match "" nil nil string)))
7761 (if (string-match "\\(\\.0\\)+\\'" string)
7762 (setq string (replace-match "" nil nil string))))
7763 string))
7764
7765
7766 ;;; Key bindings
7767
7768 ;; - Bindings in Org-mode map are currently
7769 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
7770 ;; abcd fgh j lmnopqrstuvwxyz ? # -+ /= [] ; |,.<> \t necessary bindings
7771 ;; e (?) useful from outline-mode
7772 ;; i k @ expendable from outline-mode
7773 ;; 0123456789 ! $%^& * ()_{} " ~`' free
7774
7775 (define-key org-mode-map [(tab)] 'org-cycle)
7776 (define-key org-mode-map "\C-i" 'org-cycle)
7777 (define-key org-mode-map [(meta tab)] 'org-complete)
7778 (define-key org-mode-map "\M-\C-i" 'org-complete)
7779 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
7780 (define-key org-mode-map [(meta left)] 'org-metaleft)
7781 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
7782 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
7783 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
7784 (define-key org-mode-map [(meta right)] 'org-metaright)
7785 (define-key org-mode-map [(meta up)] 'org-metaup)
7786 (define-key org-mode-map [(meta down)] 'org-metadown)
7787 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
7788 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
7789 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
7790 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
7791 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
7792 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
7793 (define-key org-mode-map "\C-c\C-j" 'org-goto)
7794 (define-key org-mode-map "\C-c\C-t" 'org-todo)
7795 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
7796 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
7797 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
7798 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
7799 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
7800 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
7801 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
7802 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
7803 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
7804 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
7805 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
7806 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
7807 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
7808 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
7809 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
7810 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
7811 (define-key org-mode-map "\C-c[" 'org-add-file)
7812 (define-key org-mode-map "\C-c]" 'org-remove-file)
7813 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
7814 ;(define-key org-mode-map [(shift up)] 'org-timestamp-up)
7815 ;(define-key org-mode-map [(shift down)] 'org-timestamp-down)
7816 (define-key org-mode-map [(shift up)] 'org-shiftup)
7817 (define-key org-mode-map [(shift down)] 'org-shiftdown)
7818 (define-key org-mode-map [(shift left)] 'org-timestamp-down-day)
7819 (define-key org-mode-map [(shift right)] 'org-timestamp-up-day)
7820 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
7821 ;; The following line is e.g. necessary for German keyboards under Suse Linux
7822 (unless org-xemacs-p
7823 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
7824 (define-key org-mode-map [(shift tab)] 'org-shifttab)
7825 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
7826 (define-key org-mode-map [(return)] 'org-return)
7827 (define-key org-mode-map [(shift return)] 'org-table-copy-down)
7828 (define-key org-mode-map [(meta return)] 'org-meta-return)
7829 (define-key org-mode-map [(control up)] 'org-move-line-up)
7830 (define-key org-mode-map [(control down)] 'org-move-line-down)
7831 (define-key org-mode-map "\C-c?" 'org-table-current-column)
7832 (define-key org-mode-map "\C-c " 'org-table-blank-field)
7833 (define-key org-mode-map "\C-c+" 'org-table-sum)
7834 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
7835 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
7836 (define-key org-mode-map "\C-c#" 'org-table-create-with-table.el)
7837 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
7838 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
7839 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
7840 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
7841 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
7842 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
7843 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
7844 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
7845 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
7846 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
7847 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
7848
7849
7850 ;; FIXME: Do we really need to save match data in these commands?
7851 ;; I would like to remove it in order to minimize impact.
7852 ;; Self-insert already does not preserve it. How much resources used by this???
7853
7854 (defsubst org-table-p ()
7855 (if (and (eq major-mode 'org-mode) font-lock-mode)
7856 (eq (get-text-property (point) 'face) 'org-table-face)
7857 (save-match-data (org-at-table-p))))
7858
7859 (defun org-self-insert-command (N)
7860 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7861 If the cursor is in a table looking at whitespace, the whitespace is
7862 overwritten, and the table is not marked as requiring realignment."
7863 (interactive "p")
7864 (if (and (org-table-p)
7865 (eq N 1)
7866 (looking-at "[^|\n]* +|"))
7867 (let (org-table-may-need-update (pos (point)))
7868 (goto-char (1- (match-end 0)))
7869 (delete-backward-char 1)
7870 (goto-char (match-beginning 0))
7871 (self-insert-command N))
7872 (setq org-table-may-need-update t)
7873 (self-insert-command N)))
7874
7875 ;; FIXME:
7876 ;; The following two functions might still be optimized to trigger
7877 ;; re-alignment less frequently.
7878
7879 (defun org-delete-backward-char (N)
7880 "Like `delete-backward-char', insert whitespace at field end in tables.
7881 When deleting backwards, in tables this function will insert whitespace in
7882 front of the next \"|\" separator, to keep the table aligned. The table will
7883 still be marked for re-alignment, because a narrow field may lead to a
7884 reduced column width."
7885 (interactive "p")
7886 (if (and (org-table-p)
7887 (eq N 1)
7888 (looking-at ".*?|"))
7889 (let ((pos (point)))
7890 (backward-delete-char N)
7891 (skip-chars-forward "^|")
7892 (insert " ")
7893 (goto-char (1- pos)))
7894 (backward-delete-char N)))
7895
7896 (defun org-delete-char (N)
7897 "Like `delete-char', but insert whitespace at field end in tables.
7898 When deleting characters, in tables this function will insert whitespace in
7899 front of the next \"|\" separator, to keep the table aligned. The table
7900 will still be marked for re-alignment, because a narrow field may lead to
7901 a reduced column width."
7902 (interactive "p")
7903 (if (and (org-table-p)
7904 (eq N 1))
7905 (if (looking-at ".*?|")
7906 (let ((pos (point)))
7907 (replace-match (concat
7908 (substring (match-string 0) 1 -1)
7909 " |"))
7910 (goto-char pos)))
7911 (delete-char N)))
7912
7913 ;; How to do this: Measure non-white length of current string
7914 ;; If equal to column width, we should realign.
7915
7916 (when (eq org-enable-table-editor 'optimized)
7917 ;; If the user wants maximum table support, we need to hijack
7918 ;; some standard editing functions
7919 (substitute-key-definition 'self-insert-command 'org-self-insert-command
7920 org-mode-map global-map)
7921 (substitute-key-definition 'delete-char 'org-delete-char
7922 org-mode-map global-map)
7923 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
7924 org-mode-map global-map)
7925 (define-key org-mode-map "|" 'self-insert-command))
7926
7927 (defun org-shiftcursor-error ()
7928 "Throw an error because Shift-Cursor command was applied in wrong context."
7929 (error "This command is only active in tables and on headlines."))
7930
7931 (defun org-shifttab ()
7932 "Call `(org-cycle t)' or `org-table-previous-field'."
7933 (interactive)
7934 (cond
7935 ((org-at-table-p) (org-table-previous-field))
7936 (t (org-cycle '(4)))))
7937
7938 (defun org-shiftmetaleft (&optional arg)
7939 "Call `org-promote-subtree' or `org-table-delete-column'."
7940 (interactive "P")
7941 (cond
7942 ((org-at-table-p) (org-table-delete-column arg))
7943 ((org-on-heading-p) (org-promote-subtree arg))
7944 (t (org-shiftcursor-error))))
7945 (defun org-shiftmetaright (&optional arg)
7946 "Call `org-demote-subtree' or `org-table-insert-column'."
7947 (interactive "P")
7948 (cond
7949 ((org-at-table-p) (org-table-insert-column arg))
7950 ((org-on-heading-p) (org-demote-subtree arg))
7951 (t (org-shiftcursor-error))))
7952 (defun org-shiftmetaup (&optional arg)
7953 "Call `org-move-subtree-up' or `org-table-kill-row'."
7954 (interactive "P")
7955 (cond
7956 ((org-at-table-p) (org-table-kill-row arg))
7957 ((org-on-heading-p) (org-move-subtree-up arg))
7958 (t (org-shiftcursor-error))))
7959 (defun org-shiftmetadown (&optional arg)
7960 "Call `org-move-subtree-down' or `org-table-insert-row'."
7961 (interactive "P")
7962 (cond
7963 ((org-at-table-p) (org-table-insert-row arg))
7964 ((org-on-heading-p) (org-move-subtree-down arg))
7965 (t (org-shiftcursor-error))))
7966
7967 (defun org-metaleft (&optional arg)
7968 "Call `org-do-promote' or `org-table-move-column' to left."
7969 (interactive "P")
7970 (cond
7971 ((org-at-table-p) (org-table-move-column 'left))
7972 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote arg))
7973 (t (backward-word (prefix-numeric-value arg)))))
7974 (defun org-metaright (&optional arg)
7975 "Call `org-do-demote' or `org-table-move-column' to right."
7976 (interactive "P")
7977 (cond
7978 ((org-at-table-p) (org-table-move-column nil))
7979 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote arg))
7980 (t (forward-word (prefix-numeric-value arg)))))
7981 (defun org-metaup (&optional arg)
7982 "Call `org-move-subtree-up' or `org-table-move-row' up."
7983 (interactive "P")
7984 (cond
7985 ((org-at-table-p) (org-table-move-row 'up))
7986 ((org-on-heading-p) (org-move-subtree-up arg))
7987 (t (org-shiftcursor-error))))
7988 (defun org-metadown (&optional arg)
7989 "Call `org-move-subtree-down' or `org-table-move-row' down."
7990 (interactive "P")
7991 (cond
7992 ((org-at-table-p) (org-table-move-row nil))
7993 ((org-on-heading-p) (org-move-subtree-down arg))
7994 (t (org-shiftcursor-error))))
7995
7996 (defun org-shiftup (&optional arg)
7997 "Call `org-timestamp-up' or `org-priority-up'."
7998 (interactive "P")
7999 (cond
8000 ((org-at-timestamp-p) (org-timestamp-up arg))
8001 (t (org-priority-up))))
8002
8003 (defun org-shiftdown (&optional arg)
8004 "Call `org-timestamp-down' or `org-priority-down'."
8005 (interactive "P")
8006 (cond
8007 ((org-at-timestamp-p) (org-timestamp-down arg))
8008 (t (org-priority-down))))
8009
8010 (defun org-copy-special (arg)
8011 "Call either `org-table-copy' or `org-copy-subtree'."
8012 (interactive "P")
8013 (if (org-at-table-p)
8014 (org-table-copy-region arg)
8015 (org-copy-subtree arg)))
8016
8017 (defun org-cut-special (arg)
8018 "Call either `org-table-copy' or `org-copy-subtree'."
8019 (interactive "P")
8020 (if (org-at-table-p)
8021 (org-table-cut-region arg)
8022 (org-cut-subtree arg)))
8023
8024 (defun org-paste-special (arg)
8025 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
8026 (interactive "P")
8027 (if (org-at-table-p)
8028 (org-table-paste-rectangle arg)
8029 (org-paste-subtree arg)))
8030
8031 (defun org-ctrl-c-ctrl-c (&optional arg)
8032 "Call realign table, or recognize a table.el table.
8033 When the cursor is inside a table created by the table.el package,
8034 activate that table. Otherwise, if the cursor is at a normal table
8035 created with org.el, re-align that table. This command works even if
8036 the automatic table editor has been turned off."
8037 (interactive "P")
8038 (let ((org-enable-table-editor t))
8039 (cond
8040 ((org-at-table.el-p)
8041 (require 'table)
8042 (beginning-of-line 1)
8043 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
8044 (table-recognize-table))
8045 ((org-at-table-p)
8046 (org-table-align))
8047 ((save-excursion (beginning-of-line 1) (looking-at "#\\+[A-Z]+"))
8048 (let (org-inhibit-startup) (org-mode)))
8049 ((org-region-active-p)
8050 (org-table-convert-region (region-beginning) (region-end) arg))
8051 ((and (region-beginning) (region-end))
8052 (if (y-or-n-p "Convert inactive region to table? ")
8053 (org-table-convert-region (region-beginning) (region-end) arg)
8054 (error "Abort")))
8055 (t (error "No table at point, and no region to make one.")))))
8056
8057 (defun org-return (&optional arg)
8058 "Call `org-table-next-row' or `newline'."
8059 (interactive "P")
8060 (cond
8061 ((org-at-table-p)
8062 (org-table-justify-field-maybe)
8063 (org-table-next-row))
8064 (t (newline))))
8065
8066 (defun org-meta-return (&optional arg)
8067 "Call `org-insert-heading' or `org-table-wrap-region'."
8068 (interactive "P")
8069 (cond
8070 ((org-at-table-p)
8071 (org-table-wrap-region arg))
8072 (t (org-insert-heading arg))))
8073
8074 ;;; Menu entries
8075
8076 ;; First, remove the outline menus.
8077 (if org-xemacs-p
8078 (add-hook 'org-mode-hook
8079 (lambda ()
8080 (delete-menu-item '("Headings"))
8081 (delete-menu-item '("Show"))
8082 (delete-menu-item '("Hide"))
8083 (set-menubar-dirty-flag)))
8084 (setq org-mode-map (delq (assoc 'menu-bar (cdr org-mode-map))
8085 org-mode-map)))
8086
8087 ;; Define the Org-mode menus
8088 (easy-menu-define org-org-menu org-mode-map "Org menu"
8089 '("Org"
8090 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
8091 ["Sparse Tree" org-occur t]
8092 ["Show All" show-all t]
8093 "--"
8094 ["New Heading" org-insert-heading t]
8095 ("Navigate Headings"
8096 ["Up" outline-up-heading t]
8097 ["Next" outline-next-visible-heading t]
8098 ["Previous" outline-previous-visible-heading t]
8099 ["Next Same Level" outline-forward-same-level t]
8100 ["Previous Same Level" outline-backward-same-level t]
8101 "--"
8102 ["Jump" org-goto t])
8103 ("Edit Structure"
8104 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
8105 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
8106 "--"
8107 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
8108 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
8109 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
8110 "--"
8111 ["Promote Heading" org-metaleft (not (org-at-table-p))]
8112 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
8113 ["Demote Heading" org-metaright (not (org-at-table-p))]
8114 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))])
8115 "--"
8116 ("TODO Lists"
8117 ["TODO/DONE/-" org-todo t]
8118 ["Show TODO Tree" org-show-todo-tree t]
8119 "--"
8120 ["Set Priority" org-priority t]
8121 ["Priority Up" org-shiftup t]
8122 ["Priority Down" org-shiftdown t])
8123 ("Dates and Scheduling"
8124 ["Timestamp" org-time-stamp t]
8125 ("Change Date"
8126 ["1 Day Later" org-timestamp-up-day t]
8127 ["1 Day Earlier" org-timestamp-down-day t]
8128 ["1 ... Later" org-shiftup t]
8129 ["1 ... Earlier" org-shiftdown t])
8130 ["Compute Time Range" org-evaluate-time-range t]
8131 ["Schedule Item" org-schedule t]
8132 ["Deadline" org-deadline t]
8133 "--"
8134 ["Goto Calendar" org-goto-calendar t]
8135 ["Date from Calendar" org-date-from-calendar t])
8136 "--"
8137 ("Timeline/Agenda"
8138 ["Show TODO Tree this File" org-show-todo-tree t]
8139 ["Check Deadlines this File" org-check-deadlines t]
8140 ["Timeline Current File" org-timeline t]
8141 "--"
8142 ["Agenda" org-agenda t])
8143 ("File List for Agenda")
8144 "--"
8145 ("Hyperlinks"
8146 ["Store Link (Global)" org-store-link t]
8147 ["Insert Link" org-insert-link t]
8148 ["Follow Link" org-open-at-point t])
8149 "--"
8150 ("Table"
8151 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
8152 ["Next Field" org-cycle (org-at-table-p)]
8153 ["Previous Field" org-shifttab (org-at-table-p)]
8154 ["Next Row" org-return (org-at-table-p)]
8155 "--"
8156 ["Blank Field" org-table-blank-field (org-at-table-p)]
8157 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
8158 "--"
8159 ("Column"
8160 ["Move Column Left" org-metaleft (org-at-table-p)]
8161 ["Move Column Right" org-metaright (org-at-table-p)]
8162 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
8163 ["Insert Column" org-shiftmetaright (org-at-table-p)])
8164 ("Row"
8165 ["Move Row Up" org-metaup (org-at-table-p)]
8166 ["Move Row Down" org-metadown (org-at-table-p)]
8167 ["Delete Row" org-shiftmetaup (org-at-table-p)]
8168 ["Insert Row" org-shiftmetadown (org-at-table-p)]
8169 "--"
8170 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
8171 ("Rectangle"
8172 ["Copy Rectangle" org-copy-special (org-at-table-p)]
8173 ["Cut Rectangle" org-cut-special (org-at-table-p)]
8174 ["Paste Rectangle" org-paste-special (org-at-table-p)]
8175 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
8176 "--"
8177 ["Which Column?" org-table-current-column (org-at-table-p)]
8178 ["Sum Column/Rectangle" org-table-sum
8179 (or (org-at-table-p) (org-region-active-p))]
8180 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
8181 "--"
8182 ["Invisible Vlines" org-table-toggle-vline-visibility
8183 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
8184 "--"
8185 ["Create" org-table-create (and (not (org-at-table-p))
8186 org-enable-table-editor)]
8187 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
8188 ["Import from File" org-table-import (not (org-at-table-p))]
8189 ["Export to File" org-table-export (org-at-table-p)]
8190 "--"
8191 ["Create/Convert from/to table.el" org-table-create-with-table.el t])
8192 "--"
8193 ("Export"
8194 ["ASCII" org-export-as-ascii t]
8195 ["Extract Visible Text" org-export-copy-visible t]
8196 ["HTML" org-export-as-html t]
8197 ["HTML and Open" org-export-as-html-and-open t]
8198 ; ["OPML" org-export-as-opml nil]
8199 "--"
8200 ["Option Template" org-insert-export-options-template t]
8201 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
8202 "--"
8203 ("Documentation"
8204 ["Show Version" org-version t]
8205 ["Info Documentation" org-info t])
8206 ("Customize"
8207 ["Browse Org Group" org-customize t]
8208 "--"
8209 ["Build Full Customize Menu" org-create-customize-menu
8210 (fboundp 'customize-menu-create)])
8211 ))
8212
8213 (defun org-info (&optional node)
8214 "Read documentation for Org-mode in the info system.
8215 With optional NODE, go directly to that node."
8216 (interactive)
8217 (require 'info)
8218 (Info-goto-node (format "(org)%s" (or node ""))))
8219
8220 (defun org-install-agenda-files-menu ()
8221 (easy-menu-change
8222 '("Org") "File List for Agenda"
8223 (append
8224 (list
8225 ["Edit File List" (customize-variable 'org-agenda-files) t]
8226 ["Add Current File to List" org-add-file t]
8227 ["Remove Current File from List" org-remove-file t]
8228 "--")
8229 (mapcar 'org-file-menu-entry org-agenda-files))))
8230
8231 ;;; Documentation
8232
8233 (defun org-customize ()
8234 "Call the customize function with org as argument."
8235 (interactive)
8236 (customize-browse 'org))
8237
8238 (defun org-create-customize-menu ()
8239 "Create a full customization menu for Org-mode, insert it into the menu."
8240 (interactive)
8241 (if (fboundp 'customize-menu-create)
8242 (progn
8243 (easy-menu-change
8244 '("Org") "Customize"
8245 `(["Browse Org group" org-customize t]
8246 "--"
8247 ,(customize-menu-create 'org)
8248 ["Set" Custom-set t]
8249 ["Save" Custom-save t]
8250 ["Reset to Current" Custom-reset-current t]
8251 ["Reset to Saved" Custom-reset-saved t]
8252 ["Reset to Standard Settings" Custom-reset-standard t]))
8253 (message "\"Org\"-menu now contains full customization menu"))
8254 (error "Cannot expand menu (outdated version of cus-edit.el)")))
8255
8256 ;;; Miscellaneous stuff
8257
8258 (defun org-move-line-down (arg)
8259 "Move the current line up."
8260 (interactive "p")
8261 (let ((col (current-column))
8262 beg end pos)
8263 (beginning-of-line 1) (setq beg (point))
8264 (beginning-of-line 2) (setq end (point))
8265 (beginning-of-line (+ 1 arg))
8266 (setq pos (move-marker (make-marker) (point)))
8267 (insert (delete-and-extract-region beg end))
8268 (goto-char pos)
8269 (move-to-column col)))
8270
8271 (defun org-move-line-up (arg)
8272 "Move the current line up."
8273 (interactive "p")
8274 (let ((col (current-column))
8275 beg end pos)
8276 (beginning-of-line 1) (setq beg (point))
8277 (beginning-of-line 2) (setq end (point))
8278 (beginning-of-line (+ -2 arg))
8279 (setq pos (move-marker (make-marker) (point)))
8280 (insert (delete-and-extract-region beg end))
8281 (goto-char pos)
8282 (move-to-column col)))
8283
8284 ;; Functions needed for Emacs/XEmacs region compatibility
8285
8286 (defun org-region-active-p ()
8287 "Is transient-mark-mode on and the region active?
8288 Works on both Emacs and XEmacs."
8289 (if org-ignore-region
8290 nil
8291 (if org-xemacs-p
8292 (and zmacs-regions (region-active-p))
8293 (and transient-mark-mode mark-active))))
8294
8295 (defun org-add-to-invisibility-spec (arg)
8296 "Add elements to `buffer-invisibility-spec'.
8297 See documentation for `buffer-invisibility-spec' for the kind of elements
8298 that can be added."
8299 (cond
8300 ((fboundp 'add-to-invisibility-spec)
8301 (add-to-invisibility-spec arg))
8302 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
8303 (setq buffer-invisibility-spec (list arg)))
8304 (t
8305 (setq buffer-invisibility-spec
8306 (cons arg buffer-invisibility-spec)))))
8307
8308 (defun org-remove-from-invisibility-spec (arg)
8309 "Remove elements from `buffer-invisibility-spec'."
8310 (if (fboundp 'remove-from-invisibility-spec)
8311 (remove-from-invisibility-spec arg)
8312 (if (consp buffer-invisibility-spec)
8313 (setq buffer-invisibility-spec
8314 (delete arg buffer-invisibility-spec)))))
8315
8316 (defun org-in-invisibility-spec-p (arg)
8317 "Is ARG a member of `buffer-invisibility-spec'?."
8318 (if (consp buffer-invisibility-spec)
8319 (member arg buffer-invisibility-spec)
8320 nil))
8321
8322 (defun org-image-file-name-regexp ()
8323 "Return regexp matching the file names of images."
8324 (if (fboundp 'image-file-name-regexp)
8325 (image-file-name-regexp)
8326 (let ((image-file-name-extensions
8327 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
8328 "xbm" "xpm" "pbm" "pgm" "ppm")))
8329 (concat "\\."
8330 (regexp-opt (nconc (mapcar 'upcase
8331 image-file-name-extensions)
8332 image-file-name-extensions)
8333 t)
8334 "\\'"))))
8335
8336 ;; Functions needed for compatibility with old outline.el
8337
8338 ;; The following functions capture almost the entire compatibility code
8339 ;; between the different versions of outline-mode. The only other place
8340 ;; where this is important are the font-lock-keywords. Search for
8341 ;; `org-noutline-p' to find it.
8342
8343 ;; C-a should go to the beginning of a *visible* line, also in the
8344 ;; new outline.el. I guess this should be patched into Emacs?
8345 (defun org-beginning-of-line ()
8346 "Go to the beginning of the current line. If that is invisible, continue
8347 to a visible line beginning. This makes the function of C-a more intuitive."
8348 (interactive)
8349 (beginning-of-line 1)
8350 (if (bobp)
8351 nil
8352 (backward-char 1)
8353 (if (org-invisible-p)
8354 (while (and (not (bobp)) (org-invisible-p))
8355 (backward-char 1)
8356 (beginning-of-line 1))
8357 (forward-char 1))))
8358 (when org-noutline-p
8359 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
8360
8361 (defun org-invisible-p ()
8362 "Check if point is at a character currently not visible."
8363 (if org-noutline-p
8364 ;; Early versions of noutline don't have `outline-invisible-p'.
8365 (if (fboundp 'outline-invisible-p)
8366 (outline-invisible-p)
8367 (get-char-property (point) 'invisible))
8368 (save-excursion
8369 (skip-chars-backward "^\r\n")
8370 (if (bobp)
8371 nil
8372 (equal (char-before) ?\r)))))
8373
8374 (defun org-back-to-heading (&optional invisible-ok)
8375 "Move to previous heading line, or beg of this line if it's a heading.
8376 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
8377 (if org-noutline-p
8378 (outline-back-to-heading invisible-ok)
8379 (if (looking-at outline-regexp)
8380 t
8381 (if (re-search-backward (concat (if invisible-ok "[\r\n]" "^")
8382 outline-regexp)
8383 nil t)
8384 (if invisible-ok
8385 (progn (forward-char 1)
8386 (looking-at outline-regexp)))
8387 (error "Before first heading")))))
8388
8389 (defun org-on-heading-p (&optional invisible-ok)
8390 "Return t if point is on a (visible) heading line.
8391 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
8392 (if org-noutline-p
8393 (outline-on-heading-p 'invisible-ok)
8394 (save-excursion
8395 (skip-chars-backward "^\n\r")
8396 (and (looking-at outline-regexp)
8397 (or invisible-ok
8398 (bobp)
8399 (equal (char-before) ?\n))))))
8400
8401 (defun org-up-heading-all (arg)
8402 "Move to the heading line of which the present line is a subheading.
8403 This function considers both visible and invisible heading lines.
8404 With argument, move up ARG levels."
8405 (if org-noutline-p
8406 (outline-up-heading arg t)
8407 (org-back-to-heading t)
8408 (looking-at outline-regexp)
8409 (if (<= (- (match-end 0) (match-beginning 0)) arg)
8410 (error "Cannot move up %d levels" arg)
8411 (re-search-backward
8412 (concat "[\n\r]" (regexp-quote
8413 (make-string (- (match-end 0) (match-beginning 0) arg)
8414 ?*))
8415 "[^*]"))
8416 (forward-char 1))))
8417
8418 (defun org-show-hidden-entry ()
8419 "Show an entry where even the heading is hidden."
8420 (save-excursion
8421 (if (not org-noutline-p)
8422 (progn
8423 (org-back-to-heading t)
8424 (org-flag-heading nil)))
8425 (show-entry)))
8426
8427 (defun org-check-occur-regexp (regexp)
8428 "If REGEXP starts with \"^\", modify it to check for \\r as well.
8429 Of course, only for the old outline mode."
8430 (if org-noutline-p
8431 regexp
8432 (if (string-match "^\\^" regexp)
8433 (concat "[\n\r]" (substring regexp 1))
8434 regexp)))
8435
8436 (defun org-flag-heading (flag &optional entry)
8437 "Flag the current heading. FLAG non-nil means make invisible.
8438 When ENTRY is non-nil, show the entire entry."
8439 (save-excursion
8440 (org-back-to-heading t)
8441 (if (not org-noutline-p)
8442 ;; Make the current headline visible
8443 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
8444 ;; Check if we should show the entire entry
8445 (if entry
8446 (progn
8447 (show-entry)
8448 (save-excursion ;; FIXME: Is this the fix for points in the -|
8449 ;; middle of text? |
8450 (and (outline-next-heading) ;; |
8451 (org-flag-heading nil)))) ; show the next heading _|
8452 (outline-flag-region (max 1 (1- (point)))
8453 (save-excursion (outline-end-of-heading) (point))
8454 (if org-noutline-p
8455 flag
8456 (if flag ?\r ?\n))))))
8457
8458 (defun org-make-options-regexp (kwds)
8459 "Make a regular expression for keyword lines."
8460 (concat
8461 (if org-noutline-p "^" "[\n\r]")
8462 "#?[ \t]*\\+\\("
8463 (mapconcat 'regexp-quote kwds "\\|")
8464 "\\):[ \t]*"
8465 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
8466
8467 ;; Advise the bookmark-jump function to make jump position visible
8468 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
8469 (eval-after-load "bookmark"
8470 '(defadvice bookmark-jump (after org-make-visible activate)
8471 "Make the position visible."
8472 (and (eq major-mode 'org-mode)
8473 (org-invisible-p)
8474 (org-show-hierarchy-above))))
8475
8476 ;;; Finish up
8477
8478 (provide 'org)
8479
8480 (run-hooks 'org-load-hook)
8481
8482 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
8483
8484 ;;; org.el ends here
8485