]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(calc-embedded-close-formula, calc-embedded-open-formula,
[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.15
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke.
80 ;;
81 ;; Changes:
82 ;; -------
83 ;; Version 3.15
84 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
85 ;; of unmodified entry text. `C-c :' toggles this keyword.
86 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
87 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
88 ;; color, to reduce the amount of aggressive color in the buffer.
89 ;;
90 ;; Version 3.14
91 ;; - Formulas for individual fields in table.
92 ;; - Automatic recalculation in calculating tables.
93 ;; - Named fields and columns in tables.
94 ;; - Fixed bug with calling `org-archive' several times in a row.
95 ;;
96 ;; Version 3.13
97 ;; - Efficiency improvements: Fewer table re-alignments needed.
98 ;; - New special lines in tables, for defining names for individual cells.
99 ;;
100 ;; Version 3.12
101 ;; - Tables can store formulas (one per column) and compute fields.
102 ;; Not quite like a full spreadsheet, but very powerful.
103 ;; - table.el keybinding is now `C-c ~'.
104 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
105 ;; - Small changes to keys in agenda buffer. Affected keys:
106 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
107 ;; - Bug fixes.
108 ;;
109 ;; Version 3.11
110 ;; - Links inserted with C-c C-l are now by default enclosed in angle
111 ;; brackets. See the new variable `org-link-format'.
112 ;; - ">" terminates a link, this is a way to have several links in a line.
113 ;; Both "<" and ">" are no longer allowed as characters in a link.
114 ;; - Archiving of finished tasks.
115 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
116 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
117 ;; - Compatibility problems with viper-mode fixed.
118 ;; - Improved html export of tables.
119 ;; - Various clean-up changes.
120 ;;
121 ;; Version 3.10
122 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
123 ;;
124 ;; Version 3.09
125 ;; - Time-of-day specifications in agenda are extracted and placed
126 ;; into the prefix. Timed entries can be placed into a time grid for
127 ;; day.
128 ;;
129 ;; Version 3.08
130 ;; - "|" no longer allowed as part of a link, to allow links in tables.
131 ;; - The prefix of items in the agenda buffer can be configured.
132 ;; - Cleanup.
133 ;;
134 ;; Version 3.07
135 ;; - Some folding incinsistencies removed.
136 ;; - BBDB links to company-only entries.
137 ;; - Bug fixes and global cleanup.
138 ;;
139 ;; Version 3.06
140 ;; - M-S-RET inserts a new TODO heading.
141 ;; - New startup option `content'.
142 ;; - Better visual response when TODO items in agenda change status.
143 ;; - Window positioning after visibility state changes optimized and made
144 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
145 ;;
146 ;; Version 3.05
147 ;; - Agenda entries from the diary are linked to the diary file, so
148 ;; adding and editing diary entries can be done directly from the agenda.
149 ;; - Many calendar/diary commands available directly from agenda.
150 ;; - Field copying in tables with S-RET does increment.
151 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
152 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
153 ;;
154 ;; Version 3.04
155 ;; - Table editor optimized to need fewer realignments, and to keep
156 ;; table shape when typing in fields.
157 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
158 ;; into arbitrary major modes.
159 ;; - Fixed bug with realignment in XEmacs.
160 ;; - Startup options can be set with special #+STARTUP line.
161 ;; - Heading following a match in org-occur can be suppressed.
162 ;;
163 ;; Version 3.03
164 ;; - Copyright transfer to the FSF.
165 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
166 ;; - Timeline now always contains today, and `.' jumps to it.
167 ;; - Table editor:
168 ;; - cut and paste of rectangular regions in tables
169 ;; - command to convert org-mode table to table.el table and back
170 ;; - command to treat several cells like a paragraph and fill it
171 ;; - command to convert a buffer region to a table
172 ;; - import/export tables as tab-separated files (exchange with Excel)
173 ;; - Agenda:
174 ;; - Sorting mechanism for agenda items rewritten from scratch.
175 ;; - Sorting fully configurable.
176 ;; - Entries specifying a time are sorted together.
177 ;; - Completion also covers option keywords after `#-'.
178 ;; - Bug fixes.
179 ;;
180 ;; Version 3.01
181 ;; - New reference card, thanks to Philip Rooke for creating it.
182 ;; - Single file agenda renamed to "Timeline". It no longer shows
183 ;; warnings about upcoming deadlines/overdue scheduled items.
184 ;; That functionality is now limited to the (multifile) agenda.
185 ;; - When reading a date, the calendar can be manipulated with keys.
186 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
187 ;; - Minor bug fixes and documentation improvements.
188
189 ;;; Code:
190
191 (eval-when-compile (require 'cl) (require 'calendar))
192 (require 'outline)
193 (require 'time-date)
194 (require 'easymenu)
195
196 (defvar calc-embedded-close-formula)
197 (defvar calc-embedded-open-formula)
198 (defvar font-lock-unfontify-region-function)
199
200 ;;; Customization variables
201
202 (defvar org-version "3.15"
203 "The version number of the file org.el.")
204 (defun org-version ()
205 (interactive)
206 (message "Org-mode version %s" org-version))
207
208 ;; The following two constants are for compatibility with different Emacs
209 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
210 ;; The compatibility code in org.el is based on these two constants.
211 (defconst org-xemacs-p (featurep 'xemacs)
212 "Are we running xemacs?")
213 (defconst org-noutline-p (featurep 'noutline)
214 "Are we using the new outline mode?")
215
216 (defgroup org nil
217 "Outline-based notes management and organizer "
218 :tag "Org"
219 :group 'outlines
220 :group 'hypermedia
221 :group 'calendar)
222
223 (defgroup org-startup nil
224 "Options concerning startup of Org-mode."
225 :tag "Org Startup"
226 :group 'org)
227
228 (defcustom org-CUA-compatible nil
229 "Non-nil means use alternative key bindings for S-<cursor movement>.
230 Org-mode used S-<cursor movement> for changing timestamps and priorities.
231 S-<cursor movement> is also used for example by `CUA-mode' to select text.
232 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
233 alternative bindings. Setting this variable to t will replace the following
234 keys both in Org-mode and in the Org-agenda buffer.
235
236 S-RET -> C-S-RET
237 S-up -> M-p
238 S-down -> M-n
239 S-left -> M--
240 S-right -> M-+
241
242 If you do not like the alternative keys, take a look at the variable
243 `org-disputed-keys'.
244
245 This option is only relevant at load-time of Org-mode. Changing it requires
246 a restart of Emacs to become effective."
247 :group 'org-startup
248 :type 'boolean)
249
250 (defvar org-disputed-keys
251 '((S-up [(shift up)] [(meta ?p)])
252 (S-down [(shift down)] [(meta ?n)])
253 (S-left [(shift left)] [(meta ?-)])
254 (S-right [(shift right)] [(meta ?+)])
255 (S-return [(shift return)] [(control shift return)]))
256 "Keys for which Org-mode and other modes compete.
257 This is an alist, cars are symbols for lookup, 1st element is the default key,
258 second element will be used when `org-CUA-compatible' is t.")
259
260 (defun org-key (key)
261 "Select a key according to `org-CUA-compatible'."
262 (nth (if org-CUA-compatible 2 1)
263 (or (assq key org-disputed-keys)
264 (error "Invalid Key %s in `org-key'" key))))
265
266 (defcustom org-startup-folded t
267 "Non-nil means, entering Org-mode will switch to OVERVIEW.
268 This can also be configured on a per-file basis by adding one of
269 the following lines anywhere in the buffer:
270
271 #+STARTUP: fold
272 #+STARTUP: nofold
273 #+STARTUP: content"
274 :group 'org-startup
275 :type '(choice
276 (const :tag "nofold: show all" nil)
277 (const :tag "fold: overview" t)
278 (const :tag "content: all headlines" content)))
279
280 (defcustom org-startup-truncated t
281 "Non-nil means, entering Org-mode will set `truncate-lines'.
282 This is useful since some lines containing links can be very long and
283 uninteresting. Also tables look terrible when wrapped."
284 :group 'org-startup
285 :type 'boolean)
286
287 (defcustom org-startup-with-deadline-check nil
288 "Non-nil means, entering Org-mode will run the deadline check.
289 This means, if you start editing an org file, you will get an
290 immediate reminder of any due deadlines.
291 This can also be configured on a per-file basis by adding one of
292 the following lines anywhere in the buffer:
293
294 #+STARTUP: dlcheck
295 #+STARTUP: nodlcheck"
296 :group 'org-startup
297 :type 'boolean)
298
299 (defcustom org-insert-mode-line-in-empty-file nil
300 "Non-nil means insert the first line setting Org-mode in empty files.
301 When the function `org-mode' is called interactively in an empty file, this
302 normally means that the file name does not automatically trigger Org-mode.
303 To ensure that the file will always be in Org-mode in the future, a
304 line enforcing Org-mode will be inserted into the buffer, if this option
305 has been set."
306 :group 'org-startup
307 :type 'boolean)
308
309 (defgroup org-keywords nil
310 "Options concerning TODO items in Org-mode."
311 :tag "Org Keywords"
312 :group 'org)
313
314 (defcustom org-todo-keywords '("TODO" "DONE")
315 "List of TODO entry keywords.
316 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
317 considered to mean that the entry is \"done\". All the other mean that
318 action is required, and will make the entry show up in todo lists, diaries
319 etc.
320 The command \\[org-todo] cycles an entry through these states, and an
321 additional state where no keyword is present. For details about this
322 cycling, see also the variable `org-todo-interpretation'
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type '(repeat (string :tag "Keyword")))
326
327 (defcustom org-todo-interpretation 'sequence
328 "Controls how TODO keywords are interpreted.
329 \\<org-mode-map>Possible values are `sequence' and `type'.
330 This variable is only relevant if `org-todo-keywords' contains more than two
331 states. There are two ways how these keywords can be used:
332
333 - As a sequence in the process of working on a TODO item, for example
334 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
335 org-todo-interpretation 'sequence)
336
337 - As different types of TODO items, for example
338 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
339 org-todo-interpretation 'type)
340
341 When the states are interpreted as a sequence, \\[org-todo] always cycles
342 to the next state, in order to walk through all different states. So with
343 \\[org-todo], you turn an empty entry into the state TODO. When you started
344 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
345 later to VERIFY and finally to DONE.
346
347 When the states are interpreted as types, \\[org-todo] still cycles through
348 when it is called several times in direct succession, in order to initially
349 select the type. However, if not called immediately after a previous
350 \\[org-todo], it switches from each type directly to DONE. So with the
351 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
352 RELAXED. If you later return to this entry and press \\[org-todo] again,
353 RELAXED will not be changed REMIND, but directly to DONE.
354
355 You can create a large number of types. To initially select a
356 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
357 type with completion. Of course, you can also type the keyword
358 directly into the buffer. M-TAB completes TODO keywords at the
359 beginning of a headline."
360 :group 'org-keywords
361 :type '(choice (const sequence)
362 (const type)))
363
364 (defcustom org-default-priority ?B
365 "The default priority of TODO items.
366 This is the priority an item get if no explicit priority is given."
367 :group 'org-keywords
368 :type 'character)
369
370 (defcustom org-lowest-priority ?C
371 "The lowest priority of TODO items. A character like ?A, ?B etc."
372 :group 'org-keywords
373 :type 'character)
374
375 (defcustom org-deadline-string "DEADLINE:"
376 "String to mark deadline entries.
377 A deadline is this string, followed by a time stamp. Should be a word,
378 terminated by a colon. You can insert a schedule keyword and
379 a timestamp with \\[org-deadline].
380 Changes become only effective after restarting Emacs."
381 :group 'org-keywords
382 :type 'string)
383
384 (defcustom org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 A schedule is this string, followed by a time stamp. Should be a word,
387 terminated by a colon. You can insert a schedule keyword and
388 a timestamp with \\[org-schedule].
389 Changes become only effective after restarting Emacs."
390 :group 'org-keywords
391 :type 'string)
392
393 (defcustom org-comment-string "COMMENT"
394 "Entries starting with this keyword will never be exported.
395 An entry can be toggled between COMMENT and normal with
396 \\[org-toggle-comment].
397 Changes become only effective after restarting Emacs."
398 :group 'org-keywords
399 :type 'string)
400
401 (defcustom org-quote-string "QUOTE"
402 "Entries starting with this keyword will be exported in fixed-width font.
403 Quoting applies only to the text in the entry following the headline, and does
404 not extend beyond the next headline, even if that is lower level.
405 An entry can be toggled between QUOTE and normal with
406 \\[org-toggle-fixed-width-section]"
407 :group 'org-keywords
408 :type 'string)
409
410 (defcustom org-after-todo-state-change-hook nil
411 "Hook which is run after the state of a TODO item was changed.
412 The new state (a string with a todo keyword, or nil) is available in the
413 Lisp variable `state'."
414 :group 'org-keywords
415 :type 'hook)
416
417 ;; Variables for pre-computed regular expressions, all buffer local
418 (defvar org-todo-kwd-priority-p nil
419 "Do TODO items have priorities?")
420 (make-variable-buffer-local 'org-todo-kwd-priority-p)
421 (defvar org-todo-kwd-max-priority nil
422 "Maximum priority of TODO items.")
423 (make-variable-buffer-local 'org-todo-kwd-max-priority)
424 (defvar org-ds-keyword-length 12
425 "Maximum length of the Deadline and SCHEDULED keywords.")
426 (make-variable-buffer-local 'org-ds-keyword-length)
427 (defvar org-done-string nil
428 "The last string in `org-todo-keywords', indicating an item is DONE.")
429 (make-variable-buffer-local 'org-done-string)
430 (defvar org-todo-regexp nil
431 "Matches any of the TODO state keywords.")
432 (make-variable-buffer-local 'org-todo-regexp)
433 (defvar org-not-done-regexp nil
434 "Matches any of the TODO state keywords except the last one.")
435 (make-variable-buffer-local 'org-not-done-regexp)
436 (defvar org-todo-line-regexp nil
437 "Matches a headline and puts TODO state into group 2 if present.")
438 (make-variable-buffer-local 'org-todo-line-regexp)
439 (defvar org-nl-done-regexp nil
440 "Matches newline followed by a headline with the DONE keyword.")
441 (make-variable-buffer-local 'org-nl-done-regexp)
442 (defvar org-looking-at-done-regexp nil
443 "Matches the DONE keyword a point.")
444 (make-variable-buffer-local 'org-looking-at-done-regexp)
445 (defvar org-deadline-regexp nil
446 "Matches the DEADLINE keyword.")
447 (make-variable-buffer-local 'org-deadline-regexp)
448 (defvar org-deadline-time-regexp nil
449 "Matches the DEADLINE keyword together with a time stamp.")
450 (make-variable-buffer-local 'org-deadline-time-regexp)
451 (defvar org-deadline-line-regexp nil
452 "Matches the DEADLINE keyword and the rest of the line.")
453 (make-variable-buffer-local 'org-deadline-line-regexp)
454 (defvar org-scheduled-regexp nil
455 "Matches the SCHEDULED keyword.")
456 (make-variable-buffer-local 'org-scheduled-regexp)
457 (defvar org-scheduled-time-regexp nil
458 "Matches the SCHEDULED keyword together with a time stamp.")
459 (make-variable-buffer-local 'org-scheduled-time-regexp)
460
461 (defvar org-category nil
462 "Variable used by org files to set a category for agenda display.
463 Such files should use a file variable to set it, for example
464
465 -*- mode: org; org-category: \"ELisp\"
466
467 or contain a special line
468
469 #+CATEGORY: ELisp
470
471 If the file does not specify a category, then file's base name
472 is used instead.")
473
474 (defun org-set-regexps-and-options ()
475 "Precompute regular expressions for current buffer."
476 (when (eq major-mode 'org-mode)
477 (let ((re (org-make-options-regexp
478 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
479 "STARTUP" "ARCHIVE")))
480 (splitre "[ \t]+")
481 kwds int key value cat arch)
482 (save-excursion
483 (save-restriction
484 (widen)
485 (goto-char (point-min))
486 (while (re-search-forward re nil t)
487 (setq key (match-string 1) value (match-string 2))
488 (cond
489 ((equal key "CATEGORY")
490 (if (string-match "[ \t]+$" value)
491 (setq value (replace-match "" t t value)))
492 (setq cat (intern value)))
493 ((equal key "SEQ_TODO")
494 (setq int 'sequence
495 kwds (append kwds (org-split-string value splitre))))
496 ((equal key "PRI_TODO")
497 (setq int 'priority
498 kwds (append kwds (org-split-string value splitre))))
499 ((equal key "TYP_TODO")
500 (setq int 'type
501 kwds (append kwds (org-split-string value splitre))))
502 ((equal key "STARTUP")
503 (let ((opts (org-split-string value splitre))
504 (set '(("fold" org-startup-folded t)
505 ("nofold" org-startup-folded nil)
506 ("content" org-startup-folded content)
507 ("dlcheck" org-startup-with-deadline-check t)
508 ("nodlcheck" org-startup-with-deadline-check nil)))
509 l var val)
510 (while (setq l (assoc (pop opts) set))
511 (setq var (nth 1 l) val (nth 2 l))
512 (set (make-local-variable var) val))))
513 ((equal key "ARCHIVE")
514 (string-match " *$" value)
515 (setq arch (replace-match "" t t value))
516 (remove-text-properties 0 (length arch)
517 '(face t fontified t) arch)))
518 )))
519 (and cat (set (make-local-variable 'org-category) cat))
520 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
521 (and arch (set (make-local-variable 'org-archive-location) arch))
522 (and int (set (make-local-variable 'org-todo-interpretation) int)))
523 ;; Compute the regular expressions and other local variables
524 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
525 org-todo-kwd-max-priority (1- (length org-todo-keywords))
526 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
527 (length org-scheduled-string)))
528 org-done-string
529 (nth (1- (length org-todo-keywords)) org-todo-keywords)
530 org-todo-regexp
531 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
532 "\\|") "\\)\\>")
533 org-not-done-regexp
534 (concat "\\<\\("
535 (mapconcat 'regexp-quote
536 (nreverse (cdr (reverse org-todo-keywords)))
537 "\\|")
538 "\\)\\>")
539 org-todo-line-regexp
540 (concat "^\\(\\*+\\)[ \t]*\\("
541 (mapconcat 'regexp-quote org-todo-keywords "\\|")
542 "\\)? *\\(.*\\)")
543 org-nl-done-regexp
544 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
545 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
546 org-deadline-regexp (concat "\\<" org-deadline-string)
547 org-deadline-time-regexp
548 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
549 org-deadline-line-regexp
550 (concat "\\<\\(" org-deadline-string "\\).*")
551 org-scheduled-regexp
552 (concat "\\<" org-scheduled-string)
553 org-scheduled-time-regexp
554 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
555 (org-set-font-lock-defaults)))
556
557 (defgroup org-time nil
558 "Options concerning time stamps and deadlines in Org-mode."
559 :tag "Org Time"
560 :group 'org)
561
562 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
563 "Formats for `format-time-string' which are used for time stamps.
564 It is not recommended to change this constant.")
565
566
567 (defcustom org-deadline-warning-days 30
568 "No. of days before expiration during which a deadline becomes active.
569 This variable governs the display in the org file."
570 :group 'org-time
571 :type 'number)
572
573 (defcustom org-popup-calendar-for-date-prompt t
574 "Non-nil means, pop up a calendar when prompting for a date.
575 In the calendar, the date can be selected with mouse-1. However, the
576 minibuffer will also be active, and you can simply enter the date as well.
577 When nil, only the minibuffer will be available."
578 :group 'org-time
579 :type 'number)
580
581 (defcustom org-calendar-follow-timestamp-change t
582 "Non-nil means, make the calendar window follow timestamp changes.
583 When a timestamp is modified and the calendar window is visible, it will be
584 moved to the new date."
585 :group 'org-time
586 :type 'boolean)
587
588 (defgroup org-agenda nil
589 "Options concerning agenda display Org-mode."
590 :tag "Org Agenda"
591 :group 'org)
592
593 (defcustom org-agenda-files nil
594 "A list of org files for agenda/diary display.
595 Entries are added to this list with \\[org-add-file] and removed with
596 \\[org-remove-file]. You can also use customize to edit the list."
597 :group 'org-agenda
598 :type '(repeat file))
599
600 (defcustom org-select-timeline-window t
601 "Non-nil means, after creating a timeline, move cursor into Timeline window.
602 When nil, cursor will remain in the current window."
603 :group 'org-agenda
604 :type 'boolean)
605
606 (defcustom org-select-agenda-window t
607 "Non-nil means, after creating an agenda, move cursor into Agenda window.
608 When nil, cursor will remain in the current window."
609 :group 'org-agenda
610 :type 'boolean)
611
612 (defcustom org-fit-agenda-window t
613 "Non-nil means, change window size of agenda to fit content."
614 :group 'org-agenda
615 :type 'boolean)
616
617 (defcustom org-agenda-show-all-dates t
618 "Non-nil means, `org-agenda' shows every day in the selected range.
619 When nil, only the days which actually have entries are shown."
620 :group 'org-agenda
621 :type 'boolean)
622
623 ;; FIXME: First day of month works only for current month because it would
624 ;; require a variable ndays treatment.
625 (defcustom org-agenda-start-on-weekday 1
626 "Non-nil means, start the overview always on the specified weekday.
627 0 Denotes Sunday, 1 denotes Monday etc.
628 When nil, always start on the current day."
629 :group 'org-agenda
630 :type '(choice (const :tag "Today" nil)
631 (const :tag "First day of month" t)
632 (number :tag "Weekday No.")))
633
634 (defcustom org-agenda-ndays 7
635 "Number of days to include in overview display."
636 :group 'org-agenda
637 :type 'number)
638
639 (defcustom org-agenda-include-all-todo t
640 "Non-nil means, the agenda will always contain all TODO entries.
641 When nil, date-less entries will only be shown if `org-agenda' is called
642 with a prefix argument.
643 When non-nil, the TODO entries will be listed at the top of the agenda, before
644 the entries for specific days."
645 :group 'org-agenda
646 :type 'boolean)
647
648 (defcustom org-agenda-include-diary nil
649 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
650 :group 'org-agenda
651 :type 'boolean)
652
653 (defcustom org-calendar-to-agenda-key [?c]
654 "The key to be installed in `calendar-mode-map' for switching to the agenda.
655 The command `org-calendar-goto-agenda' will be bound to this key. The
656 default is the character `c' because then`c' can be used to switch back and
657 force between agenda and calendar."
658 :group 'org-agenda
659 :type 'sexp)
660
661 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
662 "Sorting structure for the agenda items of a single day.
663 This is a list of symbols which will be used in sequence to determine
664 if an entry should be listed before another entry. The following
665 symbols are recognized.
666
667 time-up Put entries with time-of-day indications first, early first
668 time-down Put entries with time-of-day indications first, late first
669 category-keep Keep the default order of categories, corresponding to the
670 sequence in `org-agenda-files'.
671 category-up Sort alphabetically by category, A-Z.
672 category-down Sort alphabetically by category, Z-A.
673 priority-up Sort numerically by priority, high priority last.
674 priority-down Sort numerically by priority, high priority first.
675
676 The different possibilities will be tried in sequence, and testing stops
677 if one comparison returns a \"not-equal\". For example, the default
678 '(time-up category-keep priority-down)
679 means: Pull out all entries having a specified time of day and sort them,
680 in order to make a time schedule for the current day the first thing in the
681 agenda listing for the day. Of the entries without a time indication, keep
682 the grouped in categories, don't sort the categories, but keep them in
683 the sequence given in `org-agenda-files'. Within each category sort by
684 priority.
685
686 Leaving out `category-keep' would mean that items will be sorted across
687 categories by priority."
688 :group 'org-agenda
689 :type '(repeat
690 (choice
691 (const time-up)
692 (const time-down)
693 (const category-keep)
694 (const category-up)
695 (const category-down)
696 (const priority-up)
697 (const priority-down))))
698
699 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
700 "Format specification for the prefix of items in the agenda buffer.
701 This format works similar to a printf format, with the following meaning:
702
703 %c the category of the item, \"Diary\" for entries from the diary, or
704 as given by the CATEGORY keyword or derived from the file name.
705 %t the time-of-day specification if one applies to the entry, in the
706 format HH:MM
707 %s Scheduling/Deadline information, a short string
708
709 All specifiers work basically like the standard `%s' of printf, but may
710 contain two additional characters: A question mark just after the `%' and
711 a whitespace/punctuation character just before the final letter.
712
713 If the first character after `%' is a question mark, the entire field
714 will only be included if the corresponding value applies to the
715 current entry. This is useful for fields which should have fixed
716 width when present, but zero width when absent. For example,
717 \"%?-12t\" will result in a 12 character time field if a time of the
718 day is specified, but will completely disappear in entries which do
719 not contain a time.
720
721 If there is punctuation or whitespace character just before the final
722 format letter, this character will be appended to the field value if
723 the value is not empty. For example, the format \"%-12:c\" leads to
724 \"Diary: \" if the category is \"Diary\". If the category were be
725 empty, no additional colon would be interted.
726
727 The default value of this option is \" %-12:c%?-12t% s\", meaning:
728 - Indent the line with two space characters
729 - Give the category in a 12 chars wide field, padded with whitespace on
730 the right (because of `-'). Append a colon if there is a category
731 (because of `:').
732 - If there is a time-of-day, put it into a 12 chars wide field. If no
733 time, don't put in an empty field, just skip it (because of '?').
734 - Finally, put the scheduling information and append a whitespace.
735
736 As another example, if you don't want the time-of-day of entries in
737 the prefix, you could use:
738
739 (setq org-agenda-prefix-format \" %-11:c% s\")
740
741 See also the variable `org-agenda-remove-times-when-in-prefix'."
742 :type 'string
743 :group 'org-agenda)
744
745 (defcustom org-timeline-prefix-format " % s"
746 "Like `org-agenda-prefix-format', but for the timeline of a single file."
747 :type 'string
748 :group 'org-agenda)
749
750 (defvar org-prefix-format-compiled nil
751 "The compiled version of the most recently used prefix format.
752 Depending on which command was used last, this may be the compiled version
753 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
754
755 (defcustom org-agenda-use-time-grid t
756 "Non-nil means, show a time grid in the agenda schedule.
757 A time grid is a set of lines for specific times (like every two hours between
758 8:00 and 20:00. The items scheduled for a day at specific times are
759 sorted in between these lines.
760 For deails about when the grid will be shown, and what it will look like, see
761 the variable `org-agenda-time-grid'."
762 :group 'org-agenda
763 :type 'boolean)
764
765 (defcustom org-agenda-time-grid
766 '((daily today require-timed)
767 "----------------"
768 (800 1000 1200 1400 1600 1800 2000))
769
770 "The settings for time grid for agenda display.
771 This is a list of three items. The first item is again a list. It contains
772 symbols specifying conditions when the grid should be displayed:
773
774 daily if the agenda shows a single day
775 weekly if the agenda shows an entire week
776 today show grid on current date, independent of daily/weekly display
777 require-timed show grid only if at least on item has a time specification
778
779 The second item is a string which will be places behing the grid time.
780
781 The third item is a list of integers, indicating the times that should have
782 a grid line."
783 :group 'org-agenda
784 :type
785 '(list
786 (set :greedy t :tag "Grid Display Options"
787 (const :tag "Show grid in single day agenda display" daily)
788 (const :tag "Show grid in weekly agenda display" weekly)
789 (const :tag "Always show grid for today" today)
790 (const :tag "Show grid only if any timed entries are present"
791 require-timed)
792 (const :tag "Skip grid times already present in an entry"
793 remove-match))
794 (string :tag "Grid String")
795 (repeat :tag "Grid Times" (integer :tag "Time"))))
796
797 (defcustom org-agenda-remove-times-when-in-prefix t
798 "Non-nil means, remove duplicate time specifications in agenda items.
799 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
800 time-of-day specification in a headline or diary entry is extracted and
801 placed into the prefix. If this option is non-nil, the original specification
802 \(a timestamp or -range, or just a plain time(range) specification like
803 11:30-4pm) will be removed for agenda display. This makes the agenda less
804 cluttered.
805 The option can be t or nil. It may also be the symbol `beg', indicating
806 that the time should only be removed what it is located at the beginning of
807 the headline/diary entry."
808 :group 'org-agenda
809 :type '(choice
810 (const :tag "Always" t)
811 (const :tag "Never" nil)
812 (const :tag "When at beginning of entry" beg)))
813
814 (defcustom org-sort-agenda-notime-is-late t
815 "Non-nil means, items without time are considered late.
816 This is only relevant for sorting. When t, items which have no explicit
817 time like 15:30 will be considered as 24:01, i.e. later than any items which
818 do have a time. When nil, the default time is before 0:00. You can use this
819 option to decide if the schedule for today should come before or after timeless
820 agenda entries."
821 :group 'org-agenda
822 :type 'boolean)
823
824 (defgroup org-structure nil
825 "Options concerning structure editing in Org-mode."
826 :tag "Org Structure"
827 :group 'org)
828
829 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
830 "Hook that is run after `org-cycle' has changed the buffer visibility.
831 The function(s) in this hook must accept a single argument which indicates
832 the new state that was set by the most recent `org-cycle' command. The
833 argument is a symbol. After a global state change, it can have the values
834 `overview', `content', or `all'. After a local state change, it can have
835 the values `folded', `children', or `subtree'."
836 :group 'org-structure
837 :type 'hook)
838
839 (defcustom org-occur-hook '(org-first-headline-recenter)
840 "Hook that is run after `org-occur' has constructed a sparse tree.
841 This can be used to recenter the window to show as much of the structure
842 as possible."
843 :group 'org-structure
844 :type 'hook)
845
846 (defcustom org-adapt-indentation t
847 "Non-nil means, adapt indentation when promoting and demoting.
848 When this is set and the *entire* text in an entry is indented, the
849 indentation is increased by one space in a demotion command, and
850 decreased by one in a promotion command. If any line in the entry
851 body starts at column 0, indentation is not changed at all."
852 :group 'org-structure
853 :type 'boolean)
854
855 (defcustom org-cycle-emulate-tab t
856 "Where should `org-cycle' emulate TAB.
857 nil Never
858 white Only in completely white lines
859 t Everywhere except in headlines"
860 :group 'org-structure
861 :type '(choice (const :tag "Never" nil)
862 (const :tag "Only in completely white lines" white)
863 (const :tag "Everywhere except in headlines" t)
864 ))
865
866 (defcustom org-show-following-heading t
867 "Non-nil means, show heading following match in `org-occur'.
868 When doing an `org-occur' it is useful to show the headline which
869 follows the match, even if they do not match the regexp. This makes it
870 easier to edit directly inside the sparse tree. However, if you use
871 org-occur mainly as an overview, the following headlines are
872 unnecessary clutter."
873 :group 'org-structure
874 :type 'boolean)
875
876 (defcustom org-archive-location "%s_archive::"
877 "The location where subtrees should be archived.
878 This string consists of two parts, separated by a double-colon.
879
880 The first part is a file name - when omitted, archiving happens in the same
881 file. %s will be replaced by the current file name (without directory part).
882 Archiving to a different file is useful to keep archived entries from
883 contributing to the Org-mode Agenda.
884
885 The part after the double colon is a headline. The archived entries will be
886 filed under that headline. When omitted, the subtrees are simply filed away
887 at the end of the file, as top-level entries.
888
889 Here are a few examples:
890 \"%s_archive::\"
891 If the current file is Projects.org, archive in file
892 Projects.org_archive, as top-level trees. This is the default.
893
894 \"::* Archived Tasks\"
895 Archive in the current file, under the top-level headline
896 \"* Archived Tasks\".
897
898 \"~/org/archive.org::\"
899 Archive in file ~/org/archive.org (absolute path), as top-level trees.
900
901 \"basement::** Finished Tasks\"
902 Archive in file ./basement (relative path), as level 3 trees
903 below the level 2 heading \"** Finished Tasks\".
904
905 You may set this option on a per-file basis by adding to the buffer a
906 line like
907
908 #+ARCHIVE: basement::** Finished Tasks"
909 :group 'org-structure
910 :type 'string)
911
912 (defcustom org-archive-mark-done t
913 "Non-nil means, mark archived entries as DONE."
914 :group 'org-structure
915 :type 'boolean)
916
917 (defcustom org-archive-stamp-time t
918 "Non-nil means, add a time stamp to archived entries.
919 The time stamp will be added directly after the TODO state keyword in the
920 first line, so it is probably best to use this in combinations with
921 `org-archive-mark-done'."
922 :group 'org-structure
923 :type 'boolean)
924
925 (defgroup org-link nil
926 "Options concerning links in Org-mode."
927 :tag "Org Link"
928 :group 'org)
929
930 (defcustom org-link-format "<%s>"
931 "Default format for linkes in the buffer.
932 This is a format string for printf, %s will be replaced by the link text.
933 If you want to make sure that your link is always properly terminated,
934 include angle brackets into this format, like \"<%s>\". Some people also
935 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
936 :group 'org-link
937 :type '(choice
938 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
939 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
940 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
941 (string :tag "Other" :value "<%s>")))
942
943 (defcustom org-allow-space-in-links t
944 "Non-nil means, file names in links may contain space characters.
945 When nil, it becomes possible to put several links into a line.
946 Note that in tables, a link never extends accross fields, so in a table
947 it is always possible to put several links into a line.
948 Changing this varable requires a re-launch of Emacs of become effective."
949 :group 'org-link
950 :type 'boolean)
951
952 (defcustom org-line-numbers-in-file-links t
953 "Non-nil means, file links from `org-store-link' contain line numbers.
954 The line number will be added to the file name with :NNN and interpreted
955 by the command `org-open-at-point'.
956 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
957 negates this setting for the duration of the command."
958 :group 'org-link
959 :type 'boolean)
960
961 (defcustom org-keep-stored-link-after-insertion nil
962 "Non-nil means, keep link in list for entire session.
963
964 The command `org-store-link' adds a link pointing to the current
965 location to an internal list. These links accumulate during a session.
966 The command `org-insert-link' can be used to insert links into any
967 Org-mode file (offering completion for all stored links). When this
968 option is nil, every link which has been inserted once using \\[org-insert-link]
969 will be removed from the list, to make completing the unused links
970 more efficient."
971 :group 'org-link
972 :type 'boolean)
973
974 (defcustom org-link-frame-setup
975 '((vm . vm-visit-folder-other-frame)
976 (gnus . gnus-other-frame)
977 (file . find-file-other-window))
978 "Setup the frame configuration for following links.
979 When following a link with Emacs, it may often be useful to display
980 this link in another window or frame. This variable can be used to
981 set this up for the different types of links.
982 For VM, use any of
983 `vm-visit-folder'
984 `vm-visit-folder-other-frame'
985 For Gnus, use any of
986 `gnus'
987 `gnus-other-frame'
988 For FILE, use any of
989 `find-file'
990 `find-file-other-window'
991 `find-file-other-frame'
992 For the calendar, use the variable `calendar-setup'.
993 For BBDB, it is currently only possible to display the matches in
994 another window."
995 :group 'org-link
996 :type '(list
997 (cons (const vm)
998 (choice
999 (const vm-visit-folder)
1000 (const vm-visit-folder-other-window)
1001 (const vm-visit-folder-other-frame)))
1002 (cons (const gnus)
1003 (choice
1004 (const gnus)
1005 (const gnus-other-frame)))
1006 (cons (const file)
1007 (choice
1008 (const find-file)
1009 (const find-file-other-window)
1010 (const find-file-other-frame)))))
1011
1012 (defcustom org-usenet-links-prefer-google nil
1013 "Non-nil means, `org-store-link' will create web links to google groups.
1014 When nil, Gnus will be used for such links.
1015 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1016 negates this setting for the duration of the command."
1017 :group 'org-link
1018 :type 'boolean)
1019
1020 (defcustom org-open-non-existing-files nil
1021 "Non-nil means, `org-open-file' will open non-existing file.
1022 When nil, an error will be generated."
1023 :group 'org-link
1024 :type 'boolean)
1025
1026 (defcustom org-confirm-shell-links t
1027 "Non-nil means, ask for confirmation before executing shell links.
1028 The default is true, to keep new users from shooting into their own foot."
1029 :group 'org-link
1030 :type 'boolean)
1031
1032 (defconst org-file-apps-defaults-gnu
1033 '((t . emacs)
1034 ("jpg" . "xv %s")
1035 ("gif" . "xv %s")
1036 ("ppm" . "xv %s")
1037 ("pgm" . "xv %s")
1038 ("pbm" . "xv %s")
1039 ("tif" . "xv %s")
1040 ("png" . "xv %s")
1041 ("ps" . "gv %s")
1042 ("ps.gz" . "gv %s")
1043 ("eps" . "gv %s")
1044 ("eps.gz" . "gv %s")
1045 ("dvi" . "xdvi %s")
1046 ("mpeg" . "plaympeg %s")
1047 ("mp3" . "plaympeg %s")
1048 ("fig" . "xfig %s")
1049 ("pdf" . "acroread %s")
1050 ("doc" . "soffice %s")
1051 ("ppt" . "soffice %s")
1052 ("pps" . "soffice %s")
1053 ("html" . "netscape -remote openURL(%s,new-window)")
1054 ("htm" . "netscape -remote openURL(%s,new-window)")
1055 ("xs" . "soffice %s"))
1056 "Default file applications on a UNIX/LINUX system.
1057 See `org-file-apps'.")
1058
1059 (defconst org-file-apps-defaults-macosx
1060 '((t . "open %s")
1061 ("ps" . "gv %s")
1062 ("ps.gz" . "gv %s")
1063 ("eps" . "gv %s")
1064 ("eps.gz" . "gv %s")
1065 ("dvi" . "xdvi %s")
1066 ("fig" . "xfig %s"))
1067 "Default file applications on a MacOS X system.
1068 The system \"open\" is known as a default, but we use X11 applications
1069 for some files for which the OS does not have a good default.
1070 See `org-file-apps'.")
1071
1072 (defconst org-file-apps-defaults-windowsnt
1073 '((t . (w32-shell-execute "open" file)))
1074 "Default file applications on a Windows NT system.
1075 The system \"open\" is used for most files.
1076 See `org-file-apps'.")
1077
1078 (defcustom org-file-apps
1079 '(
1080 ("txt" . emacs)
1081 ("tex" . emacs)
1082 ("ltx" . emacs)
1083 ("org" . emacs)
1084 ("el" . emacs)
1085 )
1086 "External applications for opening `file:path' items in a document.
1087 Org-mode uses system defaults for different file types, but
1088 you can use this variable to set the application for a given file
1089 extension. The entries in this list are cons cells with a file extension
1090 and the corresponding command. Possible values for the command are:
1091 `emacs' The file will be visited by the current Emacs process.
1092 `default' Use the default application for this file type.
1093 string A command to be executed by a shell; %s will be replaced
1094 by the path to the file.
1095 sexp A Lisp form which will be evaluated. The file path will
1096 be available in the Lisp variable `file'.
1097 For more examples, see the system specific constants
1098 `org-file-apps-defaults-macosx'
1099 `org-file-apps-defaults-windowsnt'
1100 `org-file-apps-defaults-gnu'."
1101 :group 'org-link
1102 :type '(repeat
1103 (cons (string :tag "Extension")
1104 (choice :value ""
1105 (const :tag "Visit with Emacs" 'emacs)
1106 (const :tag "Use system default" 'default)
1107 (string :tag "Command")
1108 (sexp :tag "Lisp form")))))
1109
1110
1111 (defgroup org-remember nil
1112 "Options concerning interaction with remember.el."
1113 :tag "Org Remember"
1114 :group 'org)
1115
1116 (defcustom org-directory "~/org"
1117 "Directory with org files.
1118 This directory will be used as default to prompt for org files.
1119 Used by the hooks for remember.el."
1120 :group 'org-remember
1121 :type 'directory)
1122
1123 (defcustom org-default-notes-file "~/.notes"
1124 "Default target for storing notes.
1125 Used by the hooks for remember.el. This can be a string, or nil to mean
1126 the value of `remember-data-file'."
1127 :group 'org-remember
1128 :type '(choice
1129 (const :tag "Default from remember-data-file" nil)
1130 file))
1131
1132 (defcustom org-reverse-note-order nil
1133 "Non-nil means, store new notes at the beginning of a file or entry.
1134 When nil, new notes will be filed to the end of a file or entry."
1135 :group 'org-remember
1136 :type '(choice
1137 (const :tag "Reverse always" t)
1138 (const :tag "Reverse never" nil)
1139 (repeat :tag "By file name regexp"
1140 (cons regexp boolean))))
1141
1142 (defgroup org-table nil
1143 "Options concerning tables in Org-mode."
1144 :tag "Org Table"
1145 :group 'org)
1146
1147 (defcustom org-enable-table-editor 'optimized
1148 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1149 When nil, such lines will be treated like ordinary lines.
1150
1151 When equal to the symbol `optimized', the table editor will be optimized to
1152 do the following
1153 - Use automatic overwrite mode in front of whitespace in table fields.
1154 This make the structure of the table stay in tact as long as the edited
1155 field does not exceed the column width.
1156 - Minimize the number of realigns. Normally, the table is aligned each time
1157 TAB or RET are pressed to move to another field. With optimization this
1158 happens only if changes to a field might have changed the column width.
1159 Optimization requires replacing the functions `self-insert-command',
1160 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1161 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1162 very good at guessing when a re-align will be necessary, but you can always
1163 force one with `C-c C-c'.
1164
1165 If you would like to use the optimized version in Org-mode, but the
1166 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1167
1168 This variable can be used to turn on and off the table editor during a session,
1169 but in order to toggle optimization, a restart is required."
1170 :group 'org-table
1171 :type '(choice
1172 (const :tag "off" nil)
1173 (const :tag "on" t)
1174 (const :tag "on, optimized" optimized)))
1175
1176 (defcustom org-table-default-size "5x2"
1177 "The default size for newly created tables, Columns x Rows."
1178 :group 'org-table
1179 :type 'string)
1180
1181 (defcustom org-table-automatic-realign t
1182 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1183 When nil, aligning is only done with \\[org-table-align], or after column
1184 removal/insertion."
1185 :group 'org-table
1186 :type 'boolean)
1187
1188 (defcustom org-table-spaces-around-separators '(1 . 1)
1189 "The number of spaces to be placed before and after separators."
1190 :group 'org-table
1191 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1192
1193 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1194 "The number of spaces to be placed before and after separators.
1195 This option applies when the column separators have been made invisible."
1196 :group 'org-table
1197 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1198
1199 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1200 "Regular expression for recognizing numbers in table columns.
1201 If a table column contains mostly numbers, it will be aligned to the
1202 right. If not, it will be aligned to the left.
1203
1204 The default value of this option is a regular expression which allows
1205 anything which looks remotely like a number as used in scientific
1206 context. For example, all of the following will be considered a
1207 number:
1208 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1209
1210 Other options offered by the customize interface are more restrictive."
1211 :group 'org-table
1212 :type '(choice
1213 (const :tag "Positive Integers"
1214 "^[0-9]+$")
1215 (const :tag "Integers"
1216 "^[-+]?[0-9]+$")
1217 (const :tag "Floating Point Numbers"
1218 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1219 (const :tag "Floating Point Number or Integer"
1220 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1221 (const :tag "Exponential, Floating point, Integer"
1222 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1223 (const :tag "Very General Number-Like"
1224 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1225 (string :tag "Regexp:")))
1226
1227 (defcustom org-table-number-fraction 0.5
1228 "Fraction of numbers in a column required to make the column align right.
1229 In a column all non-white fields are considered. If at least this
1230 fraction of fields is matched by `org-table-number-fraction',
1231 alignment to the right border applies."
1232 :group 'org-table
1233 :type 'number)
1234
1235 (defcustom org-export-highlight-first-table-line t
1236 "Non-nil means, highlight the first table line.
1237 In HTML export, this means use <th> instead of <td>.
1238 In tables created with table.el, this applies to the first table line.
1239 In Org-mode tables, all lines before the first horizontal separator
1240 line will be formatted with <th> tags."
1241 :group 'org-table
1242 :type 'boolean)
1243
1244 (defcustom org-table-tab-recognizes-table.el t
1245 "Non-nil means, TAB will automatically notice a table.el table.
1246 When it sees such a table, it moves point into it and - if necessary -
1247 calls `table-recognize-table'."
1248 :group 'org-table
1249 :type 'boolean)
1250
1251 ;; FIXME: Should this one be in another group? Which one?
1252 (defcustom org-enable-fixed-width-editor t
1253 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1254 This currently only means, they are never auto-wrapped.
1255 When nil, such lines will be treated like ordinary lines."
1256 :group 'org-table
1257 :type 'boolean)
1258
1259 (defgroup org-table-calculation nil
1260 "Options concerning tables in Org-mode."
1261 :tag "Org Table Calculation"
1262 :group 'org)
1263
1264 (defcustom org-table-copy-increment t
1265 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1266 :group 'org-table-calculation
1267 :type 'boolean)
1268
1269 (defcustom org-calc-default-modes
1270 '(calc-internal-prec 12
1271 calc-float-format (float 5)
1272 calc-angle-mode deg
1273 calc-prefer-frac nil
1274 calc-symbolic-mode nil
1275 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1276 calc-display-working-message t
1277 )
1278 "List with Calc mode settings for use in calc-eval for table formulas.
1279 The list must contain alternating symbols (calc modes variables and values.
1280 Don't remove any of the default settings, just change the values. Org-mode
1281 relies on the variables to be present in the list."
1282 :group 'org-table-calculation
1283 :type 'plist)
1284
1285 (defcustom org-table-formula-evaluate-inline t
1286 "Non-nil means, TAB and RET evaluate a formula in current table field.
1287 If the current field starts with an equal sign, it is assumed to be a formula
1288 which should be evaluated as described in the manual and in the documentation
1289 string of the command `org-table-eval-formula'. This feature requires the
1290 Emacs calc package.
1291 When this variable is nil, formula calculation is only available through
1292 the command \\[org-table-eval-formula]."
1293 :group 'org-table-calculation
1294 :type 'boolean)
1295
1296
1297 (defcustom org-table-formula-use-constants t
1298 "Non-nil means, interpret constants in formulas in tables.
1299 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1300 by the value given in `org-table-formula-constants', or by a value obtained
1301 from the `constants.el' package."
1302 :group 'org-table-calculation
1303 :type 'boolean)
1304
1305 (defcustom org-table-formula-constants nil
1306 "Alist with constant names and values, for use in table formulas.
1307 The car of each element is a name of a constant, without the `$' before it.
1308 The cdr is the value as a string. For example, if you'd like to use the
1309 speed of light in a formula, you would configure
1310
1311 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1312
1313 and then use it in an equation like `$1*$c'."
1314 :group 'org-table-calculation
1315 :type '(repeat
1316 (cons (string :tag "name")
1317 (string :tag "value"))))
1318
1319 (defcustom org-table-formula-numbers-only nil
1320 "Non-nil means, calculate only with numbers in table formulas.
1321 Then all input fields will be converted to a number, and the result
1322 must also be a number. When nil, calc's full potential is available
1323 in table calculations, including symbolics etc."
1324 :group 'org-table-calculation
1325 :type 'boolean)
1326
1327 (defcustom org-table-allow-automatic-line-recalculation t
1328 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1329 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1330 :group 'org-table-calculation
1331 :type 'boolean)
1332
1333 (defgroup org-export nil
1334 "Options for exporting org-listings."
1335 :tag "Org Export"
1336 :group 'org)
1337
1338 (defcustom org-export-language-setup
1339 '(("en" "Author" "Date" "Table of Contents")
1340 ("da" "Ophavsmand" "Dato" "Indhold")
1341 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1342 ("es" "Autor" "Fecha" "\xccndice")
1343 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1344 ("it" "Autore" "Data" "Indice")
1345 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1346 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1347 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1348 "Terms used in export text, translated to different languages.
1349 Use the variable `org-export-default-language' to set the language,
1350 or use the +OPTION lines for a per-file setting."
1351 :group 'org-export
1352 :type '(repeat
1353 (list
1354 (string :tag "HTML language tag")
1355 (string :tag "Author")
1356 (string :tag "Date")
1357 (string :tag "Table of Contents"))))
1358
1359 (defcustom org-export-default-language "en"
1360 "The default language of HTML export, as a string.
1361 This should have an association in `org-export-language-setup'"
1362 :group 'org-export
1363 :type 'string)
1364
1365 (defcustom org-export-headline-levels 3
1366 "The last level which is still exported as a headline.
1367 Inferior levels will produce itemize lists when exported.
1368 Note that a numeric prefix argument to an exporter function overrides
1369 this setting.
1370
1371 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1372 :group 'org-export
1373 :type 'number)
1374
1375 (defcustom org-export-with-section-numbers t
1376 "Non-nil means, add section numbers to headlines when exporting.
1377
1378 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1379 :group 'org-export
1380 :type 'boolean)
1381
1382 (defcustom org-export-with-toc t
1383 "Non-nil means, create a table of contents in exported files.
1384 The TOC contains headlines with levels up to`org-export-headline-levels'.
1385
1386 Headlines which contain any TODO items will be marked with \"(*)\" in
1387 ASCII export, and with red color in HTML output.
1388
1389 In HTML output, the TOC will be clickable.
1390
1391 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1392 :group 'org-export
1393 :type 'boolean)
1394
1395 (defcustom org-export-preserve-breaks nil
1396 "Non-nil means, preserve all line breaks when exporting.
1397 Normally, in HTML output paragraphs will be reformatted. In ASCII
1398 export, line breaks will always be preserved, regardless of this variable.
1399
1400 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1401 :group 'org-export
1402 :type 'boolean)
1403
1404 (defcustom org-export-html-inline-images t
1405 "Non-nil means, inline images into exported HTML pages.
1406 The link will still be to the original location of the image file.
1407 So if you are moving the page, lets say to your public HTML site,
1408 you will have to move the image and maybe change the link."
1409 :group 'org-export
1410 :type 'boolean)
1411
1412 (defcustom org-export-html-expand t
1413 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1414 When nil, these tags will be exported as plain text and therefore
1415 not be interpreted by a browser.
1416
1417 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1418 :group 'org-export
1419 :type 'boolean)
1420
1421 (defcustom org-export-with-fixed-width t
1422 "Non-nil means, lines starting with \":\" will be in fixed width font.
1423 This can be used to have pre-formatted text, fragments of code etc. For
1424 example
1425 : ;; Some Lisp examples
1426 : (while (defc cnt)
1427 : (ding))
1428 will be looking just like this in also HTML. In ASCII export, this option
1429 has no effect.
1430
1431 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1432 :group 'org-export
1433 :type 'boolean)
1434
1435 (defcustom org-export-with-tables t
1436 "If non-nil, lines starting with \"|\" define a table.
1437 For example:
1438
1439 | Name | Address | Birthday |
1440 |-------------+----------+-----------|
1441 | Arthur Dent | England | 29.2.2100 |
1442
1443 In ASCII export, this option has no effect.
1444
1445 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1446 :group 'org-export
1447 :type 'boolean)
1448
1449 (defcustom org-export-prefer-native-exporter-for-tables nil
1450 "Non-nil means, always export tables created with table.el natively.
1451 Natively means, use the HTML code generator in table.el.
1452 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1453 the table does not use row- or column-spanning). This has the
1454 advantage, that the automatic HTML conversions for math symbols and
1455 sub/superscripts can be applied. Org-mode's HTML generator is also
1456 much faster."
1457 :group 'org-export
1458 :type 'boolean)
1459
1460 (defcustom org-export-html-table-tag
1461 "<table border=1 cellspacing=0 cellpadding=6>"
1462 "The HTML tag used to start a table.
1463 This must be a <table> tag, but you may change the options like
1464 borders and spacing."
1465 :group 'org-export
1466 :type 'string)
1467
1468 (defcustom org-export-with-emphasize t
1469 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1470 If the export target supports emphasizing text, the word will be
1471 typeset in bold, italic, or underlined, respectively. Works only for
1472 single words, but you can say: I *really* *mean* *this*.
1473 In ASCII export, this option has no effect.
1474
1475 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1476 :group 'org-export
1477 :type 'boolean)
1478
1479 (defcustom org-match-sexp-depth 3
1480 "Number of stacked braces for sub/superscript matching.
1481 This has to be set before loading org.el to be effective."
1482 :group 'org-export
1483 :type 'integer)
1484
1485 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1486 (defcustom org-export-with-sub-superscripts t
1487 "Non-nil means, interpret \"_\" and \"^\" for export.
1488 When this option is turned on, you can use TeX-like syntax for sub- and
1489 superscripts. Several characters after \"_\" or \"^\" will be
1490 considered as a single item - so grouping with {} is normally not
1491 needed. For example, the following things will be parsed as single
1492 sub- or superscripts.
1493
1494 10^24 or 10^tau several digits will be considered 1 item
1495 10^-12 or 10^-tau a leading sign with digits or a word
1496 x^2-y^3 will be read as x^2 - y^3, because items are
1497 terminated by almost any nonword/nondigit char.
1498 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1499
1500 Still, ambiguity is possible - so when in doubt use {} to enclose the
1501 sub/superscript.
1502 In ASCII export, this option has no effect.
1503
1504 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1505 :group 'org-export
1506 :type 'boolean)
1507
1508 (defcustom org-export-with-TeX-macros t
1509 "Non-nil means, interpret simple TeX-like macros when exporting.
1510 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1511 No only real TeX macros will work here, but the standard HTML entities
1512 for math can be used as macro names as well. For a list of supported
1513 names in HTML export, see the constant `org-html-entities'.
1514 In ASCII export, this option has no effect.
1515
1516 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1517 :group 'org-export
1518 :type 'boolean)
1519
1520 (defcustom org-export-html-with-timestamp nil
1521 "If non-nil, write `org-export-html-html-helper-timestamp'
1522 into the exported html text. Otherwise, the buffer will just be saved
1523 to a file."
1524 :group 'org-export
1525 :type 'boolean)
1526
1527 (defcustom org-export-html-html-helper-timestamp
1528 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1529 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1530 :group 'org-export
1531 :type 'string)
1532
1533 (defcustom org-export-ascii-show-new-buffer t
1534 "Non-nil means, popup buffer containing the exported ASCII text.
1535 Otherwise the buffer will just be saved to a file and stay hidden."
1536 :group 'org-export
1537 :type 'boolean)
1538
1539 (defcustom org-export-html-show-new-buffer nil
1540 "Non-nil means, popup buffer containing the exported html text.
1541 Otherwise, the buffer will just be saved to a file and stay hidden."
1542 :group 'org-export
1543 :type 'boolean)
1544
1545 (defgroup org-faces nil
1546 "Faces for highlighting in Org-mode."
1547 :tag "Org Faces"
1548 :group 'org)
1549
1550 (defface org-level-1 ;; font-lock-function-name-face
1551 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1552 (((class color) (background light)) (:foreground "Blue"))
1553 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1554 (t (:inverse-video t :bold t)))
1555 "Face used for level 1 headlines."
1556 :group 'org-faces)
1557
1558 (defface org-level-2 ;; font-lock-variable-name-face
1559 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1560 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1561 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1562 (t (:bold t :italic t)))
1563 "Face used for level 2 headlines."
1564 :group 'org-faces)
1565
1566 (defface org-level-3 ;; font-lock-keyword-face
1567 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1568 (((class color) (background light)) (:foreground "Purple"))
1569 (((class color) (background dark)) (:foreground "Cyan"))
1570 (t (:bold t)))
1571 "Face used for level 3 headlines."
1572 :group 'org-faces)
1573
1574 (defface org-level-4 ;; font-lock-comment-face
1575 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1576 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1577 (((class color) (background light)) (:foreground "Firebrick"))
1578 (((class color) (background dark)) (:foreground "chocolate1"))
1579 (t (:bold t :italic t)))
1580 "Face used for level 4 headlines."
1581 :group 'org-faces)
1582
1583 (defface org-level-5 ;; font-lock-type-face
1584 '((((type tty) (class color)) (:foreground "green"))
1585 (((class color) (background light)) (:foreground "ForestGreen"))
1586 (((class color) (background dark)) (:foreground "PaleGreen"))
1587 (t (:bold t :underline t)))
1588 "Face used for level 5 headlines."
1589 :group 'org-faces)
1590
1591 (defface org-level-6 ;; font-lock-constant-face
1592 '((((type tty) (class color)) (:foreground "magenta"))
1593 (((class color) (background light)) (:foreground "CadetBlue"))
1594 (((class color) (background dark)) (:foreground "Aquamarine"))
1595 (t (:bold t :underline t)))
1596 "Face used for level 6 headlines."
1597 :group 'org-faces)
1598
1599 (defface org-level-7 ;; font-lock-builtin-face
1600 '((((type tty) (class color)) (:foreground "blue" :weight light))
1601 (((class color) (background light)) (:foreground "Orchid"))
1602 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1603 (t (:bold t)))
1604 "Face used for level 7 headlines."
1605 :group 'org-faces)
1606
1607 (defface org-level-8 ;; font-lock-string-face
1608 '((((type tty) (class color)) (:foreground "green"))
1609 (((class color) (background light)) (:foreground "RosyBrown"))
1610 (((class color) (background dark)) (:foreground "LightSalmon"))
1611 (t (:italic t)))
1612 "Face used for level 8 headlines."
1613 :group 'org-faces)
1614
1615 (defface org-special-keyword ;; font-lock-string-face
1616 '((((type tty) (class color)) (:foreground "green"))
1617 (((class color) (background light)) (:foreground "RosyBrown"))
1618 (((class color) (background dark)) (:foreground "LightSalmon"))
1619 (t (:italic t)))
1620 "Face used for level 8 headlines."
1621 :group 'org-faces)
1622
1623 (defface org-warning ;; font-lock-warning-face
1624 '((((type tty) (class color)) (:foreground "red"))
1625 (((class color) (background light)) (:foreground "Red" :bold t))
1626 (((class color) (background dark)) (:foreground "Red1" :bold t))
1627 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1628 (t (:inverse-video t :bold t)))
1629 "Face for deadlines and TODO keywords."
1630 :group 'org-faces)
1631
1632 (defcustom org-fontify-done-headline nil
1633 "Non-nil means, change the face of a headline if it is marked DONE.
1634 Normally, only the TODO/DONE keyword indicates the state of a headline.
1635 When this is non-nil, the headline after the keyword is set to the
1636 `org-headline-done' as an additional indication."
1637 :group 'org-faces
1638 :type 'boolean)
1639
1640 (defface org-headline-done ;; font-lock-string-face
1641 '((((type tty) (class color)) (:foreground "green"))
1642 (((class color) (background light)) (:foreground "RosyBrown"))
1643 (((class color) (background dark)) (:foreground "LightSalmon"))
1644 (t (:italic t)))
1645 "Face used to indicate that a headline is DONE. See also the variable
1646 `org-fontify-done-headline'."
1647 :group 'org-faces)
1648
1649 ;; Inheritance does not yet work for xemacs. So we just copy...
1650
1651 (defface org-deadline-announce
1652 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1653 (((class color) (background light)) (:foreground "Blue"))
1654 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1655 (t (:inverse-video t :bold t)))
1656 "Face for upcoming deadlines."
1657 :group 'org-faces)
1658
1659 (defface org-scheduled-today
1660 '((((type tty) (class color)) (:foreground "green"))
1661 (((class color) (background light)) (:foreground "DarkGreen"))
1662 (((class color) (background dark)) (:foreground "PaleGreen"))
1663 (t (:bold t :underline t)))
1664 "Face for items scheduled for a certain day."
1665 :group 'org-faces)
1666
1667 (defface org-scheduled-previously
1668 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1669 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1670 (((class color) (background light)) (:foreground "Firebrick"))
1671 (((class color) (background dark)) (:foreground "chocolate1"))
1672 (t (:bold t :italic t)))
1673 "Face for items scheduled previously, and not yet done."
1674 :group 'org-faces)
1675
1676 (defface org-formula
1677 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1678 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1679 (((class color) (background light)) (:foreground "Firebrick"))
1680 (((class color) (background dark)) (:foreground "chocolate1"))
1681 (t (:bold t :italic t)))
1682 "Face for items scheduled previously, and not yet done."
1683 :group 'org-faces)
1684
1685 (defface org-link
1686 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1687 (((class color) (background light)) (:foreground "Purple"))
1688 (((class color) (background dark)) (:foreground "Cyan"))
1689 (t (:bold t)))
1690 "Face for links."
1691 :group 'org-faces)
1692
1693 (defface org-done ;; font-lock-type-face
1694 '((((type tty) (class color)) (:foreground "green"))
1695 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1696 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1697 (t (:bold t :underline t)))
1698 "Face used for DONE."
1699 :group 'org-faces)
1700
1701 (defface org-table ;; font-lock-function-name-face
1702 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1703 (((class color) (background light)) (:foreground "Blue"))
1704 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1705 (t (:inverse-video t :bold t)))
1706 "Face used for tables."
1707 :group 'org-faces)
1708
1709 (defface org-time-grid ;; font-lock-variable-name-face
1710 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1711 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1712 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1713 (t (:bold t :italic t)))
1714 "Face used for level 2 headlines."
1715 :group 'org-faces)
1716
1717 (defvar org-level-faces
1718 '(
1719 org-level-1
1720 org-level-2
1721 org-level-3
1722 org-level-4
1723 org-level-5
1724 org-level-6
1725 org-level-7
1726 org-level-8
1727 ))
1728 (defvar org-n-levels (length org-level-faces))
1729
1730 ;; Tell the compiler about dynamically scoped variables,
1731 ;; and variables from other packages
1732 (eval-when-compile
1733 (defvar zmacs-regions)
1734 (defvar original-date)
1735 (defvar org-transient-mark-mode)
1736 (defvar org-old-auto-fill-inhibit-regexp)
1737 (defvar orgtbl-mode-menu)
1738 (defvar org-html-entities)
1739 (defvar org-goto-start-pos)
1740 (defvar org-cursor-color)
1741 (defvar org-time-was-given)
1742 (defvar org-ts-what)
1743 (defvar mark-active)
1744 (defvar timecnt)
1745 (defvar levels-open)
1746 (defvar title)
1747 (defvar author)
1748 (defvar email)
1749 (defvar text)
1750 (defvar entry)
1751 (defvar date)
1752 (defvar language)
1753 (defvar options)
1754 (defvar ans1)
1755 (defvar ans2)
1756 (defvar starting-day)
1757 (defvar include-all-loc)
1758 (defvar vm-message-pointer)
1759 (defvar vm-folder-directory)
1760 (defvar wl-summary-buffer-elmo-folder)
1761 (defvar wl-summary-buffer-folder-name)
1762 (defvar gnus-group-name)
1763 (defvar gnus-article-current)
1764 (defvar w3m-current-url)
1765 (defvar org-selected-point)
1766 (defvar calendar-mode-map)
1767 (defvar remember-save-after-remembering)
1768 (defvar remember-data-file))
1769
1770
1771 ;;; Define the mode
1772
1773 (defvar org-mode-map (copy-keymap outline-mode-map)
1774 "Keymap for Org-mode.")
1775
1776 (defvar org-struct-menu)
1777 (defvar org-org-menu)
1778 (defvar org-tbl-menu)
1779
1780 ;; We use a before-change function to check if a table might need
1781 ;; an update.
1782 (defvar org-table-may-need-update t
1783 "Indicates of a table might need an update.
1784 This variable is set by `org-before-change-function'. `org-table-align'
1785 sets it back to nil.")
1786 (defvar org-mode-hook nil)
1787 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1788
1789
1790 ;;;###autoload
1791 (define-derived-mode org-mode outline-mode "Org"
1792 "Outline-based notes management and organizer, alias
1793 \"Carstens outline-mode for keeping track of everything.\"
1794
1795 Org-mode develops organizational tasks around a NOTES file which
1796 contains information about projects as plain text. Org-mode is
1797 implemented on top of outline-mode, which is ideal to keep the content
1798 of large files well structured. It supports ToDo items, deadlines and
1799 time stamps, which magically appear in the diary listing of the Emacs
1800 calendar. Tables are easily created with a built-in table editor.
1801 Plain text URL-like links connect to websites, emails (VM), Usenet
1802 messages (Gnus), BBDB entries, and any files related to the project.
1803 For printing and sharing of notes, an Org-mode file (or a part of it)
1804 can be exported as a structured ASCII or HTML file.
1805
1806 The following commands are available:
1807
1808 \\{org-mode-map}"
1809 (easy-menu-add org-org-menu)
1810 (easy-menu-add org-tbl-menu)
1811 (org-install-agenda-files-menu)
1812 (setq outline-regexp "\\*+")
1813 (if org-startup-truncated (setq truncate-lines t))
1814 (org-set-regexps-and-options)
1815 (set (make-local-variable 'font-lock-unfontify-region-function)
1816 'org-unfontify-region)
1817 ;; Activate before-change-function
1818 (set (make-local-variable 'org-table-may-need-update) t)
1819 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1820 (add-hook 'before-change-functions 'org-before-change-function nil
1821 'local)
1822 ;; Paragraph regular expressions
1823 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1824 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1825 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1826 (set (make-local-variable 'auto-fill-inhibit-regexp)
1827 (concat "\\*\\|#"
1828 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1829 (concat
1830 "\\|[ \t]*["
1831 (if org-enable-table-editor "|" "")
1832 (if org-enable-fixed-width-editor ":" "")
1833 "]"))))
1834 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1835 ;; Settings for Calc embedded mode
1836 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1837 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1838 (if (and org-insert-mode-line-in-empty-file
1839 (interactive-p)
1840 (= (point-min) (point-max)))
1841 (insert " -*- mode: org -*-\n\n"))
1842
1843 ;; Get rid of Outline menus, they are not needed
1844 ;; Need to do this here because define-derived-mode sets up
1845 ;; the keymap so late.
1846 (if org-xemacs-p
1847 (progn
1848 (delete-menu-item '("Headings"))
1849 (delete-menu-item '("Show"))
1850 (delete-menu-item '("Hide"))
1851 (set-menubar-dirty-flag))
1852 (define-key org-mode-map [menu-bar headings] 'undefined)
1853 (define-key org-mode-map [menu-bar hide] 'undefined)
1854 (define-key org-mode-map [menu-bar show] 'undefined))
1855
1856 (unless org-inhibit-startup
1857 (if org-startup-with-deadline-check
1858 (call-interactively 'org-check-deadlines)
1859 (cond
1860 ((eq org-startup-folded t)
1861 (org-cycle '(4)))
1862 ((eq org-startup-folded 'content)
1863 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1864 (org-cycle '(4)) (org-cycle '(4))))))))
1865
1866 (defun org-fill-paragraph (&optional justify)
1867 "Re-align a table, pass through to fill-paragraph if no table."
1868 (save-excursion
1869 (beginning-of-line 1)
1870 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1871
1872 (defsubst org-current-line (&optional pos)
1873 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1874
1875 ;;; Font-Lock stuff
1876
1877 (defvar org-mouse-map (make-sparse-keymap))
1878 (define-key org-mouse-map
1879 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1880 (define-key org-mouse-map
1881 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1882
1883 (require 'font-lock)
1884
1885 (defconst org-non-link-chars "\t\n\r|<>\000")
1886 (defconst org-link-regexp
1887 (if org-allow-space-in-links
1888 (concat
1889 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1890 (concat
1891 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1892 )
1893 "Regular expression for matching links.")
1894 (defconst org-link-maybe-angles-regexp
1895 (concat "<?\\(" org-link-regexp "\\)>?")
1896 "Matches a link and optionally surrounding angle brackets.")
1897 (defconst org-protected-link-regexp
1898 (concat "\000" org-link-regexp "\000")
1899 "Matches a link and optionally surrounding angle brackets.")
1900
1901 (defconst org-ts-lengths
1902 (cons (length (format-time-string (car org-time-stamp-formats)))
1903 (length (format-time-string (cdr org-time-stamp-formats))))
1904 "This holds the lengths of the two different time formats.")
1905 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1906 "Regular expression for fast time stamp matching.")
1907 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1908 "Regular expression matching time strings for analysis.")
1909 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1910 "Regular expression matching time stamps, with groups.")
1911 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1912 "Regular expression matching a time stamp range.")
1913 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1914 org-ts-regexp "\\)?")
1915 "Regular expression matching a time stamp or time stamp range.")
1916
1917 (defun org-activate-links (limit)
1918 "Run through the buffer and add overlays to links."
1919 (if (re-search-forward org-link-regexp limit t)
1920 (progn
1921 (add-text-properties (match-beginning 0) (match-end 0)
1922 (list 'mouse-face 'highlight
1923 'keymap org-mouse-map))
1924 t)))
1925
1926 (defun org-activate-dates (limit)
1927 "Run through the buffer and add overlays to dates."
1928 (if (re-search-forward org-tsr-regexp limit t)
1929 (progn
1930 (add-text-properties (match-beginning 0) (match-end 0)
1931 (list 'mouse-face 'highlight
1932 'keymap org-mouse-map))
1933 t)))
1934
1935 (defun org-font-lock-level ()
1936 (save-excursion
1937 (org-back-to-heading t)
1938 (- (match-end 0) (match-beginning 0))))
1939
1940 (defvar org-font-lock-keywords nil)
1941
1942 (defun org-set-font-lock-defaults ()
1943 (let ((org-font-lock-extra-keywords
1944 (list
1945 '(org-activate-links (0 'org-link))
1946 '(org-activate-dates (0 'org-link))
1947 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1948 '(1 'org-warning t))
1949 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
1950 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1951 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1952 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
1953 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
1954 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1955 ;; (3 'bold))
1956 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1957 ;; (3 'italic))
1958 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1959 ;; (3 'underline))
1960 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1961 ; '(1 'org-warning t))
1962 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
1963 "\\|" org-quote-string "\\)\\>")
1964 '(1 'org-special-keyword t))
1965 '("^#.*" (0 'font-lock-comment-face t))
1966 (if org-fontify-done-headline
1967 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1968 '(1 'org-done t) '(2 'org-headline-done t))
1969 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1970 '(1 'org-done t)))
1971 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1972 (1 'org-table t))
1973 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1974 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
1975 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
1976 )))
1977 (set (make-local-variable 'org-font-lock-keywords)
1978 (append
1979 (if org-noutline-p ; FIXME: I am not sure if eval will work
1980 ; on XEmacs if noutline is ever ported
1981 '((eval . (list "^\\(\\*+\\).*"
1982 0 '(nth
1983 (% (- (match-end 1) (match-beginning 1) 1)
1984 org-n-levels)
1985 org-level-faces)
1986 nil t)))
1987 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1988 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1989 org-n-levels)
1990 org-level-faces)
1991 nil t))))
1992 org-font-lock-extra-keywords))
1993 (set (make-local-variable 'font-lock-defaults)
1994 '(org-font-lock-keywords t nil nil backward-paragraph))
1995 (kill-local-variable 'font-lock-keywords) nil))
1996
1997 (defun org-unfontify-region (beg end &optional maybe_loudly)
1998 "Remove fontification and activation overlays from links."
1999 (font-lock-default-unfontify-region beg end)
2000 (let* ((buffer-undo-list t)
2001 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2002 (inhibit-modification-hooks t)
2003 deactivate-mark buffer-file-name buffer-file-truename)
2004 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2005
2006 ;;; Visibility cycling
2007
2008 (defvar org-cycle-global-status nil)
2009 (defvar org-cycle-subtree-status nil)
2010 (defun org-cycle (&optional arg)
2011 "Visibility cycling for Org-mode.
2012
2013 - When this function is called with a prefix argument, rotate the entire
2014 buffer through 3 states (global cycling)
2015 1. OVERVIEW: Show only top-level headlines.
2016 2. CONTENTS: Show all headlines of all levels, but no body text.
2017 3. SHOW ALL: Show everything.
2018
2019 - When point is at the beginning of a headline, rotate the subtree started
2020 by this line through 3 different states (local cycling)
2021 1. FOLDED: Only the main headline is shown.
2022 2. CHILDREN: The main headline and the direct children are shown. From
2023 this state, you can move to one of the children and
2024 zoom in further.
2025 3. SUBTREE: Show the entire subtree, including body text.
2026
2027 - When there is a numeric prefix, go up to a heading with level ARG, do
2028 a `show-subtree' and return to the previous cursor position. If ARG
2029 is negative, go up that many levels.
2030
2031 - When point is not at the beginning of a headline, execute
2032 `indent-relative', like TAB normally does. See the option
2033 `org-cycle-emulate-tab' for details.
2034
2035 - Special case: if point is the the beginning of the buffer and there is
2036 no headline in line 1, this function will act as if called with prefix arg."
2037 (interactive "P")
2038
2039 (if (or (and (bobp) (not (looking-at outline-regexp)))
2040 (equal arg '(4)))
2041 ;; special case: use global cycling
2042 (setq arg t))
2043
2044 (cond
2045
2046 ((org-at-table-p 'any)
2047 ;; Enter the table or move to the next field in the table
2048 (or (org-table-recognize-table.el)
2049 (progn
2050 (org-table-justify-field-maybe)
2051 (org-table-next-field))))
2052
2053 ((eq arg t) ;; Global cycling
2054
2055 (cond
2056 ((and (eq last-command this-command)
2057 (eq org-cycle-global-status 'overview))
2058 ;; We just created the overview - now do table of contents
2059 ;; This can be slow in very large buffers, so indicate action
2060 (message "CONTENTS...")
2061 (save-excursion
2062 ;; Visit all headings and show their offspring
2063 (goto-char (point-max))
2064 (catch 'exit
2065 (while (and (progn (condition-case nil
2066 (outline-previous-visible-heading 1)
2067 (error (goto-char (point-min))))
2068 t)
2069 (looking-at outline-regexp))
2070 (show-branches)
2071 (if (bobp) (throw 'exit nil))))
2072 (message "CONTENTS...done"))
2073 (setq org-cycle-global-status 'contents)
2074 (run-hook-with-args 'org-cycle-hook 'contents))
2075
2076 ((and (eq last-command this-command)
2077 (eq org-cycle-global-status 'contents))
2078 ;; We just showed the table of contents - now show everything
2079 (show-all)
2080 (message "SHOW ALL")
2081 (setq org-cycle-global-status 'all)
2082 (run-hook-with-args 'org-cycle-hook 'all))
2083
2084 (t
2085 ;; Default action: go to overview
2086 (hide-sublevels 1)
2087 (message "OVERVIEW")
2088 (setq org-cycle-global-status 'overview)
2089 (run-hook-with-args 'org-cycle-hook 'overview))))
2090
2091 ((integerp arg)
2092 ;; Show-subtree, ARG levels up from here.
2093 (save-excursion
2094 (org-back-to-heading)
2095 (outline-up-heading (if (< arg 0) (- arg)
2096 (- (outline-level) arg)))
2097 (org-show-subtree)))
2098
2099 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2100 ;; At a heading: rotate between three different views
2101 (org-back-to-heading)
2102 (let ((goal-column 0) eoh eol eos)
2103 ;; First, some boundaries
2104 (save-excursion
2105 (org-back-to-heading)
2106 (save-excursion
2107 (beginning-of-line 2)
2108 (while (and (not (eobp)) ;; this is like `next-line'
2109 (get-char-property (1- (point)) 'invisible))
2110 (beginning-of-line 2)) (setq eol (point)))
2111 (outline-end-of-heading) (setq eoh (point))
2112 (outline-end-of-subtree) (setq eos (point))
2113 (outline-next-heading))
2114 ;; Find out what to do next and set `this-command'
2115 (cond
2116 ((= eos eoh)
2117 ;; Nothing is hidden behind this heading
2118 (message "EMPTY ENTRY")
2119 (setq org-cycle-subtree-status nil))
2120 ((>= eol eos)
2121 ;; Entire subtree is hidden in one line: open it
2122 (org-show-entry)
2123 (show-children)
2124 (message "CHILDREN")
2125 (setq org-cycle-subtree-status 'children)
2126 (run-hook-with-args 'org-cycle-hook 'children))
2127 ((and (eq last-command this-command)
2128 (eq org-cycle-subtree-status 'children))
2129 ;; We just showed the children, now show everything.
2130 (org-show-subtree)
2131 (message "SUBTREE")
2132 (setq org-cycle-subtree-status 'subtree)
2133 (run-hook-with-args 'org-cycle-hook 'subtree))
2134 (t
2135 ;; Default action: hide the subtree.
2136 (hide-subtree)
2137 (message "FOLDED")
2138 (setq org-cycle-subtree-status 'folded)
2139 (run-hook-with-args 'org-cycle-hook 'folded)))))
2140
2141 ;; TAB emulation
2142 (buffer-read-only (org-back-to-heading))
2143 ((if (and (eq org-cycle-emulate-tab 'white)
2144 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2145 t
2146 (eq org-cycle-emulate-tab t))
2147 (if (and (looking-at "[ \n\r\t]")
2148 (string-match "^[ \t]*$" (buffer-substring
2149 (point-at-bol) (point))))
2150 (progn
2151 (beginning-of-line 1)
2152 (and (looking-at "[ \t]+") (replace-match ""))))
2153 (indent-relative))
2154
2155 (t (save-excursion
2156 (org-back-to-heading)
2157 (org-cycle)))))
2158
2159 (defun org-optimize-window-after-visibility-change (state)
2160 "Adjust the window after a change in outline visibility.
2161 This function is the default value of the hook `org-cycle-hook'."
2162 (cond
2163 ((eq state 'overview) (org-first-headline-recenter 1))
2164 ((eq state 'content) nil)
2165 ((eq state 'all) nil)
2166 ((eq state 'folded) nil)
2167 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2168 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2169
2170 (defun org-subtree-end-visible-p ()
2171 "Is the end of the current subtree visible?"
2172 (pos-visible-in-window-p
2173 (save-excursion (outline-end-of-subtree) (point))))
2174
2175 (defun org-first-headline-recenter (&optional N)
2176 "Move cursor to the first headline and recenter the headline.
2177 Optional argument N means, put the headline into the Nth line of the window."
2178 (goto-char (point-min))
2179 (when (re-search-forward (concat "^" outline-regexp) nil t)
2180 (beginning-of-line)
2181 (recenter (prefix-numeric-value N))))
2182
2183 (defvar org-goto-window-configuration nil)
2184 (defvar org-goto-marker nil)
2185 (defvar org-goto-map (make-sparse-keymap))
2186 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2187 (while (setq cmd (pop cmds))
2188 (substitute-key-definition cmd cmd org-goto-map global-map)))
2189 (define-key org-goto-map "\C-m" 'org-goto-ret)
2190 (define-key org-goto-map [(left)] 'org-goto-left)
2191 (define-key org-goto-map [(right)] 'org-goto-right)
2192 (define-key org-goto-map [(?q)] 'org-goto-quit)
2193 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2194 (define-key org-goto-map "\C-i" 'org-cycle)
2195 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2196 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2197 (define-key org-goto-map "n" 'outline-next-visible-heading)
2198 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2199 (define-key org-goto-map "f" 'outline-forward-same-level)
2200 (define-key org-goto-map "b" 'outline-backward-same-level)
2201 (define-key org-goto-map "u" 'outline-up-heading)
2202 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2203 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2204 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2205 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2206 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2207 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2208 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2209
2210 (defconst org-goto-help
2211 "Select a location to jump to, press RET
2212 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2213
2214 (defun org-goto ()
2215 "Go to a different location of the document, keeping current visibility.
2216
2217 When you want to go to a different location in a document, the fastest way
2218 is often to fold the entire buffer and then dive into the tree. This
2219 method has the disadvantage, that the previous location will be folded,
2220 which may not be what you want.
2221
2222 This command works around this by showing a copy of the current buffer in
2223 overview mode. You can dive into the tree in that copy, to find the
2224 location you want to reach. When pressing RET, the command returns to the
2225 original buffer in which the visibility is still unchanged. It then jumps
2226 to the new location, making it and the headline hierarchy above it visible."
2227 (interactive)
2228 (let* ((org-goto-start-pos (point))
2229 (selected-point
2230 (org-get-location (current-buffer) org-goto-help)))
2231 (if selected-point
2232 (progn
2233 (goto-char selected-point)
2234 (if (org-invisible-p) (org-show-hierarchy-above)))
2235 (error "Quit"))))
2236
2237 (defun org-get-location (buf help)
2238 "Let the user select a location in the Org-mode buffer BUF.
2239 This function uses a recursive edit. It returns the selected position
2240 or nil."
2241 (let (org-selected-point)
2242 (save-excursion
2243 (save-window-excursion
2244 (delete-other-windows)
2245 (switch-to-buffer (get-buffer-create "*org-goto*"))
2246 (with-output-to-temp-buffer "*Help*"
2247 (princ help))
2248 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2249 (setq buffer-read-only nil)
2250 (erase-buffer)
2251 (insert-buffer-substring buf)
2252 (let ((org-startup-truncated t)
2253 (org-startup-folded t)
2254 (org-startup-with-deadline-check nil))
2255 (org-mode))
2256 (setq buffer-read-only t)
2257 (if (boundp 'org-goto-start-pos)
2258 (goto-char org-goto-start-pos)
2259 (goto-char (point-min)))
2260 (org-beginning-of-line)
2261 (message "Select location and press RET")
2262 ;; now we make sure that during selection, ony very few keys work
2263 ;; and that it is impossible to switch to another window.
2264 (let ((gm (current-global-map))
2265 (overriding-local-map org-goto-map))
2266 (unwind-protect
2267 (progn
2268 (use-global-map org-goto-map)
2269 (recursive-edit))
2270 (use-global-map gm)))))
2271 (kill-buffer "*org-goto*")
2272 org-selected-point))
2273
2274 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2275 (defun org-goto-ret (&optional arg)
2276 "Finish org-goto by going to the new location."
2277 (interactive "P")
2278 (setq org-selected-point (point)
2279 current-prefix-arg arg)
2280 (throw 'exit nil))
2281
2282 (defun org-goto-left ()
2283 "Finish org-goto by going to the new location."
2284 (interactive)
2285 (if (org-on-heading-p)
2286 (progn
2287 (beginning-of-line 1)
2288 (setq org-selected-point (point)
2289 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2290 (throw 'exit nil))
2291 (error "Not on a heading")))
2292
2293 (defun org-goto-right ()
2294 "Finish org-goto by going to the new location."
2295 (interactive)
2296 (if (org-on-heading-p)
2297 (progn
2298 (outline-end-of-subtree)
2299 (or (eobp) (forward-char 1))
2300 (setq org-selected-point (point)
2301 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2302 (throw 'exit nil))
2303 (error "Not on a heading")))
2304
2305 (defun org-goto-quit ()
2306 "Finish org-goto without cursor motion."
2307 (interactive)
2308 (setq org-selected-point nil)
2309 (throw 'exit nil))
2310
2311 ;;; Promotion, Demotion, Inserting new headlines
2312
2313 (defvar org-ignore-region nil
2314 "To temporarily disable the active region.")
2315
2316 (defun org-insert-heading ()
2317 "Insert a new heading with same depth at point."
2318 (interactive)
2319 (let* ((head (save-excursion
2320 (condition-case nil
2321 (org-back-to-heading)
2322 (error (outline-next-heading)))
2323 (prog1 (match-string 0)
2324 (funcall outline-level)))))
2325 (unless (bolp) (newline))
2326 (insert head)
2327 (unless (eolp)
2328 (save-excursion (newline-and-indent)))
2329 (unless (equal (char-before) ?\ )
2330 (insert " "))
2331 (run-hooks 'org-insert-heading-hook)))
2332
2333 (defun org-insert-todo-heading (arg)
2334 "Insert a new heading with the same level and TODO state as current heading.
2335 If the heading has no TODO state, or if the state is DONE, use the first
2336 state (TODO by default). Also with prefix arg, force first state."
2337 (interactive "P")
2338 (org-insert-heading)
2339 (save-excursion
2340 (org-back-to-heading)
2341 (outline-previous-heading)
2342 (looking-at org-todo-line-regexp))
2343 (if (or arg
2344 (not (match-beginning 2))
2345 (equal (match-string 2) org-done-string))
2346 (insert (car org-todo-keywords) " ")
2347 (insert (match-string 2) " ")))
2348
2349 (defun org-promote-subtree ()
2350 "Promote the entire subtree.
2351 See also `org-promote'."
2352 (interactive)
2353 (save-excursion
2354 (org-map-tree 'org-promote)))
2355
2356 (defun org-demote-subtree ()
2357 "Demote the entire subtree. See `org-demote'.
2358 See also `org-promote'."
2359 (interactive)
2360 (save-excursion
2361 (org-map-tree 'org-demote)))
2362
2363 (defun org-do-promote ()
2364 "Promote the current heading higher up the tree.
2365 If the region is active in `transient-mark-mode', promote all headings
2366 in the region."
2367 (interactive)
2368 (save-excursion
2369 (if (org-region-active-p)
2370 (org-map-region 'org-promote (region-beginning) (region-end))
2371 (org-promote)))
2372 (org-fix-position-after-promote))
2373
2374 (defun org-do-demote ()
2375 "Demote the current heading lower down the tree.
2376 If the region is active in `transient-mark-mode', demote all headings
2377 in the region."
2378 (interactive)
2379 (save-excursion
2380 (if (org-region-active-p)
2381 (org-map-region 'org-demote (region-beginning) (region-end))
2382 (org-demote)))
2383 (org-fix-position-after-promote))
2384
2385 (defun org-fix-position-after-promote ()
2386 "Make sure that after pro/demotion cursor position is right."
2387 (and (equal (char-after) ?\ )
2388 (equal (char-before) ?*)
2389 (forward-char 1)))
2390
2391 (defun org-promote ()
2392 "Promote the current heading higher up the tree.
2393 If the region is active in `transient-mark-mode', promote all headings
2394 in the region."
2395 (org-back-to-heading t)
2396 (let* ((level (save-match-data (funcall outline-level)))
2397 (up-head (make-string (1- level) ?*)))
2398 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2399 (replace-match up-head nil t)
2400 (if org-adapt-indentation
2401 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2402
2403 (defun org-demote ()
2404 "Demote the current heading lower down the tree.
2405 If the region is active in `transient-mark-mode', demote all headings
2406 in the region."
2407 (org-back-to-heading t)
2408 (let* ((level (save-match-data (funcall outline-level)))
2409 (down-head (make-string (1+ level) ?*)))
2410 (replace-match down-head nil t)
2411 (if org-adapt-indentation
2412 (org-fixup-indentation "^ " " " "^\\S-"))))
2413
2414 (defun org-map-tree (fun)
2415 "Call FUN for every heading underneath the current one."
2416 (org-back-to-heading)
2417 (let ((level (outline-level)))
2418 (save-excursion
2419 (funcall fun)
2420 (while (and (progn
2421 (outline-next-heading)
2422 (> (funcall outline-level) level))
2423 (not (eobp)))
2424 (funcall fun)))))
2425
2426 (defun org-map-region (fun beg end)
2427 "Call FUN for every heading between BEG and END."
2428 (let ((org-ignore-region t))
2429 (save-excursion
2430 (setq end (copy-marker end))
2431 (goto-char beg)
2432 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2433 (< (point) end))
2434 (funcall fun))
2435 (while (and (progn
2436 (outline-next-heading)
2437 (< (point) end))
2438 (not (eobp)))
2439 (funcall fun)))))
2440
2441 (defun org-fixup-indentation (from to prohibit)
2442 "Change the indentation in the current entry by re-replacing FROM with TO.
2443 However, if the regexp PROHIBIT matches at all, don't do anything.
2444 This is being used to change indentation along with the length of the
2445 heading marker. But if there are any lines which are not indented, nothing
2446 is changed at all."
2447 (save-excursion
2448 (let ((end (save-excursion (outline-next-heading)
2449 (point-marker))))
2450 (unless (save-excursion (re-search-forward prohibit end t))
2451 (while (re-search-forward from end t)
2452 (replace-match to)
2453 (beginning-of-line 2)))
2454 (move-marker end nil))))
2455
2456 ;;; Vertical tree motion, cutting and pasting of subtrees
2457
2458 (defun org-move-subtree-up (&optional arg)
2459 "Move the current subtree up past ARG headlines of the same level."
2460 (interactive "p")
2461 (org-move-subtree-down (- (prefix-numeric-value arg))))
2462
2463 (defun org-move-subtree-down (&optional arg)
2464 "Move the current subtree down past ARG headlines of the same level."
2465 (interactive "p")
2466 (setq arg (prefix-numeric-value arg))
2467 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2468 'outline-get-last-sibling))
2469 (ins-point (make-marker))
2470 (cnt (abs arg))
2471 beg end txt folded)
2472 ;; Select the tree
2473 (org-back-to-heading)
2474 (setq beg (point))
2475 (save-match-data
2476 (save-excursion (outline-end-of-heading)
2477 (setq folded (org-invisible-p)))
2478 (outline-end-of-subtree))
2479 (outline-next-heading)
2480 (setq end (point))
2481 ;; Find insertion point, with error handling
2482 (goto-char beg)
2483 (while (> cnt 0)
2484 (or (and (funcall movfunc) (looking-at outline-regexp))
2485 (progn (goto-char beg)
2486 (error "Cannot move past superior level or buffer limit")))
2487 (setq cnt (1- cnt)))
2488 (if (> arg 0)
2489 ;; Moving forward - still need to move over subtree
2490 (progn (outline-end-of-subtree)
2491 (outline-next-heading)
2492 (if (not (or (looking-at (concat "^" outline-regexp))
2493 (bolp)))
2494 (newline))))
2495 (move-marker ins-point (point))
2496 (setq txt (buffer-substring beg end))
2497 (delete-region beg end)
2498 (insert txt)
2499 (goto-char ins-point)
2500 (if folded (hide-subtree))
2501 (move-marker ins-point nil)))
2502
2503 (defvar org-subtree-clip ""
2504 "Clipboard for cut and paste of subtrees.
2505 This is actually only a copy of the kill, because we use the normal kill
2506 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2507
2508 (defvar org-subtree-clip-folded nil
2509 "Was the last copied subtree folded?
2510 This is used to fold the tree back after pasting.")
2511
2512 (defun org-cut-subtree ()
2513 "Cut the current subtree into the clipboard.
2514 This is a short-hand for marking the subtree and then cutting it."
2515 (interactive)
2516 (org-copy-subtree 'cut))
2517
2518 (defun org-copy-subtree (&optional cut)
2519 "Cut the current subtree into the clipboard.
2520 This is a short-hand for marking the subtree and then copying it.
2521 If CUT is non nil, actually cut the subtree."
2522 (interactive)
2523 (let (beg end folded)
2524 (org-back-to-heading)
2525 (setq beg (point))
2526 (save-match-data
2527 (save-excursion (outline-end-of-heading)
2528 (setq folded (org-invisible-p)))
2529 (outline-end-of-subtree))
2530 (if (equal (char-after) ?\n) (forward-char 1))
2531 (setq end (point))
2532 (goto-char beg)
2533 (when (> end beg)
2534 (setq org-subtree-clip-folded folded)
2535 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2536 (setq org-subtree-clip (current-kill 0))
2537 (message "%s: Subtree with %d characters"
2538 (if cut "Cut" "Copied")
2539 (length org-subtree-clip)))))
2540
2541 (defun org-paste-subtree (&optional level tree)
2542 "Paste the clipboard as a subtree, with modification of headline level.
2543 The entire subtree is promoted or demoted in order to match a new headline
2544 level. By default, the new level is derived from the visible headings
2545 before and after the insertion point, and taken to be the inferior headline
2546 level of the two. So if the previous visible heading is level 3 and the
2547 next is level 4 (or vice versa), level 4 will be used for insertion.
2548 This makes sure that the subtree remains an independent subtree and does
2549 not swallow low level entries.
2550
2551 You can also force a different level, either by using a numeric prefix
2552 argument, or by inserting the heading marker by hand. For example, if the
2553 cursor is after \"*****\", then the tree will be shifted to level 5.
2554
2555 If you want to insert the tree as is, just use \\[yank].
2556
2557 If optional TREE is given, use this text instead of the kill ring."
2558 (interactive "P")
2559 (unless (org-kill-is-subtree-p tree)
2560 (error
2561 (substitute-command-keys
2562 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2563 (let* ((txt (or tree (current-kill 0)))
2564 (^re (concat "^\\(" outline-regexp "\\)"))
2565 (re (concat "\\(" outline-regexp "\\)"))
2566 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2567
2568 (old-level (if (string-match ^re txt)
2569 (- (match-end 0) (match-beginning 0))
2570 -1))
2571 (force-level (cond (level (prefix-numeric-value level))
2572 ((string-match
2573 ^re_ (buffer-substring (point-at-bol) (point)))
2574 (- (match-end 0) (match-beginning 0)))
2575 (t nil)))
2576 (previous-level (save-excursion
2577 (condition-case nil
2578 (progn
2579 (outline-previous-visible-heading 1)
2580 (if (looking-at re)
2581 (- (match-end 0) (match-beginning 0))
2582 1))
2583 (error 1))))
2584 (next-level (save-excursion
2585 (condition-case nil
2586 (progn
2587 (outline-next-visible-heading 1)
2588 (if (looking-at re)
2589 (- (match-end 0) (match-beginning 0))
2590 1))
2591 (error 1))))
2592 (new-level (or force-level (max previous-level next-level)))
2593 (shift (if (or (= old-level -1)
2594 (= new-level -1)
2595 (= old-level new-level))
2596 0
2597 (- new-level old-level)))
2598 (shift1 shift)
2599 (delta (if (> shift 0) -1 1))
2600 (func (if (> shift 0) 'org-demote 'org-promote))
2601 beg end)
2602 ;; Remove the forces level indicator
2603 (if force-level
2604 (delete-region (point-at-bol) (point)))
2605 ;; Make sure we start at the beginning of an empty line
2606 (if (not (bolp)) (insert "\n"))
2607 (if (not (looking-at "[ \t]*$"))
2608 (progn (insert "\n") (backward-char 1)))
2609 ;; Paste
2610 (setq beg (point))
2611 (insert txt)
2612 (setq end (point))
2613 (goto-char beg)
2614 ;; Shift if necessary
2615 (if (= shift 0)
2616 (message "Pasted at level %d, without shift" new-level)
2617 (save-restriction
2618 (narrow-to-region beg end)
2619 (while (not (= shift 0))
2620 (org-map-region func (point-min) (point-max))
2621 (setq shift (+ delta shift)))
2622 (goto-char (point-min))
2623 (message "Pasted at level %d, with shift by %d levels"
2624 new-level shift1)))
2625 (if (and (eq org-subtree-clip (current-kill 0))
2626 org-subtree-clip-folded)
2627 ;; The tree was folded before it was killed/copied
2628 (hide-subtree))))
2629
2630 (defun org-kill-is-subtree-p (&optional txt)
2631 "Check if the current kill is an outline subtree, or a set of trees.
2632 Returns nil if kill does not start with a headline, or if the first
2633 headline level is not the largest headline level in the tree.
2634 So this will actually accept several entries of equal levels as well,
2635 which is OK for `org-paste-subtree'.
2636 If optional TXT is given, check this string instead of the current kill."
2637 (let* ((kill (or txt (current-kill 0) ""))
2638 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2639 (- (match-end 0) (match-beginning 0))))
2640 (re (concat "^" outline-regexp))
2641 (start 1))
2642 (if (not start-level)
2643 nil ;; does not even start with a heading
2644 (catch 'exit
2645 (while (setq start (string-match re kill (1+ start)))
2646 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2647 (throw 'exit nil)))
2648 t))))
2649
2650 (defun org-archive-subtree ()
2651 "Move the current subtree to the archive.
2652 The archive can be a certain top-level heading in the current file, or in
2653 a different file. The tree will be moved to that location, the subtree
2654 heading be marked DONE, and the current time will be added."
2655 (interactive)
2656 ;; Save all relevant TODO keyword-relatex variables
2657 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2658 (tr-org-todo-keywords org-todo-keywords)
2659 (tr-org-todo-interpretation org-todo-interpretation)
2660 (tr-org-done-string org-done-string)
2661 (tr-org-todo-regexp org-todo-regexp)
2662 (tr-org-todo-line-regexp org-todo-line-regexp)
2663 (this-buffer (current-buffer))
2664 file heading buffer level newfile-p)
2665 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2666 (progn
2667 (setq file (format (match-string 1 org-archive-location)
2668 (file-name-nondirectory (buffer-file-name)))
2669 heading (match-string 2 org-archive-location)))
2670 (error "Invalid `org-archive-location'"))
2671 (if (> (length file) 0)
2672 (setq newfile-p (not (file-exists-p file))
2673 buffer (find-file-noselect file))
2674 (setq buffer (current-buffer)))
2675 (unless buffer
2676 (error "Cannot access file \"%s\"" file))
2677 (if (and (> (length heading) 0)
2678 (string-match "^\\*+" heading))
2679 (setq level (match-end 0))
2680 (setq heading nil level 0))
2681 (save-excursion
2682 ;; We first only copy, in case something goes wrong
2683 ;; we need to protect this-command, to avoid kill-region sets it,
2684 ;; which would lead to duplication of subtrees
2685 (let (this-command) (org-copy-subtree))
2686 (set-buffer buffer)
2687 ;; Enforce org-mode for the archive buffer
2688 (if (not (eq major-mode 'org-mode))
2689 ;; Force the mode for future visits.
2690 (let ((org-insert-mode-line-in-empty-file t))
2691 (call-interactively 'org-mode)))
2692 (when newfile-p
2693 (goto-char (point-max))
2694 (insert (format "\nArchived entries from file %s\n\n"
2695 (buffer-file-name this-buffer))))
2696 ;; Force the TODO keywords of the original buffer
2697 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2698 (org-todo-keywords tr-org-todo-keywords)
2699 (org-todo-interpretation tr-org-todo-interpretation)
2700 (org-done-string tr-org-done-string)
2701 (org-todo-regexp tr-org-todo-regexp)
2702 (org-todo-line-regexp tr-org-todo-line-regexp))
2703 (goto-char (point-min))
2704 (if heading
2705 (progn
2706 (if (re-search-forward
2707 (concat "\\(^\\|\r\\)"
2708 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2709 nil t)
2710 (goto-char (match-end 0))
2711 ;; Heading not found, just insert it at the end
2712 (goto-char (point-max))
2713 (or (bolp) (insert "\n"))
2714 (insert "\n" heading "\n")
2715 (end-of-line 0))
2716 ;; Make the heading visible, and the following as well
2717 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2718 (if (re-search-forward
2719 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2720 nil t)
2721 (progn (goto-char (match-beginning 0)) (insert "\n")
2722 (beginning-of-line 0))
2723 (goto-char (point-max)) (insert "\n")))
2724 (goto-char (point-max)) (insert "\n"))
2725 ;; Paste
2726 (org-paste-subtree (1+ level))
2727 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2728 (if org-archive-mark-done
2729 (org-todo (length org-todo-keywords)))
2730 ;; Move cursor to right after the TODO keyword
2731 (when org-archive-stamp-time
2732 (beginning-of-line 1)
2733 (looking-at org-todo-line-regexp)
2734 (goto-char (or (match-end 2) (match-beginning 3)))
2735 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2736 (current-time))
2737 ")"))
2738 ;; Save the buffer, if it is not the same buffer.
2739 (if (not (eq this-buffer buffer)) (save-buffer))))
2740 ;; Here we are back in the original buffer. Everything seems to have
2741 ;; worked. So now cut the tree and finish up.
2742 (let (this-command) (org-cut-subtree))
2743 (if (looking-at "[ \t]*$") (kill-line))
2744 (message "Subtree archived %s"
2745 (if (eq this-buffer buffer)
2746 (concat "under heading: " heading)
2747 (concat "in file: " (abbreviate-file-name file))))))
2748
2749 ;;; Completion
2750
2751 (defun org-complete (&optional arg)
2752 "Perform completion on word at point.
2753 At the beginning of a headline, this completes TODO keywords as given in
2754 `org-todo-keywords'.
2755 If the current word is preceded by a backslash, completes the TeX symbols
2756 that are supported for HTML support.
2757 If the current word is preceded by \"#+\", completes special words for
2758 setting file options.
2759 At all other locations, this simply calls `ispell-complete-word'."
2760 (interactive "P")
2761 (catch 'exit
2762 (let* ((end (point))
2763 (beg (save-excursion
2764 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2765 (skip-chars-backward "a-zA-Z0-9_:$")
2766 (point)))
2767 (texp (equal (char-before beg) ?\\))
2768 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2769 beg)
2770 "#+"))
2771 (pattern (buffer-substring-no-properties beg end))
2772 (completion-ignore-case opt)
2773 (type nil)
2774 (table (cond
2775 (opt
2776 (setq type :opt)
2777 (mapcar (lambda (x)
2778 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2779 (cons (match-string 2 x) (match-string 1 x)))
2780 (org-split-string (org-get-current-options) "\n")))
2781 (texp
2782 (setq type :tex)
2783 org-html-entities)
2784 ((string-match "\\`\\*+[ \t]*\\'"
2785 (buffer-substring (point-at-bol) beg))
2786 (setq type :todo)
2787 (mapcar 'list org-todo-keywords))
2788 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2789 (completion (try-completion pattern table)))
2790 (cond ((eq completion t)
2791 (if (equal type :opt)
2792 (insert (substring (cdr (assoc (upcase pattern) table))
2793 (length pattern)))))
2794 ((null completion)
2795 (message "Can't find completion for \"%s\"" pattern)
2796 (ding))
2797 ((not (string= pattern completion))
2798 (delete-region beg end)
2799 (if (string-match " +$" completion)
2800 (setq completion (replace-match "" t t completion)))
2801 (insert completion)
2802 (if (get-buffer-window "*Completions*")
2803 (delete-window (get-buffer-window "*Completions*")))
2804 (if (and (eq type :todo)
2805 (assoc completion table))
2806 (insert " "))
2807 (if (and (equal type :opt) (assoc completion table))
2808 (message (substitute-command-keys
2809 "Press \\[org-complete] again to insert example settings"))))
2810 (t
2811 (message "Making completion list...")
2812 (let ((list (sort (all-completions pattern table) 'string<)))
2813 (with-output-to-temp-buffer "*Completions*"
2814 (display-completion-list list)))
2815 (message "Making completion list...%s" "done"))))))
2816
2817 ;;; Comments, TODO and DEADLINE
2818
2819 (defun org-toggle-comment ()
2820 "Change the COMMENT state of an entry."
2821 (interactive)
2822 (save-excursion
2823 (org-back-to-heading)
2824 (if (looking-at (concat outline-regexp
2825 "\\( +\\<" org-comment-string "\\>\\)"))
2826 (replace-match "" t t nil 1)
2827 (if (looking-at outline-regexp)
2828 (progn
2829 (goto-char (match-end 0))
2830 (insert " " org-comment-string))))))
2831
2832 (defvar org-last-todo-state-is-todo nil
2833 "This is non-nil when the last TODO state change led to a TODO state.
2834 If the last change removed the TODO tag or switched to DONE, then
2835 this is nil.")
2836
2837 (defun org-todo (&optional arg)
2838 "Change the TODO state of an item.
2839 The state of an item is given by a keyword at the start of the heading,
2840 like
2841 *** TODO Write paper
2842 *** DONE Call mom
2843
2844 The different keywords are specified in the variable `org-todo-keywords'. By
2845 default the available states are \"TODO\" and \"DONE\".
2846 So for this example: when the item starts with TODO, it is changed to DONE.
2847 When it starts with DONE, the DONE is removed. And when neither TODO nor
2848 DONE are present, add TODO at the beginning of the heading.
2849
2850 With prefix arg, use completion to determined the new state. With numeric
2851 prefix arg, switch to that state."
2852 (interactive "P")
2853 (save-excursion
2854 (org-back-to-heading)
2855 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2856 (or (looking-at (concat " +" org-todo-regexp " *"))
2857 (looking-at " *"))
2858 (let* ((this (match-string 1))
2859 (completion-ignore-case t)
2860 (member (member this org-todo-keywords))
2861 (tail (cdr member))
2862 (state (cond
2863 ((equal arg '(4))
2864 ;; Read a state with completion
2865 (completing-read "State: " (mapcar (lambda(x) (list x))
2866 org-todo-keywords)
2867 nil t))
2868 (arg
2869 ;; user requests a specific state
2870 (nth (1- (prefix-numeric-value arg))
2871 org-todo-keywords))
2872 ((null member) (car org-todo-keywords))
2873 ((null tail) nil) ;; -> first entry
2874 ((eq org-todo-interpretation 'sequence)
2875 (car tail))
2876 ((memq org-todo-interpretation '(type priority))
2877 (if (eq this-command last-command)
2878 (car tail)
2879 (if (> (length tail) 0) org-done-string nil)))
2880 (t nil)))
2881 (next (if state (concat " " state " ") " ")))
2882 (replace-match next t t)
2883 (setq org-last-todo-state-is-todo
2884 (not (equal state org-done-string)))
2885 (run-hooks 'org-after-todo-state-change-hook)))
2886 ;; Fixup cursor location if close to the keyword
2887 (if (and (outline-on-heading-p)
2888 (not (bolp))
2889 (save-excursion (beginning-of-line 1)
2890 (looking-at org-todo-line-regexp))
2891 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2892 (progn
2893 (goto-char (or (match-end 2) (match-end 1)))
2894 (just-one-space))))
2895
2896 (defun org-show-todo-tree (arg)
2897 "Make a compact tree which shows all headlines marked with TODO.
2898 The tree will show the lines where the regexp matches, and all higher
2899 headlines above the match."
2900 (interactive "P")
2901 (let ((case-fold-search nil)
2902 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2903 (message "%d TODO entries found"
2904 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2905
2906 (defun org-deadline ()
2907 "Insert the DEADLINE: string to make a deadline.
2908 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2909 to modify it to the correct date."
2910 (interactive)
2911 (insert
2912 org-deadline-string " "
2913 (format-time-string (car org-time-stamp-formats)
2914 (org-read-date nil 'to-time)))
2915 (message (substitute-command-keys
2916 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2917
2918 (defun org-schedule ()
2919 "Insert the SCHEDULED: string to schedule a TODO item.
2920 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2921 to modify it to the correct date."
2922 (interactive)
2923 (insert
2924 org-scheduled-string " "
2925 (format-time-string (car org-time-stamp-formats)
2926 (org-read-date nil 'to-time)))
2927 (message (substitute-command-keys
2928 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2929
2930
2931 (defun org-occur (regexp &optional callback)
2932 "Make a compact tree which shows all matches of REGEXP.
2933 The tree will show the lines where the regexp matches, and all higher
2934 headlines above the match. It will also show the heading after the match,
2935 to make sure editing the matching entry is easy.
2936 if CALLBACK is non-nil, it is a function which is called to confirm
2937 that the match should indeed be shown."
2938 (interactive "sRegexp: ")
2939 (setq regexp (org-check-occur-regexp regexp))
2940 (let ((cnt 0))
2941 (save-excursion
2942 (goto-char (point-min))
2943 (hide-sublevels 1)
2944 (while (re-search-forward regexp nil t)
2945 (when (or (not callback)
2946 (funcall callback))
2947 (setq cnt (1+ cnt))
2948 (org-show-hierarchy-above))))
2949 (run-hooks 'org-occur-hook)
2950 (if (interactive-p)
2951 (message "%d match(es) for regexp %s" cnt regexp))
2952 cnt))
2953
2954 (defun org-show-hierarchy-above ()
2955 "Make sure point and the headings hierarchy above is visible."
2956 (if (org-on-heading-p t)
2957 (org-flag-heading nil) ; only show the heading
2958 (org-show-hidden-entry)) ; show entire entry
2959 (save-excursion
2960 (and org-show-following-heading
2961 (outline-next-heading)
2962 (org-flag-heading nil))) ; show the next heading
2963 (save-excursion ; show all higher headings
2964 (while (condition-case nil
2965 (progn (org-up-heading-all 1) t)
2966 (error nil))
2967 (org-flag-heading nil))))
2968
2969 ;;; Priorities
2970
2971 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2972 "Regular expression matching the priority indicator.")
2973
2974 (defvar org-remove-priority-next-time nil)
2975
2976 (defun org-priority-up ()
2977 "Increase the priority of the current item."
2978 (interactive)
2979 (org-priority 'up))
2980
2981 (defun org-priority-down ()
2982 "Decrease the priority of the current item."
2983 (interactive)
2984 (org-priority 'down))
2985
2986 (defun org-priority (&optional action)
2987 "Change the priority of an item by ARG.
2988 ACTION can be set, up, or down."
2989 (interactive)
2990 (setq action (or action 'set))
2991 (let (current new news have remove)
2992 (save-excursion
2993 (org-back-to-heading)
2994 (if (looking-at org-priority-regexp)
2995 (setq current (string-to-char (match-string 2))
2996 have t)
2997 (setq current org-default-priority))
2998 (cond
2999 ((eq action 'set)
3000 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
3001 (setq new (read-char-exclusive))
3002 (cond ((equal new ?\ ) (setq remove t))
3003 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3004 (error "Priority must be between `%c' and `%c'"
3005 ?A org-lowest-priority))))
3006 ((eq action 'up)
3007 (setq new (1- current)))
3008 ((eq action 'down)
3009 (setq new (1+ current)))
3010 (t (error "Invalid action")))
3011 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3012 (setq news (format "%c" new))
3013 (if have
3014 (if remove
3015 (replace-match "" t t nil 1)
3016 (replace-match news t t nil 2))
3017 (if remove
3018 (error "No priority cookie found in line")
3019 (looking-at org-todo-line-regexp)
3020 (if (match-end 2)
3021 (progn
3022 (goto-char (match-end 2))
3023 (insert " [#" news "]"))
3024 (goto-char (match-beginning 3))
3025 (insert "[#" news "] ")))))
3026 (if remove
3027 (message "Priority removed")
3028 (message "Priority of current item set to %s" news))))
3029
3030
3031 (defun org-get-priority (s)
3032 "Find priority cookie and return priority."
3033 (save-match-data
3034 (if (not (string-match org-priority-regexp s))
3035 (* 1000 (- org-lowest-priority org-default-priority))
3036 (* 1000 (- org-lowest-priority
3037 (string-to-char (match-string 2 s)))))))
3038
3039 ;;; Timestamps
3040
3041 (defvar org-last-changed-timestamp nil)
3042
3043 (defun org-time-stamp (arg)
3044 "Prompt for a date/time and insert a time stamp.
3045 If the user specifies a time like HH:MM, or if this command is called
3046 with a prefix argument, the time stamp will contain date and time.
3047 Otherwise, only the date will be included. All parts of a date not
3048 specified by the user will be filled in from the current date/time.
3049 So if you press just return without typing anything, the time stamp
3050 will represent the current date/time. If there is already a timestamp
3051 at the cursor, it will be modified."
3052 (interactive "P")
3053 (let ((fmt (if arg (cdr org-time-stamp-formats)
3054 (car org-time-stamp-formats)))
3055 (org-time-was-given nil)
3056 time)
3057 (cond
3058 ((and (org-at-timestamp-p)
3059 (eq last-command 'org-time-stamp)
3060 (eq this-command 'org-time-stamp))
3061 (insert "--")
3062 (setq time (let ((this-command this-command))
3063 (org-read-date arg 'totime)))
3064 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3065 (insert (format-time-string fmt time)))
3066 ((org-at-timestamp-p)
3067 (setq time (let ((this-command this-command))
3068 (org-read-date arg 'totime)))
3069 (and (org-at-timestamp-p) (replace-match
3070 (setq org-last-changed-timestamp
3071 (format-time-string fmt time))
3072 t t))
3073 (message "Timestamp updated"))
3074 (t
3075 (setq time (let ((this-command this-command))
3076 (org-read-date arg 'totime)))
3077 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3078 (insert (format-time-string fmt time))))))
3079
3080 ;;; FIXME: Make the function take "Fri" as "next friday"
3081 (defun org-read-date (&optional with-time to-time)
3082 "Read a date and make things smooth for the user.
3083 The prompt will suggest to enter an ISO date, but you can also enter anything
3084 which will at least partially be understood by `parse-time-string'.
3085 Unrecognized parts of the date will default to the current day, month ,year,
3086 hour and minute. For example,
3087 3-2-5 --> 2003-02-05
3088 feb 15 --> currentyear-02-15
3089 sep 12 9 --> 2009-09-12
3090 12:45 --> today 12:45
3091 22 sept 0:34 --> currentyear-09-22 0:34
3092 12 --> currentyear-currentmonth-12
3093 etc.
3094 The function understands only English month and weekday abbreviations,
3095 but this can be configured with the variables `parse-time-months' and
3096 `parse-time-weekdays'.
3097
3098 While prompting, a calendar is popped up - you can also select the
3099 date with the mouse (button 1). The calendar shows a period of three
3100 month. To scroll it to other months, use the keys `>' and `<'.
3101 If you don't like the calendar, turn it off with
3102 \(setq org-popup-calendar-for-date-prompt nil).
3103
3104 With optional argument TO-TIME, the date will immediately be converted
3105 to an internal time.
3106 With an optional argument WITH-TIME, the prompt will suggest to also
3107 insert a time. Note that when WITH-TIME is not set, you can still
3108 enter a time, and this function will inform the calling routine about
3109 this change. The calling routine may then choose to change the format
3110 used to insert the time stamp into the buffer to include the time."
3111 (let* ((default-time
3112 ;; Default time is either today, or, when entering a range,
3113 ;; the range start.
3114 (if (save-excursion
3115 (re-search-backward
3116 (concat org-ts-regexp "--\\=")
3117 (- (point) 20) t))
3118 (apply
3119 'encode-time
3120 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3121 (parse-time-string (match-string 1))))
3122 (current-time)))
3123 (timestr (format-time-string
3124 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3125 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3126 ans ans1 ans2
3127 second minute hour day month year tl)
3128
3129 (if org-popup-calendar-for-date-prompt
3130 ;; Also show a calendar for date selection
3131 ;; Copied (with modifications) from planner.el by John Wiegley
3132 (save-excursion
3133 (save-window-excursion
3134 (calendar)
3135 (calendar-forward-day (- (time-to-days default-time)
3136 (calendar-absolute-from-gregorian
3137 (calendar-current-date))))
3138 (let* ((old-map (current-local-map))
3139 (map (copy-keymap calendar-mode-map))
3140 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3141 (define-key map (kbd "RET") 'org-calendar-select)
3142 (define-key map (if org-xemacs-p [button1] [mouse-1])
3143 'org-calendar-select)
3144 (define-key minibuffer-local-map [(meta shift left)]
3145 (lambda () (interactive)
3146 (org-eval-in-calendar '(calendar-backward-month 1))))
3147 (define-key minibuffer-local-map [(meta shift right)]
3148 (lambda () (interactive)
3149 (org-eval-in-calendar '(calendar-forward-month 1))))
3150 (define-key minibuffer-local-map [(shift up)]
3151 (lambda () (interactive)
3152 (org-eval-in-calendar '(calendar-backward-week 1))))
3153 (define-key minibuffer-local-map [(shift down)]
3154 (lambda () (interactive)
3155 (org-eval-in-calendar '(calendar-forward-week 1))))
3156 (define-key minibuffer-local-map [(shift left)]
3157 (lambda () (interactive)
3158 (org-eval-in-calendar '(calendar-backward-day 1))))
3159 (define-key minibuffer-local-map [(shift right)]
3160 (lambda () (interactive)
3161 (org-eval-in-calendar '(calendar-forward-day 1))))
3162 (define-key minibuffer-local-map ">"
3163 (lambda () (interactive)
3164 (org-eval-in-calendar '(scroll-calendar-left 1))))
3165 (define-key minibuffer-local-map "<"
3166 (lambda () (interactive)
3167 (org-eval-in-calendar '(scroll-calendar-right 1))))
3168 (unwind-protect
3169 (progn
3170 (use-local-map map)
3171 (setq ans (read-string prompt "" nil nil))
3172 (setq ans (or ans1 ans2 ans)))
3173 (use-local-map old-map)))))
3174 ;; Naked prompt only
3175 (setq ans (read-string prompt "" nil timestr)))
3176
3177 (if (string-match
3178 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3179 (progn
3180 (setq year (if (match-end 2)
3181 (string-to-number (match-string 2 ans))
3182 (string-to-number (format-time-string "%Y")))
3183 month (string-to-number (match-string 3 ans))
3184 day (string-to-number (match-string 4 ans)))
3185 (if (< year 100) (setq year (+ 2000 year)))
3186 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3187 t t ans))))
3188 (setq tl (parse-time-string ans)
3189 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3190 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3191 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3192 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3193 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3194 second (or (nth 0 tl) 0))
3195 (if (and (boundp 'org-time-was-given)
3196 (nth 2 tl))
3197 (setq org-time-was-given t))
3198 (if (< year 100) (setq year (+ 2000 year)))
3199 (if to-time
3200 (encode-time second minute hour day month year)
3201 (if (or (nth 1 tl) (nth 2 tl))
3202 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3203 (format "%04d-%02d-%02d" year month day)))))
3204
3205 (defun org-eval-in-calendar (form)
3206 "Eval FORM in the calendar window and return to current window.
3207 Also, store the cursor date in variable ans2."
3208 (let ((sw (selected-window)))
3209 (select-window (get-buffer-window "*Calendar*"))
3210 (eval form)
3211 (when (calendar-cursor-to-date)
3212 (let* ((date (calendar-cursor-to-date))
3213 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3214 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3215 (select-window sw)))
3216
3217 (defun org-calendar-select ()
3218 "Return to `org-read-date' with the date currently selected.
3219 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3220 (interactive)
3221 (when (calendar-cursor-to-date)
3222 (let* ((date (calendar-cursor-to-date))
3223 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3224 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3225 (if (active-minibuffer-window) (exit-minibuffer))))
3226
3227 (defun org-check-deadlines (ndays)
3228 "Check if there are any deadlines due or past due.
3229 A deadline is considered due if it happens within `org-deadline-warning-days'
3230 days from today's date. If the deadline appears in an entry marked DONE,
3231 it is not shown. The prefix arg NDAYS can be used to test that many
3232 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3233 (interactive "P")
3234 (let* ((org-warn-days
3235 (cond
3236 ((equal ndays '(4)) 100000)
3237 (ndays (prefix-numeric-value ndays))
3238 (t org-deadline-warning-days)))
3239 (case-fold-search nil)
3240 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3241 (callback
3242 (lambda ()
3243 (and (let ((d1 (time-to-days (current-time)))
3244 (d2 (time-to-days
3245 (org-time-string-to-time (match-string 1)))))
3246 (< (- d2 d1) org-warn-days))
3247 (not (org-entry-is-done-p))))))
3248 (message "%d deadlines past-due or due within %d days"
3249 (org-occur regexp callback)
3250 org-warn-days)))
3251
3252 (defun org-evaluate-time-range (&optional to-buffer)
3253 "Evaluate a time range by computing the difference between start and end.
3254 Normally the result is just printed in the echo area, but with prefix arg
3255 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3256 If the time range is actually in a table, the result is inserted into the
3257 next column.
3258 For time difference computation, a year is assumed to be exactly 365
3259 days in order to avoid rounding problems."
3260 (interactive "P")
3261 (save-excursion
3262 (unless (org-at-date-range-p)
3263 (goto-char (point-at-bol))
3264 (re-search-forward org-tr-regexp (point-at-eol) t))
3265 (if (not (org-at-date-range-p))
3266 (error "Not at a time-stamp range, and none found in current line")))
3267 (let* ((ts1 (match-string 1))
3268 (ts2 (match-string 2))
3269 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3270 (match-end (match-end 0))
3271 (time1 (org-time-string-to-time ts1))
3272 (time2 (org-time-string-to-time ts2))
3273 (t1 (time-to-seconds time1))
3274 (t2 (time-to-seconds time2))
3275 (diff (abs (- t2 t1)))
3276 (negative (< (- t2 t1) 0))
3277 ;; (ys (floor (* 365 24 60 60)))
3278 (ds (* 24 60 60))
3279 (hs (* 60 60))
3280 (fy "%dy %dd %02d:%02d")
3281 (fy1 "%dy %dd")
3282 (fd "%dd %02d:%02d")
3283 (fd1 "%dd")
3284 (fh "%02d:%02d")
3285 y d h m align)
3286 ;; FIXME: Should I re-introduce years, make year refer to same date?
3287 ;; This would be the only useful way to have years, actually.
3288 (if havetime
3289 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3290 y 0
3291 d (floor (/ diff ds)) diff (mod diff ds)
3292 h (floor (/ diff hs)) diff (mod diff hs)
3293 m (floor (/ diff 60)))
3294 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3295 y 0
3296 d (floor (+ (/ diff ds) 0.5))
3297 h 0 m 0))
3298 (if (not to-buffer)
3299 (message (org-make-tdiff-string y d h m))
3300 (when (org-at-table-p)
3301 (goto-char match-end)
3302 (setq align t)
3303 (and (looking-at " *|") (goto-char (match-end 0))))
3304 (if (looking-at
3305 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3306 (replace-match ""))
3307 (if negative (insert " -"))
3308 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3309 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3310 (insert " " (format fh h m))))
3311 (if align (org-table-align))
3312 (message "Time difference inserted"))))
3313
3314 (defun org-make-tdiff-string (y d h m)
3315 (let ((fmt "")
3316 (l nil))
3317 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3318 l (push y l)))
3319 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3320 l (push d l)))
3321 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3322 l (push h l)))
3323 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3324 l (push m l)))
3325 (apply 'format fmt (nreverse l))))
3326
3327 (defun org-time-string-to-time (s)
3328 (apply 'encode-time (org-parse-time-string s)))
3329
3330 (defun org-parse-time-string (s &optional nodefault)
3331 "Parse the standard Org-mode time string.
3332 This should be a lot faster than the normal `parse-time-string'.
3333 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3334 hour and minute fields will be nil if not given."
3335 (if (string-match org-ts-regexp1 s)
3336 (list 0
3337 (if (or (match-beginning 8) (not nodefault))
3338 (string-to-number (or (match-string 8 s) "0")))
3339 (if (or (match-beginning 7) (not nodefault))
3340 (string-to-number (or (match-string 7 s) "0")))
3341 (string-to-number (match-string 4 s))
3342 (string-to-number (match-string 3 s))
3343 (string-to-number (match-string 2 s))
3344 nil nil nil)
3345 (make-list 9 0)))
3346
3347 (defun org-timestamp-up (&optional arg)
3348 "Increase the date item at the cursor by one.
3349 If the cursor is on the year, change the year. If it is on the month or
3350 the day, change that.
3351 With prefix ARG, change by that many units."
3352 (interactive "p")
3353 (org-timestamp-change (prefix-numeric-value arg)))
3354
3355 (defun org-timestamp-down (&optional arg)
3356 "Decrease the date item at the cursor by one.
3357 If the cursor is on the year, change the year. If it is on the month or
3358 the day, change that.
3359 With prefix ARG, change by that many units."
3360 (interactive "p")
3361 (org-timestamp-change (- (prefix-numeric-value arg))))
3362
3363 (defun org-timestamp-up-day (&optional arg)
3364 "Increase the date in the time stamp by one day.
3365 With prefix ARG, change that many days."
3366 (interactive "p")
3367 (org-timestamp-change (prefix-numeric-value arg) 'day))
3368
3369 (defun org-timestamp-down-day (&optional arg)
3370 "Decrease the date in the time stamp by one day.
3371 With prefix ARG, change that many days."
3372 (interactive "p")
3373 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3374
3375 (defsubst org-pos-in-match-range (pos n)
3376 (and (match-beginning n)
3377 (<= (match-beginning n) pos)
3378 (>= (match-end n) pos)))
3379
3380 (defun org-at-timestamp-p ()
3381 "Determine if the cursor is or at a timestamp."
3382 (interactive)
3383 (let* ((tsr org-ts-regexp2)
3384 (pos (point))
3385 (ans (or (looking-at tsr)
3386 (save-excursion
3387 (skip-chars-backward "^<\n\r\t")
3388 (if (> (point) 1) (backward-char 1))
3389 (and (looking-at tsr)
3390 (> (- (match-end 0) pos) -1))))))
3391 (and (boundp 'org-ts-what)
3392 (setq org-ts-what
3393 (cond
3394 ((org-pos-in-match-range pos 2) 'year)
3395 ((org-pos-in-match-range pos 3) 'month)
3396 ((org-pos-in-match-range pos 7) 'hour)
3397 ((org-pos-in-match-range pos 8) 'minute)
3398 ((or (org-pos-in-match-range pos 4)
3399 (org-pos-in-match-range pos 5)) 'day)
3400 (t 'day))))
3401 ans))
3402
3403 (defun org-timestamp-change (n &optional what)
3404 "Change the date in the time stamp at point.
3405 The date will be changed by N times WHAT. WHAT can be `day', `month',
3406 `year', `minute', `second'. If WHAT is not given, the cursor position
3407 in the timestamp determines what will be changed."
3408 (let ((fmt (car org-time-stamp-formats))
3409 org-ts-what
3410 (pos (point))
3411 ts time time0)
3412 (if (not (org-at-timestamp-p))
3413 (error "Not at a timestamp"))
3414 (setq org-ts-what (or what org-ts-what))
3415 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3416 (- (match-end 0) (match-beginning 0))))
3417 1)
3418 (cdr org-time-stamp-formats)
3419 (car org-time-stamp-formats)))
3420 (setq ts (match-string 0))
3421 (replace-match "")
3422 (setq time0 (org-parse-time-string ts))
3423 (setq time
3424 (apply 'encode-time
3425 (append
3426 (list (or (car time0) 0))
3427 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3428 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3429 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3430 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3431 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3432 (nthcdr 6 time0))))
3433 (if (eq what 'calendar)
3434 (let ((cal-date
3435 (save-excursion
3436 (save-match-data
3437 (set-buffer "*Calendar*")
3438 (calendar-cursor-to-date)))))
3439 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3440 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3441 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3442 (setcar time0 (or (car time0) 0))
3443 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3444 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3445 (setq time (apply 'encode-time time0))))
3446 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3447 (goto-char pos)
3448 ;; Try to recenter the calendar window, if any
3449 (if (and org-calendar-follow-timestamp-change
3450 (get-buffer-window "*Calendar*" t)
3451 (memq org-ts-what '(day month year)))
3452 (org-recenter-calendar (time-to-days time)))))
3453
3454 (defun org-recenter-calendar (date)
3455 "If the calendar is visible, recenter it to DATE."
3456 (let* ((win (selected-window))
3457 (cwin (get-buffer-window "*Calendar*" t)))
3458 (when cwin
3459 (select-window cwin)
3460 (calendar-goto-date (if (listp date) date
3461 (calendar-gregorian-from-absolute date)))
3462 (select-window win))))
3463
3464 (defun org-goto-calendar (&optional arg)
3465 "Go to the Emacs calendar at the current date.
3466 If there is a time stamp in the current line, go to that date.
3467 A prefix ARG can be used force the current date."
3468 (interactive "P")
3469 (let ((tsr org-ts-regexp) diff)
3470 (if (or (org-at-timestamp-p)
3471 (save-excursion
3472 (beginning-of-line 1)
3473 (looking-at (concat ".*" tsr))))
3474 (let ((d1 (time-to-days (current-time)))
3475 (d2 (time-to-days
3476 (org-time-string-to-time (match-string 1)))))
3477 (setq diff (- d2 d1))))
3478 (calendar)
3479 (calendar-goto-today)
3480 (if (and diff (not arg)) (calendar-forward-day diff))))
3481
3482 (defun org-date-from-calendar ()
3483 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3484 If there is already a time stamp at the cursor position, update it."
3485 (interactive)
3486 (org-timestamp-change 0 'calendar))
3487
3488 ;;; Agenda, and Diary Integration
3489
3490 ;;; Define the mode
3491
3492 (defvar org-agenda-mode-map (make-sparse-keymap)
3493 "Keymap for `org-agenda-mode'.")
3494
3495 (defvar org-agenda-menu)
3496 (defvar org-agenda-follow-mode nil)
3497 (defvar org-agenda-buffer-name "*Org Agenda*")
3498 (defvar org-agenda-redo-command nil)
3499 (defvar org-agenda-mode-hook nil)
3500
3501 ;;;###autoload
3502 (defun org-agenda-mode ()
3503 "Mode for time-sorted view on action items in Org-mode files.
3504
3505 The following commands are available:
3506
3507 \\{org-agenda-mode-map}"
3508 (interactive)
3509 (kill-all-local-variables)
3510 (setq major-mode 'org-agenda-mode)
3511 (setq mode-name "Org-Agenda")
3512 (use-local-map org-agenda-mode-map)
3513 (easy-menu-add org-agenda-menu)
3514 (if org-startup-truncated (setq truncate-lines t))
3515 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3516 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3517 (setq org-agenda-follow-mode nil)
3518 (easy-menu-change
3519 '("Agenda") "Agenda Files"
3520 (append
3521 (list
3522 ["Edit File List" (customize-variable 'org-agenda-files) t]
3523 "--")
3524 (mapcar 'org-file-menu-entry org-agenda-files)))
3525 (org-agenda-set-mode-name)
3526 (apply
3527 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3528 org-agenda-mode-hook))
3529
3530 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3531 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3532 (define-key org-agenda-mode-map " " 'org-agenda-show)
3533 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3534 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3535 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3536 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3537 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3538 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3539 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3540 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3541 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3542
3543 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3544 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3545 (while l (define-key org-agenda-mode-map
3546 (int-to-string (pop l)) 'digit-argument)))
3547
3548 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3549 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3550 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3551 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3552 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3553 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3554 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3555 (define-key org-agenda-mode-map "n" 'next-line)
3556 (define-key org-agenda-mode-map "p" 'previous-line)
3557 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3558 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3559 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3560 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3561 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3562 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3563 (eval-after-load "calendar"
3564 '(define-key calendar-mode-map org-calendar-to-agenda-key
3565 'org-calendar-goto-agenda))
3566 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3567 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3568 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3569 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3570 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3571 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3572 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3573 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3574 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3575 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3576 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3577 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3578 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3579
3580 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3581 "Local keymap for agenda entries from Org-mode.")
3582
3583 (define-key org-agenda-keymap
3584 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3585 (define-key org-agenda-keymap
3586 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3587
3588 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3589 '("Agenda"
3590 ("Agenda Files")
3591 "--"
3592 ["Show" org-agenda-show t]
3593 ["Go To (other window)" org-agenda-goto t]
3594 ["Go To (one window)" org-agenda-switch-to t]
3595 ["Follow Mode" org-agenda-follow-mode
3596 :style toggle :selected org-agenda-follow-mode :active t]
3597 "--"
3598 ["Cycle TODO" org-agenda-todo t]
3599 ("Reschedule"
3600 ["Reschedule +1 day" org-agenda-date-later t]
3601 ["Reschedule -1 day" org-agenda-date-earlier t]
3602 "--"
3603 ["Reschedule to ..." org-agenda-date-prompt t])
3604 ("Priority"
3605 ["Set Priority" org-agenda-priority t]
3606 ["Increase Priority" org-agenda-priority-up t]
3607 ["Decrease Priority" org-agenda-priority-down t]
3608 ["Show Priority" org-agenda-show-priority t])
3609 "--"
3610 ["Rebuild buffer" org-agenda-redo t]
3611 ["Goto Today" org-agenda-goto-today t]
3612 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3613 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3614 "--"
3615 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3616 :style radio :selected (equal org-agenda-ndays 1)]
3617 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3618 :style radio :selected (equal org-agenda-ndays 7)]
3619 "--"
3620 ["Include Diary" org-agenda-toggle-diary
3621 :style toggle :selected org-agenda-include-diary :active t]
3622 ["Use Time Grid" org-agenda-toggle-time-grid
3623 :style toggle :selected org-agenda-use-time-grid :active t]
3624 "--"
3625 ["New Diary Entry" org-agenda-diary-entry t]
3626 ("Calendar Commands"
3627 ["Goto Calendar" org-agenda-goto-calendar t]
3628 ["Phases of the Moon" org-agenda-phases-of-moon t]
3629 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3630 ["Holidays" org-agenda-holidays t]
3631 ["Convert" org-agenda-convert-date t])
3632 "--"
3633 ["Quit" org-agenda-quit t]
3634 ["Exit and Release Buffers" org-agenda-exit t]
3635 ))
3636
3637 (defvar org-agenda-markers nil
3638 "List of all currently active markers created by `org-agenda'.")
3639 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3640 "Creation time of the last agenda marker.")
3641
3642 (defun org-agenda-new-marker (&optional pos)
3643 "Return a new agenda marker.
3644 Org-mode keeps a list of these markers and resets them when they are
3645 no longer in use."
3646 (let ((m (copy-marker (or pos (point)))))
3647 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3648 (push m org-agenda-markers)
3649 m))
3650
3651 (defun org-agenda-maybe-reset-markers (&optional force)
3652 "Reset markers created by `org-agenda'. But only if they are old enough."
3653 (if (or force
3654 (> (- (time-to-seconds (current-time))
3655 org-agenda-last-marker-time)
3656 5))
3657 (while org-agenda-markers
3658 (move-marker (pop org-agenda-markers) nil))))
3659
3660 (defvar org-agenda-new-buffers nil
3661 "Buffers created to visit agenda files.")
3662
3663 (defun org-get-agenda-file-buffer (file)
3664 "Get a buffer visiting FILE. If the buffer needs to be created, add
3665 it to the list of buffers which might be released later."
3666 (let ((buf (find-buffer-visiting file)))
3667 (if buf
3668 buf ; just return it
3669 ;; Make a new buffer and remember it
3670 (setq buf (find-file-noselect file))
3671 (if buf (push buf org-agenda-new-buffers))
3672 buf)))
3673
3674 (defun org-release-buffers (blist)
3675 "Release all buffers in list, asking the user for confirmation when needed.
3676 When a buffer is unmodified, it is just killed. When modified, it is saved
3677 \(if the user agrees) and then killed."
3678 (let (buf file)
3679 (while (setq buf (pop blist))
3680 (setq file (buffer-file-name buf))
3681 (when (and (buffer-modified-p buf)
3682 file
3683 (y-or-n-p (format "Save file %s? " file)))
3684 (with-current-buffer buf (save-buffer)))
3685 (kill-buffer buf))))
3686
3687 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3688
3689 (defun org-timeline (&optional include-all)
3690 "Show a time-sorted view of the entries in the current org file.
3691 Only entries with a time stamp of today or later will be listed. With
3692 one \\[universal-argument] prefix argument, past entries will also be listed.
3693 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3694 under the current date.
3695 If the buffer contains an active region, only check the region for
3696 dates."
3697 (interactive "P")
3698 (require 'calendar)
3699 (org-agenda-maybe-reset-markers 'force)
3700 (org-compile-prefix-format org-timeline-prefix-format)
3701 (let* ((dopast include-all)
3702 (dotodo (equal include-all '(16)))
3703 (entry (buffer-file-name))
3704 (org-agenda-files (list (buffer-file-name)))
3705 (date (calendar-current-date))
3706 (win (selected-window))
3707 (pos1 (point))
3708 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3709 (end (if (org-region-active-p) (region-end) (point-max)))
3710 (day-numbers (org-get-all-dates beg end 'no-ranges
3711 t)) ; always include today
3712 (today (time-to-days (current-time)))
3713 (org-respect-restriction t)
3714 (past t)
3715 s e rtn d)
3716 (setq org-agenda-redo-command
3717 (list 'progn
3718 (list 'switch-to-buffer-other-window (current-buffer))
3719 (list 'org-timeline (list 'quote include-all))))
3720 (if (not dopast)
3721 ;; Remove past dates from the list of dates.
3722 (setq day-numbers (delq nil (mapcar (lambda(x)
3723 (if (>= x today) x nil))
3724 day-numbers))))
3725 (switch-to-buffer-other-window
3726 (get-buffer-create org-agenda-buffer-name))
3727 (setq buffer-read-only nil)
3728 (erase-buffer)
3729 (org-agenda-mode) (setq buffer-read-only nil)
3730 (while (setq d (pop day-numbers))
3731 (if (and (>= d today)
3732 dopast
3733 past)
3734 (progn
3735 (setq past nil)
3736 (insert (make-string 79 ?-) "\n")))
3737 (setq date (calendar-gregorian-from-absolute d))
3738 (setq s (point))
3739 (if dotodo
3740 (setq rtn (org-agenda-get-day-entries
3741 entry date :todo :timestamp))
3742 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3743 (if (or rtn (equal d today))
3744 (progn
3745 (insert (calendar-day-name date) " "
3746 (number-to-string (extract-calendar-day date)) " "
3747 (calendar-month-name (extract-calendar-month date)) " "
3748 (number-to-string (extract-calendar-year date)) "\n")
3749 (put-text-property s (1- (point)) 'face
3750 'org-link)
3751 (if (equal d today)
3752 (put-text-property s (1- (point)) 'org-today t))
3753 (insert (org-finalize-agenda-entries rtn) "\n")
3754 (put-text-property s (1- (point)) 'day d))))
3755 (goto-char (point-min))
3756 (setq buffer-read-only t)
3757 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3758 (point-min)))
3759 (when (not org-select-timeline-window)
3760 (select-window win)
3761 (goto-char pos1))))
3762
3763 ;;;###autoload
3764 (defun org-agenda (&optional include-all start-day ndays)
3765 "Produce a weekly view from all files in variable `org-agenda-files'.
3766 The view will be for the current week, but from the overview buffer you
3767 will be able to go to other weeks.
3768 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3769 also be shown, under the current date.
3770 START-DAY defaults to TODAY, or to the most recent match for the weekday
3771 given in `org-agenda-start-on-weekday'.
3772 NDAYS defaults to `org-agenda-ndays'."
3773 (interactive "P")
3774 (org-agenda-maybe-reset-markers 'force)
3775 (org-compile-prefix-format org-agenda-prefix-format)
3776 (require 'calendar)
3777 (let* ((org-agenda-start-on-weekday
3778 (if (or (equal ndays 1)
3779 (and (null ndays) (equal 1 org-agenda-ndays)))
3780 nil org-agenda-start-on-weekday))
3781 (files (copy-sequence org-agenda-files))
3782 (win (selected-window))
3783 (today (time-to-days (current-time)))
3784 (sd (or start-day today))
3785 (start (if (or (null org-agenda-start-on-weekday)
3786 (< org-agenda-ndays 7))
3787 sd
3788 (let* ((nt (calendar-day-of-week
3789 (calendar-gregorian-from-absolute sd)))
3790 (n1 org-agenda-start-on-weekday)
3791 (d (- nt n1)))
3792 (- sd (+ (if (< d 0) 7 0) d)))))
3793 (day-numbers (list start))
3794 (inhibit-redisplay t)
3795 s e rtn rtnall file date d start-pos end-pos todayp nd)
3796 (setq org-agenda-redo-command
3797 (list 'org-agenda (list 'quote include-all) start-day ndays))
3798 ;; Make the list of days
3799 (setq ndays (or ndays org-agenda-ndays)
3800 nd ndays)
3801 (while (> ndays 1)
3802 (push (1+ (car day-numbers)) day-numbers)
3803 (setq ndays (1- ndays)))
3804 (setq day-numbers (nreverse day-numbers))
3805 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3806 (progn
3807 (delete-other-windows)
3808 (switch-to-buffer-other-window
3809 (get-buffer-create org-agenda-buffer-name))))
3810 (setq buffer-read-only nil)
3811 (erase-buffer)
3812 (org-agenda-mode) (setq buffer-read-only nil)
3813 (set (make-local-variable 'starting-day) (car day-numbers))
3814 (set (make-local-variable 'include-all-loc) include-all)
3815 (when (and (or include-all org-agenda-include-all-todo)
3816 (member today day-numbers))
3817 (setq files org-agenda-files
3818 rtnall nil)
3819 (while (setq file (pop files))
3820 (catch 'nextfile
3821 (org-check-agenda-file file)
3822 (setq date (calendar-gregorian-from-absolute today)
3823 rtn (org-agenda-get-day-entries
3824 file date :todo))
3825 (setq rtnall (append rtnall rtn))))
3826 (when rtnall
3827 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3828 (add-text-properties (point-min) (1- (point))
3829 (list 'face 'org-link))
3830 (insert (org-finalize-agenda-entries rtnall) "\n")))
3831 (while (setq d (pop day-numbers))
3832 (setq date (calendar-gregorian-from-absolute d)
3833 s (point))
3834 (if (or (setq todayp (= d today))
3835 (and (not start-pos) (= d sd)))
3836 (setq start-pos (point))
3837 (if (and start-pos (not end-pos))
3838 (setq end-pos (point))))
3839 (setq files org-agenda-files
3840 rtnall nil)
3841 (while (setq file (pop files))
3842 (catch 'nextfile
3843 (org-check-agenda-file file)
3844 (setq rtn (org-agenda-get-day-entries file date))
3845 (setq rtnall (append rtnall rtn))))
3846 (if org-agenda-include-diary
3847 (progn
3848 (require 'diary-lib)
3849 (setq rtn (org-get-entries-from-diary date))
3850 (setq rtnall (append rtnall rtn))))
3851 (if (or rtnall org-agenda-show-all-dates)
3852 (progn
3853 (insert (format "%-9s %2d %s %4d\n"
3854 (calendar-day-name date)
3855 (extract-calendar-day date)
3856 (calendar-month-name (extract-calendar-month date))
3857 (extract-calendar-year date)))
3858 (put-text-property s (1- (point)) 'face
3859 'org-link)
3860 (if rtnall (insert
3861 (org-finalize-agenda-entries ;; FIXME: condition needed
3862 (org-agenda-add-time-grid-maybe
3863 rtnall nd todayp))
3864 "\n"))
3865 (put-text-property s (1- (point)) 'day d))))
3866 (goto-char (point-min))
3867 (setq buffer-read-only t)
3868 (if org-fit-agenda-window
3869 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3870 (/ (frame-height) 2)))
3871 (unless (and (pos-visible-in-window-p (point-min))
3872 (pos-visible-in-window-p (point-max)))
3873 (goto-char (1- (point-max)))
3874 (recenter -1)
3875 (if (not (pos-visible-in-window-p (or start-pos 1)))
3876 (progn
3877 (goto-char (or start-pos 1))
3878 (recenter 1))))
3879 (goto-char (or start-pos 1))
3880 (if (not org-select-agenda-window) (select-window win))
3881 (message "")))
3882
3883 (defun org-check-agenda-file (file)
3884 "Make sure FILE exists. If not, ask user what to do."
3885 ;; FIXME: this does not correctly change the menus
3886 ;; Could probably be fixed by explicitly going to the buffer.
3887 (when (not (file-exists-p file))
3888 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3889 file)
3890 (let ((r (downcase (read-char-exclusive))))
3891 (cond
3892 ((equal r ?r)
3893 (org-remove-file file)
3894 (throw 'nextfile t))
3895 (t (error "Abort"))))))
3896
3897 (defun org-agenda-quit ()
3898 "Exit agenda by removing the window or the buffer."
3899 (interactive)
3900 (let ((buf (current-buffer)))
3901 (if (not (one-window-p)) (delete-window))
3902 (kill-buffer buf)
3903 (org-agenda-maybe-reset-markers 'force)))
3904
3905 (defun org-agenda-exit ()
3906 "Exit agenda by removing the window or the buffer.
3907 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3908 Org-mode buffers visited directly by the user will not be touched."
3909 (interactive)
3910 (org-release-buffers org-agenda-new-buffers)
3911 (setq org-agenda-new-buffers nil)
3912 (org-agenda-quit))
3913
3914 (defun org-agenda-redo ()
3915 "Rebuild Agenda."
3916 (interactive)
3917 (eval org-agenda-redo-command))
3918
3919 (defun org-agenda-goto-today ()
3920 "Go to today."
3921 (interactive)
3922 (if (boundp 'starting-day)
3923 (let ((cmd (car org-agenda-redo-command))
3924 (iall (nth 1 org-agenda-redo-command))
3925 (nday (nth 3 org-agenda-redo-command)))
3926 (eval (list cmd iall nil nday)))
3927 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3928 (point-min)))))
3929
3930 (defun org-agenda-later (arg)
3931 "Go forward in time by `org-agenda-ndays' days.
3932 With prefix ARG, go forward that many times `org-agenda-ndays'."
3933 (interactive "p")
3934 (unless (boundp 'starting-day)
3935 (error "Not allowed"))
3936 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3937 (+ starting-day (* arg org-agenda-ndays))))
3938
3939 (defun org-agenda-earlier (arg)
3940 "Go back in time by `org-agenda-ndays' days.
3941 With prefix ARG, go back that many times `org-agenda-ndays'."
3942 (interactive "p")
3943 (unless (boundp 'starting-day)
3944 (error "Not allowed"))
3945 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3946 (- starting-day (* arg org-agenda-ndays))))
3947
3948 (defun org-agenda-week-view ()
3949 "Switch to weekly view for agenda."
3950 (interactive)
3951 (unless (boundp 'starting-day)
3952 (error "Not allowed"))
3953 (setq org-agenda-ndays 7)
3954 (org-agenda include-all-loc
3955 (or (get-text-property (point) 'day)
3956 starting-day))
3957 (org-agenda-set-mode-name)
3958 (message "Switched to week view"))
3959
3960 (defun org-agenda-day-view ()
3961 "Switch to weekly view for agenda."
3962 (interactive)
3963 (unless (boundp 'starting-day)
3964 (error "Not allowed"))
3965 (setq org-agenda-ndays 1)
3966 (org-agenda include-all-loc
3967 (or (get-text-property (point) 'day)
3968 starting-day))
3969 (org-agenda-set-mode-name)
3970 (message "Switched to day view"))
3971
3972 (defun org-agenda-next-date-line (&optional arg)
3973 "Jump to the next line indicating a date in agenda buffer."
3974 (interactive "p")
3975 (beginning-of-line 1)
3976 (if (looking-at "^\\S-") (forward-char 1))
3977 (if (not (re-search-forward "^\\S-" nil t arg))
3978 (progn
3979 (backward-char 1)
3980 (error "No next date after this line in this buffer")))
3981 (goto-char (match-beginning 0)))
3982
3983 (defun org-agenda-previous-date-line (&optional arg)
3984 "Jump to the next line indicating a date in agenda buffer."
3985 (interactive "p")
3986 (beginning-of-line 1)
3987 (if (not (re-search-backward "^\\S-" nil t arg))
3988 (error "No previous date before this line in this buffer")))
3989
3990 ;; Initialize the highlight
3991 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3992 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3993 'face 'highlight)
3994
3995 (defun org-highlight (begin end &optional buffer)
3996 "Highlight a region with overlay."
3997 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3998 org-hl begin end (or buffer (current-buffer))))
3999
4000 (defun org-unhighlight ()
4001 "Detach overlay INDEX."
4002 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4003
4004
4005 (defun org-agenda-follow-mode ()
4006 "Toggle follow mode in an agenda buffer."
4007 (interactive)
4008 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4009 (org-agenda-set-mode-name)
4010 (message "Follow mode is %s"
4011 (if org-agenda-follow-mode "on" "off")))
4012
4013 (defun org-agenda-toggle-diary ()
4014 "Toggle follow mode in an agenda buffer."
4015 (interactive)
4016 (setq org-agenda-include-diary (not org-agenda-include-diary))
4017 (org-agenda-redo)
4018 (org-agenda-set-mode-name)
4019 (message "Diary inclusion turned %s"
4020 (if org-agenda-include-diary "on" "off")))
4021
4022 (defun org-agenda-toggle-time-grid ()
4023 "Toggle follow mode in an agenda buffer."
4024 (interactive)
4025 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4026 (org-agenda-redo)
4027 (org-agenda-set-mode-name)
4028 (message "Time-grid turned %s"
4029 (if org-agenda-use-time-grid "on" "off")))
4030
4031 (defun org-agenda-set-mode-name ()
4032 "Set the mode name to indicate all the small mode settings."
4033 (setq mode-name
4034 (concat "Org-Agenda"
4035 (if (equal org-agenda-ndays 1) " Day" "")
4036 (if (equal org-agenda-ndays 7) " Week" "")
4037 (if org-agenda-follow-mode " Follow" "")
4038 (if org-agenda-include-diary " Diary" "")
4039 (if org-agenda-use-time-grid " Grid" "")))
4040 (force-mode-line-update))
4041
4042 (defun org-agenda-post-command-hook ()
4043 (and (eolp) (not (bolp)) (backward-char 1))
4044 (if (and org-agenda-follow-mode
4045 (get-text-property (point) 'org-marker))
4046 (org-agenda-show)))
4047
4048 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4049
4050 (defun org-get-entries-from-diary (date)
4051 "Get the (Emacs Calendar) diary entries for DATE."
4052 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4053 (diary-display-hook '(fancy-diary-display))
4054 (list-diary-entries-hook
4055 (cons 'org-diary-default-entry list-diary-entries-hook))
4056 (diary-file-name-prefix-function nil) ; turn this feature off
4057 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4058 entries
4059 (org-disable-agenda-to-diary t))
4060 (save-excursion
4061 (save-window-excursion
4062 (list-diary-entries date 1)))
4063 (if (not (get-buffer fancy-diary-buffer))
4064 (setq entries nil)
4065 (with-current-buffer fancy-diary-buffer
4066 (setq buffer-read-only nil)
4067 (if (= (point-max) 1)
4068 ;; No entries
4069 (setq entries nil)
4070 ;; Omit the date and other unnecessary stuff
4071 (org-agenda-cleanup-fancy-diary)
4072 ;; Add prefix to each line and extend the text properties
4073 (if (= (point-max) 1)
4074 (setq entries nil)
4075 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4076 (set-buffer-modified-p nil)
4077 (kill-buffer fancy-diary-buffer)))
4078 (when entries
4079 (setq entries (org-split-string entries "\n"))
4080 (setq entries
4081 (mapcar
4082 (lambda (x)
4083 (setq x (org-format-agenda-item "" x "Diary" 'time))
4084 ;; Extend the text properties to the beginning of the line
4085 (add-text-properties
4086 0 (length x)
4087 (text-properties-at (1- (length x)) x)
4088 x)
4089 x)
4090 entries)))))
4091
4092 (defun org-agenda-cleanup-fancy-diary ()
4093 "Remove unwanted stuff in buffer created by fancy-diary-display.
4094 This gets rid of the date, the underline under the date, and
4095 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4096 date. Itt also removes lines that contain only whitespace."
4097 (goto-char (point-min))
4098 (if (looking-at ".*?:[ \t]*")
4099 (progn
4100 (replace-match "")
4101 (re-search-forward "\n=+$" nil t)
4102 (replace-match "")
4103 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4104 (re-search-forward "\n=+$" nil t)
4105 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4106 (goto-char (point-min))
4107 (while (re-search-forward "^ +\n" nil t)
4108 (replace-match ""))
4109 (goto-char (point-min))
4110 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4111 (replace-match "")))
4112
4113 ;; Make sure entries from the diary have the right text properties.
4114 (eval-after-load "diary-lib"
4115 '(if (boundp 'diary-modify-entry-list-string-function)
4116 ;; We can rely on the hook, nothing to do
4117 nil
4118 ;; Hook not avaiable, must use advice to make this work
4119 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4120 "Make the position visible."
4121 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4122 (stringp string)
4123 (buffer-file-name))
4124 (setq string (org-modify-diary-entry-string string))))))
4125
4126 (defun org-modify-diary-entry-string (string)
4127 "Add text properties to string, allowing org-mode to act on it."
4128 (add-text-properties
4129 0 (length string)
4130 (list 'mouse-face 'highlight
4131 'keymap org-agenda-keymap
4132 'help-echo
4133 (format
4134 "mouse-2 or RET jump to diary file %s"
4135 (abbreviate-file-name (buffer-file-name)))
4136 'org-agenda-diary-link t
4137 'org-marker (org-agenda-new-marker (point-at-bol)))
4138 string)
4139 string)
4140
4141 (defun org-diary-default-entry ()
4142 "Add a dummy entry to the diary.
4143 Needed to avoid empty dates which mess up holiday display."
4144 ;; Catch the error if dealing with the new add-to-diary-alist
4145 (when org-disable-agenda-to-diary
4146 (condition-case nil
4147 (add-to-diary-list original-date "Org-mode dummy" "")
4148 (error
4149 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4150
4151 (defun org-add-file (&optional file)
4152 "Add current file to the list of files in variable `org-agenda-files'.
4153 These are the files which are being checked for agenda entries.
4154 Optional argument FILE means, use this file instead of the current.
4155 It is possible (but not recommended) to add this function to the
4156 `org-mode-hook'."
4157 (interactive)
4158 (catch 'exit
4159 (let* ((file (or file (buffer-file-name)
4160 (if (interactive-p)
4161 (error "Buffer is not visiting a file")
4162 (throw 'exit nil))))
4163 (true-file (file-truename file))
4164 (afile (abbreviate-file-name file))
4165 (present (delq nil (mapcar
4166 (lambda (x)
4167 (equal true-file (file-truename x)))
4168 org-agenda-files))))
4169 (if (not present)
4170 (progn
4171 (setq org-agenda-files
4172 (cons afile org-agenda-files))
4173 ;; Make sure custom.el does not end up with Org-mode
4174 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4175 (customize-save-variable 'org-agenda-files org-agenda-files))
4176 (org-install-agenda-files-menu)
4177 (message "Added file: %s" afile))
4178 (message "File was already in list: %s" afile)))))
4179
4180 (defun org-remove-file (&optional file)
4181 "Remove current file from the list of files in variable `org-agenda-files'.
4182 These are the files which are being checked for agenda entries.
4183 Optional argument FILE means, use this file instead of the current."
4184 (interactive)
4185 (let* ((file (or file (buffer-file-name)))
4186 (true-file (file-truename file))
4187 (afile (abbreviate-file-name file))
4188 (files (delq nil (mapcar
4189 (lambda (x)
4190 (if (equal true-file
4191 (file-truename x))
4192 nil x))
4193 org-agenda-files))))
4194 (if (not (= (length files) (length org-agenda-files)))
4195 (progn
4196 (setq org-agenda-files files)
4197 (customize-save-variable 'org-agenda-files org-agenda-files)
4198 (org-install-agenda-files-menu)
4199 (message "Removed file: %s" afile))
4200 (message "File was not in list: %s" afile))))
4201
4202 (defun org-file-menu-entry (file)
4203 (vector file (list 'find-file file) t))
4204
4205 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4206 "Return a list of all relevant day numbers from BEG to END buffer positions.
4207 If NO-RANGES is non-nil, include only the start and end dates of a range,
4208 not every single day in the range. If FORCE-TODAY is non-nil, make
4209 sure that TODAY is included in the list."
4210 (let (dates date day day1 day2 ts1 ts2)
4211 (if force-today
4212 (setq dates (list (time-to-days (current-time)))))
4213 (save-excursion
4214 (goto-char beg)
4215 (while (re-search-forward org-ts-regexp end t)
4216 (setq day (time-to-days (org-time-string-to-time
4217 (substring (match-string 1) 0 10))))
4218 (or (memq day dates) (push day dates)))
4219 (unless no-ranges
4220 (goto-char beg)
4221 (while (re-search-forward org-tr-regexp end t)
4222 (setq ts1 (substring (match-string 1) 0 10)
4223 ts2 (substring (match-string 2) 0 10)
4224 day1 (time-to-days (org-time-string-to-time ts1))
4225 day2 (time-to-days (org-time-string-to-time ts2)))
4226 (while (< (setq day1 (1+ day1)) day2)
4227 (or (memq day1 dates) (push day1 dates)))))
4228 (sort dates '<))))
4229
4230 ;;;###autoload
4231 (defun org-diary (&rest args)
4232 "Return diary information from org-files.
4233 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4234 It accesses org files and extracts information from those files to be
4235 listed in the diary. The function accepts arguments specifying what
4236 items should be listed. The following arguments are allowed:
4237
4238 :timestamp List the headlines of items containing a date stamp or
4239 date range matching the selected date. Deadlines will
4240 also be listed, on the expiration day.
4241
4242 :deadline List any deadlines past due, or due within
4243 `org-deadline-warning-days'. The listing occurs only
4244 in the diary for *today*, not at any other date. If
4245 an entry is marked DONE, it is no longer listed.
4246
4247 :scheduled List all items which are scheduled for the given date.
4248 The diary for *today* also contains items which were
4249 scheduled earlier and are not yet marked DONE.
4250
4251 :todo List all TODO items from the org-file. This may be a
4252 long list - so this is not turned on by default.
4253 Like deadlines, these entries only show up in the
4254 diary for *today*, not at any other date.
4255
4256 The call in the diary file should look like this:
4257
4258 &%%(org-diary) ~/path/to/some/orgfile.org
4259
4260 Use a separate line for each org file to check. Or, if you omit the file name,
4261 all files listed in `org-agenda-files' will be checked automatically:
4262
4263 &%%(org-diary)
4264
4265 If you don't give any arguments (as in the example above), the default
4266 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4267 also be written as
4268
4269 &%%(org-diary :deadline :timestamp :scheduled)
4270
4271 The function expects the lisp variables `entry' and `date' to be provided
4272 by the caller, because this is how the calendar works. Don't use this
4273 function from a program - use `org-agenda-get-day-entries' instead."
4274 (org-agenda-maybe-reset-markers)
4275 (org-compile-prefix-format org-agenda-prefix-format)
4276 (setq args (or args '(:deadline :scheduled :timestamp)))
4277 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4278 (list entry)
4279 org-agenda-files))
4280 file rtn results)
4281 ;; If this is called during org-agenda, don't return any entries to
4282 ;; the calendar. Org Agenda will list these entries itself.
4283 (if org-disable-agenda-to-diary (setq files nil))
4284 (while (setq file (pop files))
4285 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4286 (setq results (append results rtn)))
4287 (if results
4288 (concat (org-finalize-agenda-entries results) "\n"))))
4289
4290 (defun org-agenda-get-day-entries (file date &rest args)
4291 "Does the work for `org-diary' and `org-agenda'.
4292 FILE is the path to a file to be checked for entries. DATE is date like
4293 the one returned by `calendar-current-date'. ARGS are symbols indicating
4294 which kind of entries should be extracted. For details about these, see
4295 the documentation of `org-diary'."
4296 (setq args (or args '(:deadline :scheduled :timestamp)))
4297 (let* ((org-startup-with-deadline-check nil)
4298 (org-startup-folded nil)
4299 (buffer (if (file-exists-p file)
4300 (org-get-agenda-file-buffer file)
4301 (error "No such file %s" file)))
4302 arg results rtn)
4303 (if (not buffer)
4304 ;; If file does not exist, make sure an error message ends up in diary
4305 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4306 (with-current-buffer buffer
4307 (unless (eq major-mode 'org-mode)
4308 (error "Agenda file %s is not in `org-mode'" file))
4309 (let ((case-fold-search nil))
4310 (save-excursion
4311 (save-restriction
4312 (if org-respect-restriction
4313 (if (org-region-active-p)
4314 ;; Respect a region to restrict search
4315 (narrow-to-region (region-beginning) (region-end)))
4316 ;; If we work for the calendar or many files,
4317 ;; get rid of any restriction
4318 (widen))
4319 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4320 (while (setq arg (pop args))
4321 (cond
4322 ((and (eq arg :todo)
4323 (equal date (calendar-current-date)))
4324 (setq rtn (org-agenda-get-todos))
4325 (setq results (append results rtn)))
4326 ((eq arg :timestamp)
4327 (setq rtn (org-agenda-get-blocks))
4328 (setq results (append results rtn))
4329 (setq rtn (org-agenda-get-timestamps))
4330 (setq results (append results rtn)))
4331 ((eq arg :scheduled)
4332 (setq rtn (org-agenda-get-scheduled))
4333 (setq results (append results rtn)))
4334 ((and (eq arg :deadline)
4335 (equal date (calendar-current-date)))
4336 (setq rtn (org-agenda-get-deadlines))
4337 (setq results (append results rtn))))))))
4338 results))))
4339
4340 (defun org-entry-is-done-p ()
4341 "Is the current entry marked DONE?"
4342 (save-excursion
4343 (and (re-search-backward "[\r\n]\\*" nil t)
4344 (looking-at org-nl-done-regexp))))
4345
4346 (defun org-at-date-range-p ()
4347 "Is the cursor inside a date range?"
4348 (interactive)
4349 (save-excursion
4350 (catch 'exit
4351 (let ((pos (point)))
4352 (skip-chars-backward "^<\r\n")
4353 (skip-chars-backward "<")
4354 (and (looking-at org-tr-regexp)
4355 (>= (match-end 0) pos)
4356 (throw 'exit t))
4357 (skip-chars-backward "^<\r\n")
4358 (skip-chars-backward "<")
4359 (and (looking-at org-tr-regexp)
4360 (>= (match-end 0) pos)
4361 (throw 'exit t)))
4362 nil)))
4363
4364 (defun org-agenda-get-todos ()
4365 "Return the TODO information for agenda display."
4366 (let* ((props (list 'face nil
4367 'done-face 'org-done
4368 'mouse-face 'highlight
4369 'keymap org-agenda-keymap
4370 'help-echo
4371 (format "mouse-2 or RET jump to org file %s"
4372 (abbreviate-file-name (buffer-file-name)))))
4373 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4374 "[^\n\r]*\\)"))
4375 marker priority
4376 ee txt)
4377 (goto-char (point-min))
4378 (while (re-search-forward regexp nil t)
4379 (goto-char (match-beginning 1))
4380 (setq marker (org-agenda-new-marker (point-at-bol))
4381 txt (org-format-agenda-item "" (match-string 1))
4382 priority
4383 (+ (org-get-priority txt)
4384 (if org-todo-kwd-priority-p
4385 (- org-todo-kwd-max-priority -2
4386 (length
4387 (member (match-string 2) org-todo-keywords)))
4388 1)))
4389 (add-text-properties
4390 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4391 'priority priority)
4392 props)
4393 txt)
4394 (push txt ee)
4395 (goto-char (match-end 1)))
4396 (nreverse ee)))
4397
4398 (defconst org-agenda-no-heading-message
4399 "No heading for this item in buffer or region")
4400
4401 (defun org-agenda-get-timestamps ()
4402 "Return the date stamp information for agenda display."
4403 (let* ((props (list 'face nil
4404 'mouse-face 'highlight
4405 'keymap org-agenda-keymap
4406 'help-echo
4407 (format "mouse-2 or RET jump to org file %s"
4408 (abbreviate-file-name (buffer-file-name)))))
4409 (regexp (regexp-quote
4410 (substring
4411 (format-time-string
4412 (car org-time-stamp-formats)
4413 (apply 'encode-time ; DATE bound by calendar
4414 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4415 0 11)))
4416 marker hdmarker deadlinep scheduledp donep tmp priority
4417 ee txt timestr)
4418 (goto-char (point-min))
4419 (while (re-search-forward regexp nil t)
4420 (if (not (save-match-data (org-at-date-range-p)))
4421 (progn
4422 (setq marker (org-agenda-new-marker (match-beginning 0))
4423 tmp (buffer-substring (max (point-min)
4424 (- (match-beginning 0)
4425 org-ds-keyword-length))
4426 (match-beginning 0))
4427 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4428 deadlinep (string-match org-deadline-regexp tmp)
4429 scheduledp (string-match org-scheduled-regexp tmp)
4430 donep (org-entry-is-done-p))
4431 (if (string-match ">" timestr)
4432 ;; substring should only run to end of time stamp
4433 (setq timestr (substring timestr 0 (match-end 0))))
4434 (save-excursion
4435 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4436 (progn
4437 (goto-char (match-end 1))
4438 (setq hdmarker (org-agenda-new-marker))
4439 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4440 (setq txt (org-format-agenda-item
4441 (format "%s%s"
4442 (if deadlinep "Deadline: " "")
4443 (if scheduledp "Scheduled: " ""))
4444 (match-string 1) nil timestr)))
4445 (setq txt org-agenda-no-heading-message))
4446 (setq priority (org-get-priority txt))
4447 (add-text-properties
4448 0 (length txt) (append (list 'org-marker marker
4449 'org-hd-marker hdmarker) props)
4450 txt)
4451 (if deadlinep
4452 (add-text-properties
4453 0 (length txt)
4454 (list 'face
4455 (if donep 'org-done 'org-warning)
4456 'undone-face 'org-warning
4457 'done-face 'org-done
4458 'priority (+ 100 priority))
4459 txt)
4460 (if scheduledp
4461 (add-text-properties
4462 0 (length txt)
4463 (list 'face 'org-scheduled-today
4464 'undone-face 'org-scheduled-today
4465 'done-face 'org-done
4466 priority (+ 99 priority))
4467 txt)
4468 (add-text-properties
4469 0 (length txt)
4470 (list 'priority priority) txt)))
4471 (push txt ee))
4472 (outline-next-heading))))
4473 (nreverse ee)))
4474
4475 (defun org-agenda-get-deadlines ()
4476 "Return the deadline information for agenda display."
4477 (let* ((wdays org-deadline-warning-days)
4478 (props (list 'mouse-face 'highlight
4479 'keymap org-agenda-keymap
4480 'help-echo
4481 (format "mouse-2 or RET jump to org file %s"
4482 (abbreviate-file-name (buffer-file-name)))))
4483 (regexp org-deadline-time-regexp)
4484 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4485 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4486 d2 diff pos pos1
4487 ee txt head)
4488 (goto-char (point-min))
4489 (while (re-search-forward regexp nil t)
4490 (setq pos (1- (match-beginning 1))
4491 d2 (time-to-days
4492 (org-time-string-to-time (match-string 1)))
4493 diff (- d2 d1))
4494 ;; When to show a deadline in the calendar:
4495 ;; If the expiration is within wdays warning time.
4496 ;; Past-due deadlines are only shown on the current date
4497 (if (and (< diff wdays) todayp (not (= diff 0)))
4498 (save-excursion
4499 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4500 (progn
4501 (goto-char (match-end 0))
4502 (setq pos1 (match-end 1))
4503 (setq head (buffer-substring-no-properties
4504 (point)
4505 (progn (skip-chars-forward "^\r\n")
4506 (point))))
4507 (if (string-match org-looking-at-done-regexp head)
4508 (setq txt nil)
4509 (setq txt (org-format-agenda-item
4510 (format "In %3d d.: " diff) head))))
4511 (setq txt org-agenda-no-heading-message))
4512 (when txt
4513 (add-text-properties
4514 0 (length txt)
4515 (append
4516 (list 'org-marker (org-agenda-new-marker pos)
4517 'org-hd-marker (org-agenda-new-marker pos1)
4518 'priority (+ (- 10 diff) (org-get-priority txt))
4519 'face (cond ((<= diff 0) 'org-warning)
4520 ((<= diff 5) 'org-scheduled-previously)
4521 (t nil))
4522 'undone-face (cond
4523 ((<= diff 0) 'org-warning)
4524 ((<= diff 5) 'org-scheduled-previously)
4525 (t nil))
4526 'done-face 'org-done)
4527 props)
4528 txt)
4529 (push txt ee)))))
4530 ee))
4531
4532 (defun org-agenda-get-scheduled ()
4533 "Return the scheduled information for agenda display."
4534 (let* ((props (list 'face 'org-scheduled-previously
4535 'undone-face 'org-scheduled-previously
4536 'done-face 'org-done
4537 'mouse-face 'highlight
4538 'keymap org-agenda-keymap
4539 'help-echo
4540 (format "mouse-2 or RET jump to org file %s"
4541 (abbreviate-file-name (buffer-file-name)))))
4542 (regexp org-scheduled-time-regexp)
4543 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4544 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4545 d2 diff pos pos1
4546 ee txt head)
4547 (goto-char (point-min))
4548 (while (re-search-forward regexp nil t)
4549 (setq pos (1- (match-beginning 1))
4550 d2 (time-to-days
4551 (org-time-string-to-time (match-string 1)))
4552 diff (- d2 d1))
4553 ;; When to show a scheduled item in the calendar:
4554 ;; If it is on or past the date.
4555 (if (and (< diff 0) todayp)
4556 (save-excursion
4557 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4558 (progn
4559 (goto-char (match-end 0))
4560 (setq pos1 (match-end 1))
4561 (setq head (buffer-substring-no-properties
4562 (point)
4563 (progn (skip-chars-forward "^\r\n") (point))))
4564 (if (string-match org-looking-at-done-regexp head)
4565 (setq txt nil)
4566 (setq txt (org-format-agenda-item
4567 (format "Sched.%2dx: " (- 1 diff)) head))))
4568 (setq txt org-agenda-no-heading-message))
4569 (when txt
4570 (add-text-properties
4571 0 (length txt)
4572 (append (list 'org-marker (org-agenda-new-marker pos)
4573 'org-hd-marker (org-agenda-new-marker pos1)
4574 'priority (+ (- 5 diff) (org-get-priority txt)))
4575 props) txt)
4576 (push txt ee)))))
4577 ee))
4578
4579 (defun org-agenda-get-blocks ()
4580 "Return the date-range information for agenda display."
4581 (let* ((props (list 'face nil
4582 'mouse-face 'highlight
4583 'keymap org-agenda-keymap
4584 'help-echo
4585 (format "mouse-2 or RET jump to org file %s"
4586 (abbreviate-file-name (buffer-file-name)))))
4587 (regexp org-tr-regexp)
4588 (d0 (calendar-absolute-from-gregorian date))
4589 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4590 (goto-char (point-min))
4591 (while (re-search-forward regexp nil t)
4592 (setq timestr (match-string 0)
4593 s1 (match-string 1)
4594 s2 (match-string 2)
4595 d1 (time-to-days (org-time-string-to-time s1))
4596 d2 (time-to-days (org-time-string-to-time s2)))
4597 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4598 ;; Only allow days between the limits, because the normal
4599 ;; date stamps will catch the limits.
4600 (save-excursion
4601 (setq marker (org-agenda-new-marker (point)))
4602 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4603 (progn
4604 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4605 (goto-char (match-end 1))
4606 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4607 (setq txt (org-format-agenda-item
4608 (format (if (= d1 d2) "" "(%d/%d): ")
4609 (1+ (- d0 d1)) (1+ (- d2 d1)))
4610 (match-string 1) nil (if (= d0 d1) timestr))))
4611 (setq txt org-agenda-no-heading-message))
4612 (add-text-properties
4613 0 (length txt) (append (list 'org-marker marker
4614 'org-hd-marker hdmarker
4615 'priority (org-get-priority txt))
4616 props)
4617 txt)
4618 (push txt ee)))
4619 (outline-next-heading))
4620 ;; Sort the entries by expiration date.
4621 (nreverse ee)))
4622
4623
4624
4625 (defconst org-plain-time-of-day-regexp
4626 (concat
4627 "\\(\\<[012]?[0-9]"
4628 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4629 "\\(--?"
4630 "\\(\\<[012]?[0-9]"
4631 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4632 "\\)?")
4633 "Regular expression to match a plain time or time range.
4634 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4635 groups carry important information:
4636 0 the full match
4637 1 the first time, range or not
4638 8 the second time, if it is a range.")
4639
4640 (defconst org-stamp-time-of-day-regexp
4641 (concat
4642 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4643 "\\([012][0-9]:[0-5][0-9]\\)>"
4644 "\\(--?"
4645 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4646 "Regular expression to match a timestamp time or time range.
4647 After a match, the following groups carry important information:
4648 0 the full match
4649 1 date plus weekday, for backreferencing to make sure both times on same day
4650 2 the first time, range or not
4651 4 the second time, if it is a range.")
4652
4653 (defvar org-prefix-has-time nil
4654 "A flag, set by `org-compile-prefix-format'.
4655 The flag is set if the currently compiled format contains a `%t'.")
4656
4657 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4658 "Format TXT to be inserted into the agenda buffer.
4659 In particular, it adds the prefix and corresponding text properties. EXTRA
4660 must be a string and replaces the `%s' specifier in the prefix format.
4661 CATEGORY (string, symbol or nil) may be used to overule the default
4662 category taken from local variable or file name. It will replace the `%c'
4663 specifier in the format. DOTIME, when non-nil, indicates that a
4664 time-of-day should be extracted from TXT for sorting of this entry, and for
4665 the `%t' specifier in the format. When DOTIME is a string, this string is
4666 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4667 only the correctly processes TXT should be returned - this is used by
4668 `org-agenda-change-all-lines'."
4669 (save-match-data
4670 ;; Diary entries sometimes have extra whitespace at the beginning
4671 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4672 (let* ((category (or category
4673 org-category
4674 (if (buffer-file-name)
4675 (file-name-sans-extension
4676 (file-name-nondirectory (buffer-file-name)))
4677 "")))
4678 time ;; needed for the eval of the prefix format
4679 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4680 (time-of-day (and dotime (org-get-time-of-day ts)))
4681 stamp plain s0 s1 s2 rtn)
4682 (when (and dotime time-of-day org-prefix-has-time)
4683 ;; Extract starting and ending time and move them to prefix
4684 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4685 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4686 (setq s0 (match-string 0 ts)
4687 s1 (match-string (if plain 1 2) ts)
4688 s2 (match-string (if plain 8 4) ts))
4689
4690 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4691 ;; them, we might want to remove them there to avoid duplication.
4692 ;; The user can turn this off with a variable.
4693 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4694 (string-match (concat (regexp-quote s0) " *") txt)
4695 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4696 (= (match-beginning 0) 0)
4697 t))
4698 (setq txt (replace-match "" nil nil txt))))
4699 ;; Normalize the time(s) to 24 hour
4700 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4701 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4702
4703 ;; Create the final string
4704 (if noprefix
4705 (setq rtn txt)
4706 ;; Prepare the variables needed in the eval of the compiled format
4707 (setq time (cond (s2 (concat s1 "-" s2))
4708 (s1 (concat s1 "......"))
4709 (t ""))
4710 extra (or extra "")
4711 category (if (symbolp category) (symbol-name category) category))
4712 ;; Evaluate the compiled format
4713 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4714
4715 ;; And finally add the text properties
4716 (add-text-properties
4717 0 (length rtn) (list 'category (downcase category)
4718 'prefix-length (- (length rtn) (length txt))
4719 'time-of-day time-of-day
4720 'dotime dotime)
4721 rtn)
4722 rtn)))
4723
4724 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4725 (catch 'exit
4726 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4727 ((and todayp (member 'today (car org-agenda-time-grid))))
4728 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4729 ((member 'weekly (car org-agenda-time-grid)))
4730 (t (throw 'exit list)))
4731 (let* ((have (delq nil (mapcar
4732 (lambda (x) (get-text-property 1 'time-of-day x))
4733 list)))
4734 (string (nth 1 org-agenda-time-grid))
4735 (gridtimes (nth 2 org-agenda-time-grid))
4736 (req (car org-agenda-time-grid))
4737 (remove (member 'remove-match req))
4738 new time)
4739 (if (and (member 'require-timed req) (not have))
4740 ;; don't show empty grid
4741 (throw 'exit list))
4742 (while (setq time (pop gridtimes))
4743 (unless (and remove (member time have))
4744 (setq time (int-to-string time))
4745 (push (org-format-agenda-item
4746 nil string "" ;; FIXME: put a category?
4747 (concat (substring time 0 -2) ":" (substring time -2)))
4748 new)
4749 (put-text-property
4750 1 (length (car new)) 'face 'org-time-grid (car new))))
4751 (if (member 'time-up org-agenda-sorting-strategy)
4752 (append new list)
4753 (append list new)))))
4754
4755 (defun org-compile-prefix-format (format)
4756 "Compile the prefix format into a Lisp form that can be evaluated.
4757 The resulting form is returned and stored in the variable
4758 `org-prefix-format-compiled'."
4759 (setq org-prefix-has-time nil)
4760 (let ((start 0) varform vars var (s format) c f opt)
4761 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4762 s start)
4763 (setq var (cdr (assoc (match-string 4 s)
4764 '(("c" . category) ("t" . time) ("s" . extra))))
4765 c (or (match-string 3 s) "")
4766 opt (match-beginning 1)
4767 start (1+ (match-beginning 0)))
4768 (if (equal var 'time) (setq org-prefix-has-time t))
4769 (setq f (concat "%" (match-string 2 s) "s"))
4770 (if opt
4771 (setq varform
4772 `(if (equal "" ,var)
4773 ""
4774 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4775 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4776 (setq s (replace-match "%s" t nil s))
4777 (push varform vars))
4778 (setq vars (nreverse vars))
4779 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4780
4781 (defun org-get-time-of-day (s &optional string)
4782 "Check string S for a time of day.
4783 If found, return it as a military time number between 0 and 2400.
4784 If not found, return nil.
4785 The optional STRING argument forces conversion into a 5 character wide string
4786 HH:MM."
4787 (save-match-data
4788 (when
4789 (or
4790 (string-match
4791 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4792 (string-match
4793 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4794 (let* ((t0 (+ (* 100
4795 (+ (string-to-number (match-string 1 s))
4796 (if (and (match-beginning 4)
4797 (equal (downcase (match-string 4 s)) "pm"))
4798 12 0)))
4799 (if (match-beginning 3)
4800 (string-to-number (match-string 3 s))
4801 0)))
4802 (t1 (concat " " (int-to-string t0))))
4803 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4804
4805 (defun org-finalize-agenda-entries (list)
4806 "Sort and concatenate the agenda items."
4807 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4808
4809 (defsubst org-cmp-priority (a b)
4810 "Compare the priorities of string a and b."
4811 (let ((pa (or (get-text-property 1 'priority a) 0))
4812 (pb (or (get-text-property 1 'priority b) 0)))
4813 (cond ((> pa pb) +1)
4814 ((< pa pb) -1)
4815 (t nil))))
4816
4817 (defsubst org-cmp-category (a b)
4818 "Compare the string values of categories of strings a and b."
4819 (let ((ca (or (get-text-property 1 'category a) ""))
4820 (cb (or (get-text-property 1 'category b) "")))
4821 (cond ((string-lessp ca cb) -1)
4822 ((string-lessp cb ca) +1)
4823 (t nil))))
4824
4825 (defsubst org-cmp-time (a b)
4826 "Compare the time-of-day values of strings a and b."
4827 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4828 (ta (or (get-text-property 1 'time-of-day a) def))
4829 (tb (or (get-text-property 1 'time-of-day b) def)))
4830 (cond ((< ta tb) -1)
4831 ((< tb ta) +1)
4832 (t nil))))
4833
4834 (defun org-entries-lessp (a b)
4835 "Predicate for sorting agenda entries."
4836 ;; The following variables will be used when the form is evaluated.
4837 (let* ((time-up (org-cmp-time a b))
4838 (time-down (if time-up (- time-up) nil))
4839 (priority-up (org-cmp-priority a b))
4840 (priority-down (if priority-up (- priority-up) nil))
4841 (category-up (org-cmp-category a b))
4842 (category-down (if category-up (- category-up) nil))
4843 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4844 (cdr (assoc
4845 (eval (cons 'or org-agenda-sorting-strategy))
4846 '((-1 . t) (1 . nil) (nil . nil))))))
4847
4848 (defun org-agenda-show-priority ()
4849 "Show the priority of the current item.
4850 This priority is composed of the main priority given with the [#A] cookies,
4851 and by additional input from the age of a schedules or deadline entry."
4852 (interactive)
4853 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4854 (message "Priority is %d" (if pri pri -1000))))
4855
4856 (defun org-agenda-goto (&optional highlight)
4857 "Go to the Org-mode file which contains the item at point."
4858 (interactive)
4859 (let* ((marker (or (get-text-property (point) 'org-marker)
4860 (org-agenda-error)))
4861 (buffer (marker-buffer marker))
4862 (pos (marker-position marker)))
4863 (switch-to-buffer-other-window buffer)
4864 (widen)
4865 (goto-char pos)
4866 (when (eq major-mode 'org-mode)
4867 (org-show-hidden-entry)
4868 (save-excursion
4869 (and (outline-next-heading)
4870 (org-flag-heading nil)))) ; show the next heading
4871 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4872
4873 (defun org-agenda-switch-to ()
4874 "Go to the Org-mode file which contains the item at point."
4875 (interactive)
4876 (let* ((marker (or (get-text-property (point) 'org-marker)
4877 (org-agenda-error)))
4878 (buffer (marker-buffer marker))
4879 (pos (marker-position marker)))
4880 (switch-to-buffer buffer)
4881 (delete-other-windows)
4882 (widen)
4883 (goto-char pos)
4884 (when (eq major-mode 'org-mode)
4885 (org-show-hidden-entry)
4886 (save-excursion
4887 (and (outline-next-heading)
4888 (org-flag-heading nil)))))) ; show the next heading
4889
4890 (defun org-agenda-goto-mouse (ev)
4891 "Go to the Org-mode file which contains the item at the mouse click."
4892 (interactive "e")
4893 (mouse-set-point ev)
4894 (org-agenda-goto))
4895
4896 (defun org-agenda-show ()
4897 "Display the Org-mode file which contains the item at point."
4898 (interactive)
4899 (let ((win (selected-window)))
4900 (org-agenda-goto t)
4901 (select-window win)))
4902
4903 (defun org-agenda-recenter (arg)
4904 "Display the Org-mode file which contains the item at point and recenter."
4905 (interactive "P")
4906 (let ((win (selected-window)))
4907 (org-agenda-goto t)
4908 (recenter arg)
4909 (select-window win)))
4910
4911 (defun org-agenda-show-mouse (ev)
4912 "Display the Org-mode file which contains the item at the mouse click."
4913 (interactive "e")
4914 (mouse-set-point ev)
4915 (org-agenda-show))
4916
4917 (defun org-agenda-check-no-diary ()
4918 "Check if the entry is a diary link and abort if yes."
4919 (if (get-text-property (point) 'org-agenda-diary-link)
4920 (org-agenda-error)))
4921
4922 (defun org-agenda-error ()
4923 (error "Command not allowed in this line"))
4924
4925 (defvar org-last-heading-marker (make-marker)
4926 "Marker pointing to the headline that last changed its TODO state
4927 by a remote command from the agenda.")
4928
4929 (defun org-agenda-todo ()
4930 "Cycle TODO state of line at point, also in Org-mode file.
4931 This changes the line at point, all other lines in the agenda referring to
4932 the same tree node, and the headline of the tree node in the Org-mode file."
4933 (interactive)
4934 (org-agenda-check-no-diary)
4935 (let* ((col (current-column))
4936 (marker (or (get-text-property (point) 'org-marker)
4937 (org-agenda-error)))
4938 (buffer (marker-buffer marker))
4939 (pos (marker-position marker))
4940 (hdmarker (get-text-property (point) 'org-hd-marker))
4941 (buffer-read-only nil)
4942 newhead)
4943 (with-current-buffer buffer
4944 (widen)
4945 (goto-char pos)
4946 (org-show-hidden-entry)
4947 (save-excursion
4948 (and (outline-next-heading)
4949 (org-flag-heading nil))) ; show the next heading
4950 (org-todo)
4951 (forward-char 1)
4952 (setq newhead (org-get-heading))
4953 (save-excursion
4954 (org-back-to-heading)
4955 (move-marker org-last-heading-marker (point))))
4956 (beginning-of-line 1)
4957 (save-excursion
4958 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4959 (move-to-column col)))
4960
4961 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4962 "Change all lines in the agenda buffer which match hdmarker.
4963 The new content of the line will be NEWHEAD (as modified by
4964 `org-format-agenda-item'). HDMARKER is checked with
4965 `equal' against all `org-hd-marker' text properties in the file.
4966 If FIXFACE is non-nil, the face of each item is modified acording to
4967 the new TODO state."
4968 (let* (props m pl undone-face done-face finish new dotime)
4969 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4970 (save-excursion
4971 (goto-char (point-max))
4972 (beginning-of-line 1)
4973 (while (not finish)
4974 (setq finish (bobp))
4975 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4976 (equal m hdmarker))
4977 (setq props (text-properties-at (point))
4978 dotime (get-text-property (point) 'dotime)
4979 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4980 pl (get-text-property (point) 'prefix-length)
4981 undone-face (get-text-property (point) 'undone-face)
4982 done-face (get-text-property (point) 'done-face))
4983 (move-to-column pl)
4984 (if (looking-at ".*")
4985 (progn
4986 (replace-match new t t)
4987 (beginning-of-line 1)
4988 (add-text-properties (point-at-bol) (point-at-eol) props)
4989 (if fixface
4990 (add-text-properties
4991 (point-at-bol) (point-at-eol)
4992 (list 'face
4993 (if org-last-todo-state-is-todo
4994 undone-face done-face))))
4995 (beginning-of-line 1))
4996 (error "Line update did not work")))
4997 (beginning-of-line 0)))))
4998
4999 (defun org-agenda-priority-up ()
5000 "Increase the priority of line at point, also in Org-mode file."
5001 (interactive)
5002 (org-agenda-priority 'up))
5003
5004 (defun org-agenda-priority-down ()
5005 "Decrease the priority of line at point, also in Org-mode file."
5006 (interactive)
5007 (org-agenda-priority 'down))
5008
5009 (defun org-agenda-priority (&optional force-direction)
5010 "Set the priority of line at point, also in Org-mode file.
5011 This changes the line at point, all other lines in the agenda referring to
5012 the same tree node, and the headline of the tree node in the Org-mode file."
5013 (interactive)
5014 (org-agenda-check-no-diary)
5015 (let* ((marker (or (get-text-property (point) 'org-marker)
5016 (org-agenda-error)))
5017 (buffer (marker-buffer marker))
5018 (pos (marker-position marker))
5019 (hdmarker (get-text-property (point) 'org-hd-marker))
5020 (buffer-read-only nil)
5021 newhead)
5022 (with-current-buffer buffer
5023 (widen)
5024 (goto-char pos)
5025 (org-show-hidden-entry)
5026 (save-excursion
5027 (and (outline-next-heading)
5028 (org-flag-heading nil))) ; show the next heading
5029 (funcall 'org-priority force-direction)
5030 (end-of-line 1)
5031 (setq newhead (org-get-heading)))
5032 (org-agenda-change-all-lines newhead hdmarker)
5033 (beginning-of-line 1)))
5034
5035 (defun org-agenda-date-later (arg &optional what)
5036 "Change the date of this item to one day later."
5037 (interactive "p")
5038 (org-agenda-check-no-diary)
5039 (let* ((marker (or (get-text-property (point) 'org-marker)
5040 (org-agenda-error)))
5041 (buffer (marker-buffer marker))
5042 (pos (marker-position marker)))
5043 (with-current-buffer buffer
5044 (widen)
5045 (goto-char pos)
5046 (if (not (org-at-timestamp-p))
5047 (error "Cannot find time stamp"))
5048 (org-timestamp-change arg (or what 'day))
5049 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5050
5051 (defun org-agenda-date-earlier (arg &optional what)
5052 "Change the date of this item to one day earlier."
5053 (interactive "p")
5054 (org-agenda-date-later (- arg) what))
5055
5056 (defun org-agenda-date-prompt (arg)
5057 "Change the date of this item. Date is prompted for, with default today.
5058 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5059 be used to request time specification in the time stamp."
5060 (interactive "P")
5061 (org-agenda-check-no-diary)
5062 (let* ((marker (or (get-text-property (point) 'org-marker)
5063 (org-agenda-error)))
5064 (buffer (marker-buffer marker))
5065 (pos (marker-position marker)))
5066 (with-current-buffer buffer
5067 (widen)
5068 (goto-char pos)
5069 (if (not (org-at-timestamp-p))
5070 (error "Cannot find time stamp"))
5071 (org-time-stamp arg)
5072 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5073
5074 (defun org-get-heading ()
5075 "Return the heading of the current entry, without the stars."
5076 (save-excursion
5077 (if (and (re-search-backward "[\r\n]\\*" nil t)
5078 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5079 (match-string 1)
5080 "")))
5081
5082 (defun org-agenda-diary-entry ()
5083 "Make a diary entry, like the `i' command from the calendar.
5084 All the standard commands work: block, weekly etc"
5085 (interactive)
5086 (require 'diary-lib)
5087 (let* ((char (progn
5088 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5089 (read-char-exclusive)))
5090 (cmd (cdr (assoc char
5091 '((?d . insert-diary-entry)
5092 (?w . insert-weekly-diary-entry)
5093 (?m . insert-monthly-diary-entry)
5094 (?y . insert-yearly-diary-entry)
5095 (?a . insert-anniversary-diary-entry)
5096 (?b . insert-block-diary-entry)
5097 (?c . insert-cyclic-diary-entry)))))
5098 (oldf (symbol-function 'calendar-cursor-to-date))
5099 (point (point))
5100 (mark (or (mark t) (point))))
5101 (unless cmd
5102 (error "No command associated with <%c>" char))
5103 (unless (and (get-text-property point 'day)
5104 (or (not (equal ?b char))
5105 (get-text-property mark 'day)))
5106 (error "Don't know which date to use for diary entry"))
5107 ;; We implement this by hacking the `calendar-cursor-to-date' function
5108 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5109 (let ((calendar-mark-ring
5110 (list (calendar-gregorian-from-absolute
5111 (or (get-text-property mark 'day)
5112 (get-text-property point 'day))))))
5113 (unwind-protect
5114 (progn
5115 (fset 'calendar-cursor-to-date
5116 (lambda (&optional error)
5117 (calendar-gregorian-from-absolute
5118 (get-text-property point 'day))))
5119 (call-interactively cmd))
5120 (fset 'calendar-cursor-to-date oldf)))))
5121
5122
5123 (defun org-agenda-execute-calendar-command (cmd)
5124 "Execute a calendar command from the agenda, with the date associated to
5125 the cursor position."
5126 (require 'diary-lib)
5127 (unless (get-text-property (point) 'day)
5128 (error "Don't know which date to use for calendar command"))
5129 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5130 (point (point))
5131 (date (calendar-gregorian-from-absolute
5132 (get-text-property point 'day)))
5133 (displayed-day (extract-calendar-day date))
5134 (displayed-month (extract-calendar-month date))
5135 (displayed-year (extract-calendar-year date)))
5136 (unwind-protect
5137 (progn
5138 (fset 'calendar-cursor-to-date
5139 (lambda (&optional error)
5140 (calendar-gregorian-from-absolute
5141 (get-text-property point 'day))))
5142 (call-interactively cmd))
5143 (fset 'calendar-cursor-to-date oldf))))
5144
5145 (defun org-agenda-phases-of-moon ()
5146 "Display the phases of the moon for the 3 months around the cursor date."
5147 (interactive)
5148 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5149
5150 (defun org-agenda-holidays ()
5151 "Display the holidays for the 3 months around the cursor date."
5152 (interactive)
5153 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5154
5155 (defun org-agenda-sunrise-sunset (arg)
5156 "Display sunrise and sunset for the cursor date.
5157 Latitude and longitude can be specified with the variables
5158 `calendar-latitude' and `calendar-longitude'. When called with prefix
5159 argument, latitude and longitude will be prompted for."
5160 (interactive "P")
5161 (let ((calendar-longitude (if arg nil calendar-longitude))
5162 (calendar-latitude (if arg nil calendar-latitude))
5163 (calendar-location-name
5164 (if arg "the given coordinates" calendar-location-name)))
5165 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5166
5167 (defun org-agenda-goto-calendar ()
5168 "Open the Emacs calendar with the date at the cursor."
5169 (interactive)
5170 (let* ((day (or (get-text-property (point) 'day)
5171 (error "Don't know which date to open in calendar")))
5172 (date (calendar-gregorian-from-absolute day)))
5173 (calendar)
5174 (calendar-goto-date date)))
5175
5176 (defun org-calendar-goto-agenda ()
5177 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5178 This is a command that has to be installed in `calendar-mode-map'."
5179 (interactive)
5180 (org-agenda nil (calendar-absolute-from-gregorian
5181 (calendar-cursor-to-date))))
5182
5183 (defun org-agenda-convert-date ()
5184 (interactive)
5185 (let ((day (get-text-property (point) 'day))
5186 date s)
5187 (unless day
5188 (error "Don't know which date to convert"))
5189 (setq date (calendar-gregorian-from-absolute day))
5190 (setq s (concat
5191 "Gregorian: " (calendar-date-string date) "\n"
5192 "ISO: " (calendar-iso-date-string date) "\n"
5193 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5194 "Julian: " (calendar-julian-date-string date) "\n"
5195 "Astron. JD: " (calendar-astro-date-string date)
5196 " (Julian date number at noon UTC)\n"
5197 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5198 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5199 "French: " (calendar-french-date-string date) "\n"
5200 "Mayan: " (calendar-mayan-date-string date) "\n"
5201 "Coptic: " (calendar-coptic-date-string date) "\n"
5202 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5203 "Persian: " (calendar-persian-date-string date) "\n"
5204 "Chinese: " (calendar-chinese-date-string date) "\n"))
5205 (with-output-to-temp-buffer "*Dates*"
5206 (princ s))
5207 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5208
5209 ;;; Link Stuff
5210
5211 (defun org-find-file-at-mouse (ev)
5212 "Open file link or URL at mouse."
5213 (interactive "e")
5214 (mouse-set-point ev)
5215 (org-open-at-point 'in-emacs))
5216
5217 (defun org-open-at-mouse (ev)
5218 "Open file link or URL at mouse."
5219 (interactive "e")
5220 (mouse-set-point ev)
5221 (org-open-at-point))
5222
5223 (defun org-open-at-point (&optional in-emacs)
5224 "Open link at or after point.
5225 If there is no link at point, this function will search forward up to
5226 the end of the current subtree.
5227 Normally, files will be opened by an appropriate application. If the
5228 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5229 (interactive "P")
5230 (if (org-at-timestamp-p)
5231 (org-agenda nil (time-to-days (org-time-string-to-time
5232 (substring (match-string 1) 0 10)))
5233 1)
5234 (let (type path line (pos (point)))
5235 (save-excursion
5236 (skip-chars-backward
5237 (concat (if org-allow-space-in-links "^" "^ ")
5238 org-non-link-chars))
5239 (if (re-search-forward
5240 org-link-regexp
5241 (save-excursion
5242 (condition-case nil
5243 (progn (outline-end-of-subtree) (max pos (point)))
5244 (error (end-of-line 1) (point))))
5245 t)
5246 (setq type (match-string 1)
5247 path (match-string 2)))
5248 (unless path
5249 (error "No link found"))
5250 ;; Remove any trailing spaces in path
5251 (if (string-match " +\\'" path)
5252 (setq path (replace-match "" t t path)))
5253
5254 (cond
5255
5256 ((string= type "file")
5257 (if (string-match ":\\([0-9]+\\)\\'" path)
5258 (setq line (string-to-number (match-string 1 path))
5259 path (substring path 0 (match-beginning 0))))
5260 (org-open-file path in-emacs line))
5261
5262 ((string= type "news")
5263 (org-follow-gnus-link path))
5264
5265 ((string= type "bbdb")
5266 (org-follow-bbdb-link path))
5267
5268 ((string= type "gnus")
5269 (let (group article)
5270 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5271 (error "Error in Gnus link"))
5272 (setq group (match-string 1 path)
5273 article (match-string 3 path))
5274 (org-follow-gnus-link group article)))
5275
5276 ((string= type "vm")
5277 (let (folder article)
5278 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5279 (error "Error in VM link"))
5280 (setq folder (match-string 1 path)
5281 article (match-string 3 path))
5282 ;; in-emacs is the prefix arg, will be interpreted as read-only
5283 (org-follow-vm-link folder article in-emacs)))
5284
5285 ((string= type "wl")
5286 (let (folder article)
5287 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5288 (error "Error in Wanderlust link"))
5289 (setq folder (match-string 1 path)
5290 article (match-string 3 path))
5291 (org-follow-wl-link folder article)))
5292
5293 ((string= type "rmail")
5294 (let (folder article)
5295 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5296 (error "Error in RMAIL link"))
5297 (setq folder (match-string 1 path)
5298 article (match-string 3 path))
5299 (org-follow-rmail-link folder article)))
5300
5301 ((string= type "shell")
5302 (let ((cmd path))
5303 (while (string-match "@{" cmd)
5304 (setq cmd (replace-match "<" t t cmd)))
5305 (while (string-match "@}" cmd)
5306 (setq cmd (replace-match ">" t t cmd)))
5307 (if (or (not org-confirm-shell-links)
5308 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5309 (shell-command cmd)
5310 (error "Abort"))))
5311
5312 (t
5313 (browse-url-at-point)))))))
5314
5315 (defun org-follow-bbdb-link (name)
5316 "Follow a BBDB link to NAME."
5317 (require 'bbdb)
5318 (let ((inhibit-redisplay t))
5319 (catch 'exit
5320 ;; Exact match on name
5321 (bbdb-name (concat "\\`" name "\\'") nil)
5322 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5323 ;; Exact match on name
5324 (bbdb-company (concat "\\`" name "\\'") nil)
5325 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5326 ;; Partial match on name
5327 (bbdb-name name nil)
5328 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5329 ;; Partial match on company
5330 (bbdb-company name nil)
5331 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5332 ;; General match including network address and notes
5333 (bbdb name nil)
5334 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5335 (delete-window (get-buffer-window "*BBDB*"))
5336 (error "No matching BBDB record")))))
5337
5338 (defun org-follow-gnus-link (&optional group article)
5339 "Follow a Gnus link to GROUP and ARTICLE."
5340 (require 'gnus)
5341 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5342 (if group (gnus-fetch-group group))
5343 (if article
5344 (or (gnus-summary-goto-article article nil 'force)
5345 (if (fboundp 'gnus-summary-insert-cached-articles)
5346 (progn
5347 (gnus-summary-insert-cached-articles)
5348 (gnus-summary-goto-article article nil 'force))
5349 (message "Message could not be found.")))))
5350
5351 (defun org-follow-vm-link (&optional folder article readonly)
5352 "Follow a VM link to FOLDER and ARTICLE."
5353 (require 'vm)
5354 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5355 ;; ange-ftp or efs or tramp access
5356 (let ((user (or (match-string 1 folder) (user-login-name)))
5357 (host (match-string 2 folder))
5358 (file (match-string 3 folder)))
5359 (cond
5360 ((featurep 'tramp)
5361 ;; use tramp to access the file
5362 (if org-xemacs-p
5363 (setq folder (format "[%s@%s]%s" user host file))
5364 (setq folder (format "/%s@%s:%s" user host file))))
5365 (t
5366 ;; use ange-ftp or efs
5367 (require (if org-xemacs-p 'efs 'ange-ftp))
5368 (setq folder (format "/%s@%s:%s" user host file))))))
5369 (when folder
5370 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5371 (sit-for 0.1)
5372 (when article
5373 (vm-select-folder-buffer)
5374 (widen)
5375 (let ((case-fold-search t))
5376 (goto-char (point-min))
5377 (if (not (re-search-forward
5378 (concat "^" "message-id: *" (regexp-quote article))))
5379 (error "Could not find the specified message in this folder"))
5380 (vm-isearch-update)
5381 (vm-isearch-narrow)
5382 (vm-beginning-of-message)
5383 (vm-summarize)))))
5384
5385 (defun org-follow-wl-link (folder article)
5386 "Follow a Wanderlust link to FOLDER and ARTICLE."
5387 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5388 (if article (wl-summary-jump-to-msg-by-message-id article))
5389 (wl-summary-redisplay))
5390
5391 (defun org-follow-rmail-link (folder article)
5392 "Follow an RMAIL link to FOLDER and ARTICLE."
5393 (let (message-number)
5394 (save-excursion
5395 (save-window-excursion
5396 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5397 (setq message-number
5398 (save-restriction
5399 (widen)
5400 (goto-char (point-max))
5401 (if (re-search-backward
5402 (concat "^Message-ID:\\s-+" (regexp-quote
5403 (or article "")))
5404 nil t)
5405 (rmail-what-message))))))
5406 (if message-number
5407 (progn
5408 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5409 (rmail-show-message message-number)
5410 message-number)
5411 (error "Message not found"))))
5412
5413 (defun org-open-file (path &optional in-emacs line)
5414 "Open the file at PATH.
5415 First, this expands any special file name abbreviations. Then the
5416 configuration variable `org-file-apps' is checked if it contains an
5417 entry for this file type, and if yes, the corresponding command is launched.
5418 If no application is found, Emacs simply visits the file.
5419 With optional argument IN-EMACS, Emacs will visit the file.
5420 If the file does not exist, an error is thrown."
5421 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5422 (dfile (downcase file))
5423 ext cmd apps)
5424 (if (and (not (file-exists-p file))
5425 (not org-open-non-existing-files))
5426 (error "No such file: %s" file))
5427 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5428 (setq ext (match-string 1 dfile))
5429 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5430 (setq ext (match-string 1 dfile))))
5431 (setq apps (append org-file-apps (org-default-apps)))
5432 (if in-emacs
5433 (setq cmd 'emacs)
5434 (setq cmd (or (cdr (assoc ext apps))
5435 (cdr (assoc t apps)))))
5436 (cond
5437 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5438 (setq cmd (format cmd (concat "\"" file "\"")))
5439 (save-window-excursion
5440 (shell-command (concat cmd " & &"))))
5441 ((or (stringp cmd)
5442 (eq cmd 'emacs))
5443 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5444 (if line (goto-line line)))
5445 ((consp cmd)
5446 (eval cmd))
5447 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5448
5449 (defun org-default-apps ()
5450 "Return the default applications for this operating system."
5451 (cond
5452 ((eq system-type 'darwin)
5453 org-file-apps-defaults-macosx)
5454 ((eq system-type 'windows-nt)
5455 org-file-apps-defaults-windowsnt)
5456 (t org-file-apps-defaults-gnu)))
5457
5458 (defun org-expand-file-name (path)
5459 "Replace special path abbreviations and expand the file name."
5460 (expand-file-name path))
5461
5462
5463 (defvar org-insert-link-history nil
5464 "Minibuffer history for links inserted with `org-insert-link'.")
5465
5466 (defvar org-stored-links nil
5467 "Contains the links stored with `org-store-link'.")
5468
5469 ;;;###autoload
5470 (defun org-store-link (arg)
5471 "\\<org-mode-map>Store an org-link to the current location.
5472 This link can later be inserted into an org-buffer with
5473 \\[org-insert-link].
5474 For some link types, a prefix arg is interpreted:
5475 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5476 For file links, arg negates `org-line-numbers-in-file-links'."
5477 (interactive "P")
5478 (let (link cpltxt)
5479 (cond
5480
5481 ((eq major-mode 'bbdb-mode)
5482 (setq cpltxt (concat
5483 "bbdb:"
5484 (or (bbdb-record-name (bbdb-current-record))
5485 (bbdb-record-company (bbdb-current-record))))
5486 link (org-make-link cpltxt)))
5487
5488 ((eq major-mode 'calendar-mode)
5489 (let ((cd (calendar-cursor-to-date)))
5490 (setq link
5491 (format-time-string
5492 (car org-time-stamp-formats)
5493 (apply 'encode-time
5494 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5495 nil nil nil))))))
5496
5497 ((or (eq major-mode 'vm-summary-mode)
5498 (eq major-mode 'vm-presentation-mode))
5499 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5500 (vm-follow-summary-cursor)
5501 (save-excursion
5502 (vm-select-folder-buffer)
5503 (let* ((message (car vm-message-pointer))
5504 (folder (buffer-file-name))
5505 (subject (vm-su-subject message))
5506 (author (vm-su-full-name message))
5507 (message-id (vm-su-message-id message)))
5508 (setq folder (abbreviate-file-name folder))
5509 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5510 folder)
5511 (setq folder (replace-match "" t t folder)))
5512 (setq cpltxt (concat author " on: " subject))
5513 (setq link (concat cpltxt "\n "
5514 (org-make-link
5515 "vm:" folder "#" message-id))))))
5516
5517 ((eq major-mode 'wl-summary-mode)
5518 (let* ((msgnum (wl-summary-message-number))
5519 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5520 msgnum 'message-id))
5521 (wl-message-entity (elmo-msgdb-overview-get-entity
5522 msgnum (wl-summary-buffer-msgdb)))
5523 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5524 (subject "???")) ; FIXME: How to get subject of email?
5525 (setq cpltxt (concat author " on: " subject))
5526 (setq link (concat cpltxt "\n "
5527 (org-make-link
5528 "wl:" wl-summary-buffer-folder-name
5529 "#" message-id)))))
5530
5531 ((eq major-mode 'rmail-mode)
5532 (save-excursion
5533 (save-restriction
5534 (rmail-narrow-to-non-pruned-header)
5535 (let ((folder (buffer-file-name))
5536 (message-id (mail-fetch-field "message-id"))
5537 (author (mail-fetch-field "from"))
5538 (subject (mail-fetch-field "subject")))
5539 (setq cpltxt (concat author " on: " subject))
5540 (setq link (concat cpltxt "\n "
5541 (org-make-link
5542 "rmail:" folder "#" message-id)))))))
5543
5544 ((eq major-mode 'gnus-group-mode)
5545 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5546 (gnus-group-group-name)) ; version
5547 ((fboundp 'gnus-group-name)
5548 (gnus-group-name))
5549 (t "???"))))
5550 (setq cpltxt (concat
5551 (if (org-xor arg org-usenet-links-prefer-google)
5552 "http://groups.google.com/groups?group="
5553 "gnus:")
5554 group)
5555 link (org-make-link cpltxt))))
5556
5557 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5558 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5559 (gnus-summary-beginning-of-article)
5560 (let* ((group (car gnus-article-current))
5561 (article (cdr gnus-article-current))
5562 (header (gnus-summary-article-header article))
5563 (author (mail-header-from header))
5564 (message-id (mail-header-id header))
5565 (date (mail-header-date header))
5566 (subject (gnus-summary-subject-string)))
5567 (setq cpltxt (concat author " on: " subject))
5568 (if (org-xor arg org-usenet-links-prefer-google)
5569 (setq link
5570 (concat
5571 cpltxt "\n "
5572 (format "http://groups.google.com/groups?as_umsgid=%s"
5573 (org-fixup-message-id-for-http message-id))))
5574 (setq link (concat cpltxt "\n"
5575 (org-make-link
5576 "gnus:" group
5577 "#" (number-to-string article)))))))
5578
5579 ((eq major-mode 'w3-mode)
5580 (setq cpltxt (url-view-url t)
5581 link (org-make-link cpltxt)))
5582 ((eq major-mode 'w3m-mode)
5583 (setq cpltxt w3m-current-url
5584 link (org-make-link cpltxt)))
5585
5586 ((buffer-file-name)
5587 ;; Just link to this file here.
5588 (setq cpltxt (concat "file:"
5589 (abbreviate-file-name (buffer-file-name))))
5590 ;; Add the line number?
5591 (if (org-xor org-line-numbers-in-file-links arg)
5592 (setq cpltxt
5593 (concat cpltxt
5594 ":" (int-to-string
5595 (+ (if (bolp) 1 0) (count-lines
5596 (point-min) (point)))))))
5597 (setq link (org-make-link cpltxt)))
5598
5599 ((interactive-p)
5600 (error "Cannot link to a buffer which is not visiting a file"))
5601
5602 (t (setq link nil)))
5603
5604 (if (and (interactive-p) link)
5605 (progn
5606 (setq org-stored-links
5607 (cons (cons (or cpltxt link) link) org-stored-links))
5608 (message "Stored: %s" (or cpltxt link)))
5609 link)))
5610
5611 (defun org-make-link (&rest strings)
5612 "Concatenate STRINGS, format resulting string with `org-link-format'."
5613 (format org-link-format (apply 'concat strings)))
5614
5615 (defun org-xor (a b)
5616 "Exclusive or."
5617 (if a (not b) b))
5618
5619 (defun org-get-header (header)
5620 "Find a header field in the current buffer."
5621 (save-excursion
5622 (goto-char (point-min))
5623 (let ((case-fold-search t) s)
5624 (cond
5625 ((eq header 'from)
5626 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5627 (setq s (match-string 1)))
5628 (while (string-match "\"" s)
5629 (setq s (replace-match "" t t s)))
5630 (if (string-match "[<(].*" s)
5631 (setq s (replace-match "" t t s))))
5632 ((eq header 'message-id)
5633 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5634 (setq s (match-string 1))))
5635 ((eq header 'subject)
5636 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5637 (setq s (match-string 1)))))
5638 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5639 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5640 s)))
5641
5642
5643 (defun org-fixup-message-id-for-http (s)
5644 "Replace special characters in a message id, so it can be used in an http query."
5645 (while (string-match "<" s)
5646 (setq s (replace-match "%3C" t t s)))
5647 (while (string-match ">" s)
5648 (setq s (replace-match "%3E" t t s)))
5649 (while (string-match "@" s)
5650 (setq s (replace-match "%40" t t s)))
5651 s)
5652
5653 (defun org-insert-link (&optional complete-file)
5654 "Insert a link. At the prompt, enter the link.
5655
5656 Completion can be used to select a link previously stored with
5657 `org-store-link'. When the empty string is entered (i.e. if you just
5658 press RET at the prompt), the link defaults to the most recently
5659 stored link. As SPC triggers completion in the minibuffer, you need to
5660 use M-SPC or C-q SPC to force the insertion of a space character.
5661
5662 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5663 selected using completion. The path to the file will be relative to
5664 the current directory if the file is in the current directory or a
5665 subdirectory. Otherwise, the link will be the absolute path as
5666 completed in the minibuffer (i.e. normally ~/path/to/file).
5667
5668 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5669 is in the current directory or below."
5670 (interactive "P")
5671 (let ((link (if complete-file
5672 (read-file-name "File: ")
5673 (completing-read
5674 "Link: " org-stored-links nil nil nil
5675 org-insert-link-history
5676 (or (car (car org-stored-links))))))
5677 linktxt matched)
5678 (if (or (not link) (equal link ""))
5679 (error "No links available"))
5680 (if complete-file
5681 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5682 (cond
5683 ((equal complete-file '(16))
5684 (insert
5685 (org-make-link
5686 "file:" (abbreviate-file-name (expand-file-name link)))))
5687 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5688 (expand-file-name link))
5689 (insert
5690 (org-make-link
5691 "file:" (match-string 1 (expand-file-name link)))))
5692 (t (insert (org-make-link "file:" link)))))
5693 (setq linktxt (cdr (assoc link org-stored-links)))
5694 (if (not org-keep-stored-link-after-insertion)
5695 (setq org-stored-links (delq (assoc link org-stored-links)
5696 org-stored-links)))
5697 (if (not linktxt) (setq link (org-make-link link)))
5698 (let ((lines (org-split-string (or linktxt link) "\n")))
5699 (insert (car lines))
5700 (setq matched (string-match org-link-regexp (car lines)))
5701 (setq lines (cdr lines))
5702 (while lines
5703 (insert "\n")
5704 (if (save-excursion
5705 (beginning-of-line 0)
5706 (looking-at "[ \t]+\\S-"))
5707 (indent-relative))
5708 (setq matched (or matched
5709 (string-match org-link-regexp (car lines))))
5710 (insert (car lines))
5711 (setq lines (cdr lines))))
5712 (unless matched
5713 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5714
5715 ;;; Hooks for remember.el
5716 ;;;###autoload
5717 (defun org-remember-annotation ()
5718 "Return a link to the current location as an annotation for remember.el.
5719 If you are using Org-mode files as target for data storage with
5720 remember.el, then the annotations should include a link compatible with the
5721 conventions in Org-mode. This function returns such a link."
5722 (org-store-link nil))
5723
5724 (defconst org-remember-help
5725 "Select a destination location for the note.
5726 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5727 RET at beg-of-buf -> Append to file as level 2 headline
5728 RET on headline -> Store as sublevel entry to current headline
5729 <left>/<right> -> before/after current headline, same headings level")
5730
5731 ;;;###autoload
5732 (defun org-remember-handler ()
5733 "Store stuff from remember.el into an org file.
5734 First prompts for an org file. If the user just presses return, the value
5735 of `org-default-notes-file' is used.
5736 Then the command offers the headings tree of the selected file in order to
5737 file the text at a specific location.
5738 You can either immediately press RET to get the note appended to the
5739 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5740 find a better place. Then press RET or <left> or <right> in insert the note.
5741
5742 Key Cursor position Note gets inserted
5743 -----------------------------------------------------------------------------
5744 RET buffer-start as level 2 heading at end of file
5745 RET on headline as sublevel of the heading at cursor
5746 RET no heading at cursor position, level taken from context.
5747 Or use prefix arg to specify level manually.
5748 <left> on headline as same level, before current heading
5749 <right> on headline as same level, after current heading
5750
5751 So the fastest way to store the note is to press RET RET to append it to
5752 the default file. This way your current train of thought is not
5753 interrupted, in accordance with the principles of remember.el. But with
5754 little extra effort, you can push it directly to the correct location.
5755
5756 Before being stored away, the function ensures that the text has a
5757 headline, i.e. a first line that starts with a \"*\". If not, a headline
5758 is constructed from the current date and some additional data.
5759
5760 If the variable `org-adapt-indentation' is non-nil, the entire text is
5761 also indented so that it starts in the same column as the headline
5762 \(i.e. after the stars).
5763
5764 See also the variable `org-reverse-note-order'."
5765 (catch 'quit
5766 (let* ((txt (buffer-substring (point-min) (point-max)))
5767 (fastp current-prefix-arg)
5768 (file (if fastp org-default-notes-file (org-get-org-file)))
5769 (visiting (find-buffer-visiting file))
5770 (org-startup-with-deadline-check nil)
5771 (org-startup-folded nil)
5772 spos level indent reversed)
5773 ;; Modify text so that it becomes a nice subtree which can be inserted
5774 ;; into an org tree.
5775 (let* ((lines (split-string txt "\n"))
5776 (first (car lines))
5777 (lines (cdr lines)))
5778 (if (string-match "^\\*+" first)
5779 ;; Is already a headline
5780 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5781 -1) ?\ ))
5782 ;; We need to add a headline: Use time and first buffer line
5783 (setq lines (cons first lines)
5784 first (concat "* " (current-time-string)
5785 " (" (remember-buffer-desc) ")")
5786 indent " "))
5787 (if org-adapt-indentation
5788 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5789 (setq txt (concat first "\n"
5790 (mapconcat 'identity lines "\n"))))
5791 ;; Find the file
5792 (if (not visiting)
5793 (find-file-noselect file))
5794 (with-current-buffer (get-file-buffer file)
5795 (setq reversed (org-notes-order-reversed-p))
5796 (save-excursion
5797 (save-restriction
5798 (widen)
5799 ;; Ask the User for a location
5800 (setq spos (if fastp 1 (org-get-location
5801 (current-buffer)
5802 org-remember-help)))
5803 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5804 ; not handle this note
5805 (goto-char spos)
5806 (cond ((bobp)
5807 ;; Put it at the start or end, as level 2
5808 (save-restriction
5809 (widen)
5810 (goto-char (if reversed (point-min) (point-max)))
5811 (if (not (bolp)) (newline))
5812 (org-paste-subtree (or current-prefix-arg 2) txt)))
5813 ((and (org-on-heading-p nil) (not current-prefix-arg))
5814 ;; Put it below this entry, at the beg/end of the subtree
5815 (org-back-to-heading)
5816 (setq level (outline-level))
5817 (if reversed
5818 (outline-end-of-heading)
5819 (outline-end-of-subtree))
5820 (if (not (bolp)) (newline))
5821 (beginning-of-line 1)
5822 (org-paste-subtree (1+ level) txt))
5823 (t
5824 ;; Put it right there, with automatic level determined by
5825 ;; org-paste-subtree or from prefix arg
5826 (org-paste-subtree current-prefix-arg txt)))
5827 (when remember-save-after-remembering
5828 (save-buffer)
5829 (if (not visiting) (kill-buffer (current-buffer)))))))))
5830 t) ;; return t to indicate that we took care of this note.
5831
5832 (defun org-get-org-file ()
5833 "Read a filename, with default directory `org-directory'."
5834 (let ((default (or org-default-notes-file remember-data-file)))
5835 (read-file-name (format "File name [%s]: " default)
5836 (file-name-as-directory org-directory)
5837 default)))
5838
5839 (defun org-notes-order-reversed-p ()
5840 "Check if the current file should receive notes in reversed order."
5841 (cond
5842 ((not org-reverse-note-order) nil)
5843 ((eq t org-reverse-note-order) t)
5844 ((not (listp org-reverse-note-order)) nil)
5845 (t (catch 'exit
5846 (let ((all org-reverse-note-order)
5847 entry)
5848 (while (setq entry (pop all))
5849 (if (string-match (car entry) (buffer-file-name))
5850 (throw 'exit (cdr entry))))
5851 nil)))))
5852
5853 ;;; Tables
5854
5855 ;; Watch out: Here we are talking about two different kind of tables.
5856 ;; Most of the code is for the tables created with the Org-mode table editor.
5857 ;; Sometimes, we talk about tables created and edited with the table.el
5858 ;; Emacs package. We call the former org-type tables, and the latter
5859 ;; table.el-type tables.
5860
5861
5862 (defun org-before-change-function (beg end)
5863 "Every change indicates that a table might need an update."
5864 (setq org-table-may-need-update t))
5865
5866 (defconst org-table-line-regexp "^[ \t]*|"
5867 "Detects an org-type table line.")
5868 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5869 "Detects an org-type table line.")
5870 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5871 "Detects a table line marked for automatic recalculation.")
5872 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5873 "Detects a table line marked for automatic recalculation.")
5874 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5875 "Detects a table line marked for automatic recalculation.")
5876 (defconst org-table-hline-regexp "^[ \t]*|-"
5877 "Detects an org-type table hline.")
5878 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5879 "Detects a table-type table hline.")
5880 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5881 "Detects an org-type or table-type table.")
5882 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5883 "Searching from within a table (any type) this finds the first line
5884 outside the table.")
5885 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5886 "Searching from within a table (any type) this finds the first line
5887 outside the table.")
5888
5889 (defun org-table-create-with-table.el ()
5890 "Use the table.el package to insert a new table.
5891 If there is already a table at point, convert between Org-mode tables
5892 and table.el tables."
5893 (interactive)
5894 (require 'table)
5895 (cond
5896 ((org-at-table.el-p)
5897 (if (y-or-n-p "Convert table to Org-mode table? ")
5898 (org-table-convert)))
5899 ((org-at-table-p)
5900 (if (y-or-n-p "Convert table to table.el table? ")
5901 (org-table-convert)))
5902 (t (call-interactively 'table-insert))))
5903
5904 (defun org-table-create (&optional size)
5905 "Query for a size and insert a table skeleton.
5906 SIZE is a string Columns x Rows like for example \"3x2\"."
5907 (interactive "P")
5908 (unless size
5909 (setq size (read-string
5910 (concat "Table size Columns x Rows [e.g. "
5911 org-table-default-size "]: ")
5912 "" nil org-table-default-size)))
5913
5914 (let* ((pos (point))
5915 (indent (make-string (current-column) ?\ ))
5916 (split (org-split-string size " *x *"))
5917 (rows (string-to-number (nth 1 split)))
5918 (columns (string-to-number (car split)))
5919 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5920 "\n")))
5921 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5922 (point-at-bol) (point)))
5923 (beginning-of-line 1)
5924 (newline))
5925 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5926 (dotimes (i rows) (insert line))
5927 (goto-char pos)
5928 (if (> rows 1)
5929 ;; Insert a hline after the first row.
5930 (progn
5931 (end-of-line 1)
5932 (insert "\n|-")
5933 (goto-char pos)))
5934 (org-table-align)))
5935
5936 (defun org-table-convert-region (beg0 end0 nspace)
5937 "Convert region to a table.
5938 The region goes from BEG0 to END0, but these borders will be moved
5939 slightly, to make sure a beginning of line in the first line is included.
5940 When NSPACE is non-nil, it indicates the minimum number of spaces that
5941 separate columns (default: just one space)"
5942 (let* ((beg (min beg0 end0))
5943 (end (max beg0 end0))
5944 (tabsep t)
5945 re)
5946 (goto-char beg)
5947 (beginning-of-line 1)
5948 (setq beg (move-marker (make-marker) (point)))
5949 (goto-char end)
5950 (if (bolp) (backward-char 1) (end-of-line 1))
5951 (setq end (move-marker (make-marker) (point)))
5952 ;; Lets see if this is tab-separated material. If every nonempty line
5953 ;; contains a tab, we will assume that it is tab-separated material
5954 (if nspace
5955 (setq tabsep nil)
5956 (goto-char beg)
5957 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5958 (if nspace (setq tabsep nil))
5959 (if tabsep
5960 (setq re "^\\|\t")
5961 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5962 (max 1 (prefix-numeric-value nspace)))))
5963 (goto-char beg)
5964 (while (re-search-forward re end t)
5965 (replace-match "|" t t))
5966 (goto-char beg)
5967 (insert " ")
5968 (org-table-align)))
5969
5970 (defun org-table-import (file arg)
5971 "Import FILE as a table.
5972 The file is assumed to be tab-separated. Such files can be produced by most
5973 spreadsheet and database applications. If no tabs (at least one per line)
5974 are found, lines will be split on whitespace into fields."
5975 (interactive "f\nP")
5976 (or (bolp) (newline))
5977 (let ((beg (point))
5978 (pm (point-max)))
5979 (insert-file-contents file)
5980 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5981
5982 (defun org-table-export ()
5983 "Export table as a tab-separated file.
5984 Such a file can be imported into a spreadsheet program like Excel."
5985 (interactive)
5986 (let* ((beg (org-table-begin))
5987 (end (org-table-end))
5988 (table (buffer-substring beg end))
5989 (file (read-file-name "Export table to: "))
5990 buf)
5991 (unless (or (not (file-exists-p file))
5992 (y-or-n-p (format "Overwrite file %s? " file)))
5993 (error "Abort"))
5994 (with-current-buffer (find-file-noselect file)
5995 (setq buf (current-buffer))
5996 (erase-buffer)
5997 (fundamental-mode)
5998 (insert table)
5999 (goto-char (point-min))
6000 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6001 (replace-match "" t t)
6002 (end-of-line 1))
6003 (goto-char (point-min))
6004 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6005 (replace-match "" t t)
6006 (goto-char (min (1+ (point)) (point-max))))
6007 (goto-char (point-min))
6008 (while (re-search-forward "^-[-+]*$" nil t)
6009 (replace-match "")
6010 (if (looking-at "\n")
6011 (delete-char 1)))
6012 (goto-char (point-min))
6013 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6014 (replace-match "\t" t t))
6015 (save-buffer))
6016 (kill-buffer buf)))
6017
6018 (defvar org-table-aligned-begin-marker (make-marker)
6019 "Marker at the beginning of the table last aligned.
6020 Used to check if cursor still is in that table, to minimize realignment.")
6021 (defvar org-table-aligned-end-marker (make-marker)
6022 "Marker at the end of the table last aligned.
6023 Used to check if cursor still is in that table, to minimize realignment.")
6024 (defvar org-table-last-alignment nil
6025 "List of flags for flushright alignment, from the last re-alignment.
6026 This is being used to correctly align a single field after TAB or RET.")
6027 ;; FIXME: The following is currently not used.
6028 (defvar org-table-last-column-widths nil
6029 "List of max width of fields in each column.
6030 This is being used to correctly align a single field after TAB or RET.")
6031
6032 (defvar org-last-recalc-line nil)
6033
6034 (defun org-table-align ()
6035 "Align the table at point by aligning all vertical bars."
6036 (interactive)
6037 ;; (message "align") (sit-for 2)
6038 (let* (
6039 ;; Limits of table
6040 (beg (org-table-begin))
6041 (end (org-table-end))
6042 ;; Current cursor position
6043 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6044 (colpos (org-table-current-column))
6045 (winstart (window-start))
6046 text lines (new "") lengths l typenums ty fields maxfields i
6047 column
6048 (indent "") cnt frac
6049 rfmt hfmt
6050 (spaces (if (org-in-invisibility-spec-p '(org-table))
6051 org-table-spaces-around-invisible-separators
6052 org-table-spaces-around-separators))
6053 (sp1 (car spaces))
6054 (sp2 (cdr spaces))
6055 (rfmt1 (concat
6056 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6057 (hfmt1 (concat
6058 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6059 emptystrings)
6060 (untabify beg end)
6061 ;; (message "Aligning table...")
6062 ;; Get the rows
6063 (setq lines (org-split-string
6064 (buffer-substring-no-properties beg end) "\n"))
6065 ;; Store the indentation of the first line
6066 (if (string-match "^ *" (car lines))
6067 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6068 ;; Mark the hlines
6069 (setq lines (mapcar (lambda (l)
6070 (if (string-match "^ *|-" l)
6071 nil
6072 (if (string-match "[ \t]+$" l)
6073 (substring l 0 (match-beginning 0))
6074 l)))
6075 lines))
6076 ;; Get the data fields
6077 (setq fields (mapcar
6078 (lambda (l)
6079 (org-split-string l " *| *"))
6080 (delq nil (copy-sequence lines))))
6081 ;; How many fields in the longest line?
6082 (condition-case nil
6083 (setq maxfields (apply 'max (mapcar 'length fields)))
6084 (error
6085 (kill-region beg end)
6086 (org-table-create org-table-default-size)
6087 (error "Empty table - created default table")))
6088 ;; A list of empty string to fill any short rows on output
6089 (setq emptystrings (make-list maxfields ""))
6090 ;; Get the maximum length of a field and the most common datatype
6091 ;; for each column
6092 (setq i -1)
6093 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6094 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6095 ;; maximum length
6096 (push (apply 'max 1 (mapcar 'length column)) lengths)
6097 ;; compute the fraction stepwise, ignoring empty fields
6098 (setq cnt 0 frac 0.0)
6099 (mapcar
6100 (lambda (x)
6101 (if (equal x "")
6102 nil
6103 (setq frac ( / (+ (* frac cnt)
6104 (if (string-match org-table-number-regexp x) 1 0))
6105 (setq cnt (1+ cnt))))))
6106 column)
6107 (push (>= frac org-table-number-fraction) typenums))
6108 (setq lengths (nreverse lengths)
6109 typenums (nreverse typenums))
6110 (setq org-table-last-alignment typenums
6111 org-table-last-column-widths lengths)
6112 ;; Compute the formats needed for output of the table
6113 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6114 (while (setq l (pop lengths))
6115 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6116 (setq rfmt (concat rfmt (format rfmt1 ty l))
6117 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6118 (setq rfmt (concat rfmt "\n")
6119 hfmt (concat (substring hfmt 0 -1) "|\n"))
6120 ;; Produce the new table
6121 ;;(while lines
6122 ;; (setq l (pop lines))
6123 ;; (if l
6124 ;; (setq new (concat new (apply 'format rfmt
6125 ;; (append (pop fields) emptystrings))))
6126 ;; (setq new (concat new hfmt))))
6127 (setq new (mapconcat
6128 (lambda (l)
6129 (if l (apply 'format rfmt
6130 (append (pop fields) emptystrings))
6131 hfmt))
6132 lines ""))
6133 ;; Replace the old one
6134 (delete-region beg end)
6135 (move-marker end nil)
6136 (move-marker org-table-aligned-begin-marker (point))
6137 (insert new)
6138 (move-marker org-table-aligned-end-marker (point))
6139 ;; Try to move to the old location (approximately)
6140 (goto-line linepos)
6141 (set-window-start (selected-window) winstart 'noforce)
6142 (org-table-goto-column colpos)
6143 (setq org-table-may-need-update nil)
6144 (if (org-in-invisibility-spec-p '(org-table))
6145 (org-table-add-invisible-to-vertical-lines))
6146 ))
6147
6148 (defun org-table-begin (&optional table-type)
6149 "Find the beginning of the table and return its position.
6150 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6151 (save-excursion
6152 (if (not (re-search-backward
6153 (if table-type org-table-any-border-regexp
6154 org-table-border-regexp)
6155 nil t))
6156 (error "Can't find beginning of table")
6157 (goto-char (match-beginning 0))
6158 (beginning-of-line 2)
6159 (point))))
6160
6161 (defun org-table-end (&optional table-type)
6162 "Find the end of the table and return its position.
6163 With argument TABLE-TYPE, go to the end of a table.el-type table."
6164 (save-excursion
6165 (if (not (re-search-forward
6166 (if table-type org-table-any-border-regexp
6167 org-table-border-regexp)
6168 nil t))
6169 (goto-char (point-max))
6170 (goto-char (match-beginning 0)))
6171 (point-marker)))
6172
6173 (defun org-table-justify-field-maybe (&optional new)
6174 "Justify the current field, text to left, number to right.
6175 Optional argument NEW may specify text to replace the current field content."
6176 (cond
6177 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6178 ((org-at-table-hline-p)
6179 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6180 ;; (setq org-table-may-need-update t)
6181 )
6182 ((and (not new)
6183 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6184 (current-buffer)))
6185 (< (point) org-table-aligned-begin-marker)
6186 (>= (point) org-table-aligned-end-marker)))
6187 ;; This is not the same table, force a full re-align
6188 (setq org-table-may-need-update t))
6189 (t ;; realign the current field, based on previous full realign
6190 (let* ((pos (point)) s
6191 (col (org-table-current-column))
6192 (num (nth (1- col) org-table-last-alignment))
6193 l f n o e)
6194 (when (> col 0)
6195 (skip-chars-backward "^|\n")
6196 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6197 (progn
6198 (setq s (match-string 1)
6199 o (match-string 0)
6200 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6201 e (not (= (match-beginning 2) (match-end 2))))
6202 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6203 l (if e "|" (setq org-table-may-need-update t) ""))
6204 n (format f s t t))
6205 (if new
6206 (if (<= (length new) l)
6207 (setq n (format f new t t)) ;; FIXME: why t t?????
6208 (setq n (concat new "|") org-table-may-need-update t)))
6209 (or (equal n o)
6210 (let (org-table-may-need-update)
6211 (replace-match n))))
6212 (setq org-table-may-need-update t))
6213 (goto-char pos))))))
6214
6215 (defun org-table-next-field ()
6216 "Go to the next field in the current table.
6217 Before doing so, re-align the table if necessary."
6218 (interactive)
6219 (org-table-maybe-eval-formula)
6220 (org-table-maybe-recalculate-line)
6221 (if (and org-table-automatic-realign
6222 org-table-may-need-update)
6223 (org-table-align))
6224 (if (org-at-table-hline-p)
6225 (end-of-line 1))
6226 (condition-case nil
6227 (progn
6228 (re-search-forward "|" (org-table-end))
6229 (if (looking-at "[ \t]*$")
6230 (re-search-forward "|" (org-table-end)))
6231 (if (looking-at "-")
6232 (progn
6233 (beginning-of-line 0)
6234 (org-table-insert-row 'below))
6235 (if (looking-at " ") (forward-char 1))))
6236 (error
6237 (org-table-insert-row 'below))))
6238
6239 (defun org-table-previous-field ()
6240 "Go to the previous field in the table.
6241 Before doing so, re-align the table if necessary."
6242 (interactive)
6243 (org-table-justify-field-maybe)
6244 (org-table-maybe-recalculate-line)
6245 (if (and org-table-automatic-realign
6246 org-table-may-need-update)
6247 (org-table-align))
6248 (if (org-at-table-hline-p)
6249 (end-of-line 1))
6250 (re-search-backward "|" (org-table-begin))
6251 (re-search-backward "|" (org-table-begin))
6252 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6253 (re-search-backward "|" (org-table-begin)))
6254 (if (looking-at "| ?")
6255 (goto-char (match-end 0))))
6256
6257 (defun org-table-next-row ()
6258 "Go to the next row (same column) in the current table.
6259 Before doing so, re-align the table if necessary."
6260 (interactive)
6261 (org-table-maybe-eval-formula)
6262 (org-table-maybe-recalculate-line)
6263 (if (or (looking-at "[ \t]*$")
6264 (save-excursion (skip-chars-backward " \t") (bolp)))
6265 (newline)
6266 (if (and org-table-automatic-realign
6267 org-table-may-need-update)
6268 (org-table-align))
6269 (let ((col (org-table-current-column)))
6270 (beginning-of-line 2)
6271 (if (or (not (org-at-table-p))
6272 (org-at-table-hline-p))
6273 (progn
6274 (beginning-of-line 0)
6275 (org-table-insert-row 'below)))
6276 (org-table-goto-column col)
6277 (skip-chars-backward "^|\n\r")
6278 (if (looking-at " ") (forward-char 1)))))
6279
6280 (defun org-table-copy-down (n)
6281 "Copy a field down in the current column.
6282 If the field at the cursor is empty, copy into it the content of the nearest
6283 non-empty field above. With argument N, use the Nth non-empty field.
6284 If the current field is not empty, it is copied down to the next row, and
6285 the cursor is moved with it. Therefore, repeating this command causes the
6286 column to be filled row-by-row.
6287 If the variable `org-table-copy-increment' is non-nil and the field is an
6288 integer, it will be incremented while copying."
6289 (interactive "p")
6290 (let* ((colpos (org-table-current-column))
6291 (field (org-table-get-field))
6292 (non-empty (string-match "[^ \t]" field))
6293 (beg (org-table-begin))
6294 txt)
6295 (org-table-check-inside-data-field)
6296 (if non-empty
6297 (progn
6298 (setq txt (org-trim field))
6299 (org-table-next-row)
6300 (org-table-blank-field))
6301 (save-excursion
6302 (setq txt
6303 (catch 'exit
6304 (while (progn (beginning-of-line 1)
6305 (re-search-backward org-table-dataline-regexp
6306 beg t))
6307 (org-table-goto-column colpos t)
6308 (if (and (looking-at
6309 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6310 (= (setq n (1- n)) 0))
6311 (throw 'exit (match-string 1))))))))
6312 (if txt
6313 (progn
6314 (if (and org-table-copy-increment
6315 (string-match "^[0-9]+$" txt))
6316 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6317 (insert txt)
6318 (org-table-maybe-recalculate-line)
6319 (org-table-align))
6320 (error "No non-empty field found"))))
6321
6322 (defun org-table-check-inside-data-field ()
6323 "Is point inside a table data field?
6324 I.e. not on a hline or before the first or after the last column?"
6325 (if (or (not (org-at-table-p))
6326 (= (org-table-current-column) 0)
6327 (org-at-table-hline-p)
6328 (looking-at "[ \t]*$"))
6329 (error "Not in table data field")))
6330
6331 (defvar org-table-clip nil
6332 "Clipboard for table regions.")
6333
6334 (defun org-table-blank-field ()
6335 "Blank the current table field or active region."
6336 (interactive)
6337 (org-table-check-inside-data-field)
6338 (if (and (interactive-p) (org-region-active-p))
6339 (let (org-table-clip)
6340 (org-table-cut-region (region-beginning) (region-end)))
6341 (skip-chars-backward "^|")
6342 (backward-char 1)
6343 (if (looking-at "|[^|\n]+")
6344 (let* ((pos (match-beginning 0))
6345 (match (match-string 0))
6346 (len (length match)))
6347 (replace-match (concat "|" (make-string (1- len) ?\ )))
6348 (goto-char (+ 2 pos))
6349 (substring match 1)))))
6350
6351 (defun org-table-get-field (&optional n replace)
6352 "Return the value of the field in column N of current row.
6353 N defaults to current field.
6354 If REPLACE is a string, replace field with this value. The return value
6355 is always the old value."
6356 (and n (org-table-goto-column n))
6357 (skip-chars-backward "^|\n")
6358 (backward-char 1)
6359 (if (looking-at "|[^|\r\n]*")
6360 (let* ((pos (match-beginning 0))
6361 (val (buffer-substring (1+ pos) (match-end 0))))
6362 (if replace
6363 (replace-match (concat "|" replace)))
6364 (goto-char (min (point-at-eol) (+ 2 pos)))
6365 val)
6366 (forward-char 1) ""))
6367
6368 (defun org-table-current-column ()
6369 "Find out which column we are in.
6370 When called interactively, column is also displayed in echo area."
6371 (interactive)
6372 (if (interactive-p) (org-table-check-inside-data-field))
6373 (save-excursion
6374 (let ((cnt 0) (pos (point)))
6375 (beginning-of-line 1)
6376 (while (search-forward "|" pos t)
6377 (setq cnt (1+ cnt)))
6378 (if (interactive-p) (message "This is table column %d" cnt))
6379 cnt)))
6380
6381 (defun org-table-goto-column (n &optional on-delim force)
6382 "Move the cursor to the Nth column in the current table line.
6383 With optional argument ON-DELIM, stop with point before the left delimiter
6384 of the field.
6385 If there are less than N fields, just go to after the last delimiter.
6386 However, when FORCE is non-nil, create new columns if necessary."
6387 (let ((pos (point-at-eol)))
6388 (beginning-of-line 1)
6389 (when (> n 0)
6390 (while (and (> (setq n (1- n)) -1)
6391 (or (search-forward "|" pos t)
6392 (and force
6393 (progn (end-of-line 1)
6394 (skip-chars-backward "^|")
6395 (insert " | "))))))
6396 ; (backward-char 2) t)))))
6397 (when (and force (not (looking-at ".*|")))
6398 (save-excursion (end-of-line 1) (insert " | ")))
6399 (if on-delim
6400 (backward-char 1)
6401 (if (looking-at " ") (forward-char 1))))))
6402
6403 (defun org-at-table-p (&optional table-type)
6404 "Return t if the cursor is inside an org-type table.
6405 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6406 (if org-enable-table-editor
6407 (save-excursion
6408 (beginning-of-line 1)
6409 (looking-at (if table-type org-table-any-line-regexp
6410 org-table-line-regexp)))
6411 nil))
6412
6413 (defun org-table-recognize-table.el ()
6414 "If there is a table.el table nearby, recognize it and move into it."
6415 (if org-table-tab-recognizes-table.el
6416 (if (org-at-table.el-p)
6417 (progn
6418 (beginning-of-line 1)
6419 (if (looking-at org-table-dataline-regexp)
6420 nil
6421 (if (looking-at org-table1-hline-regexp)
6422 (progn
6423 (beginning-of-line 2)
6424 (if (looking-at org-table-any-border-regexp)
6425 (beginning-of-line -1)))))
6426 (if (re-search-forward "|" (org-table-end t) t)
6427 (progn
6428 (require 'table)
6429 (if (table--at-cell-p (point))
6430 t
6431 (message "recognizing table.el table...")
6432 (table-recognize-table)
6433 (message "recognizing table.el table...done")))
6434 (error "This should not happen..."))
6435 t)
6436 nil)
6437 nil))
6438
6439 (defun org-at-table.el-p ()
6440 "Return t if the cursor is inside a table.el-type table."
6441 (save-excursion
6442 (if (org-at-table-p 'any)
6443 (progn
6444 (goto-char (org-table-begin 'any))
6445 (looking-at org-table1-hline-regexp))
6446 nil)))
6447
6448 (defun org-at-table-hline-p ()
6449 "Return t if the cursor is inside a hline in a table."
6450 (if org-enable-table-editor
6451 (save-excursion
6452 (beginning-of-line 1)
6453 (looking-at org-table-hline-regexp))
6454 nil))
6455
6456 (defun org-table-insert-column ()
6457 "Insert a new column into the table."
6458 (interactive)
6459 (if (not (org-at-table-p))
6460 (error "Not at a table"))
6461 (org-table-find-dataline)
6462 (let* ((col (max 1 (org-table-current-column)))
6463 (beg (org-table-begin))
6464 (end (org-table-end))
6465 ;; Current cursor position
6466 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6467 (colpos col))
6468 (goto-char beg)
6469 (while (< (point) end)
6470 (if (org-at-table-hline-p)
6471 nil
6472 (org-table-goto-column col t)
6473 (insert "| "))
6474 (beginning-of-line 2))
6475 (move-marker end nil)
6476 (goto-line linepos)
6477 (org-table-goto-column colpos)
6478 (org-table-align)
6479 (org-table-modify-formulas 'insert col)))
6480
6481 (defun org-table-find-dataline ()
6482 "Find a dataline in the current table, which is needed for column commands."
6483 (if (and (org-at-table-p)
6484 (not (org-at-table-hline-p)))
6485 t
6486 (let ((col (current-column))
6487 (end (org-table-end)))
6488 (move-to-column col)
6489 (while (and (< (point) end)
6490 (or (not (= (current-column) col))
6491 (org-at-table-hline-p)))
6492 (beginning-of-line 2)
6493 (move-to-column col))
6494 (if (and (org-at-table-p)
6495 (not (org-at-table-hline-p)))
6496 t
6497 (error
6498 "Please position cursor in a data line for column operations")))))
6499
6500 (defun org-table-delete-column ()
6501 "Delete a column into the table."
6502 (interactive)
6503 (if (not (org-at-table-p))
6504 (error "Not at a table"))
6505 (org-table-find-dataline)
6506 (org-table-check-inside-data-field)
6507 (let* ((col (org-table-current-column))
6508 (beg (org-table-begin))
6509 (end (org-table-end))
6510 ;; Current cursor position
6511 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6512 (colpos col))
6513 (goto-char beg)
6514 (while (< (point) end)
6515 (if (org-at-table-hline-p)
6516 nil
6517 (org-table-goto-column col t)
6518 (and (looking-at "|[^|\n]+|")
6519 (replace-match "|")))
6520 (beginning-of-line 2))
6521 (move-marker end nil)
6522 (goto-line linepos)
6523 (org-table-goto-column colpos)
6524 (org-table-align)
6525 (org-table-modify-formulas 'remove col)))
6526
6527 (defun org-table-move-column-right ()
6528 "Move column to the right."
6529 (interactive)
6530 (org-table-move-column nil))
6531 (defun org-table-move-column-left ()
6532 "Move column to the left."
6533 (interactive)
6534 (org-table-move-column 'left))
6535
6536 (defun org-table-move-column (&optional left)
6537 "Move the current column to the right. With arg LEFT, move to the left."
6538 (interactive "P")
6539 (if (not (org-at-table-p))
6540 (error "Not at a table"))
6541 (org-table-find-dataline)
6542 (org-table-check-inside-data-field)
6543 (let* ((col (org-table-current-column))
6544 (col1 (if left (1- col) col))
6545 (beg (org-table-begin))
6546 (end (org-table-end))
6547 ;; Current cursor position
6548 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6549 (colpos (if left (1- col) (1+ col))))
6550 (if (and left (= col 1))
6551 (error "Cannot move column further left"))
6552 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6553 (error "Cannot move column further right"))
6554 (goto-char beg)
6555 (while (< (point) end)
6556 (if (org-at-table-hline-p)
6557 nil
6558 (org-table-goto-column col1 t)
6559 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6560 (replace-match "|\\2|\\1|")))
6561 (beginning-of-line 2))
6562 (move-marker end nil)
6563 (goto-line linepos)
6564 (org-table-goto-column colpos)
6565 (org-table-align)
6566 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6567
6568 (defun org-table-move-row-down ()
6569 "move table row down."
6570 (interactive)
6571 (org-table-move-row nil))
6572 (defun org-table-move-row-up ()
6573 "move table row up."
6574 (interactive)
6575 (org-table-move-row 'up))
6576
6577 (defun org-table-move-row (&optional up)
6578 "Move the current table line down. With arg UP, move it up."
6579 (interactive "P")
6580 (let ((col (current-column))
6581 (pos (point))
6582 (tonew (if up 0 2))
6583 txt)
6584 (beginning-of-line tonew)
6585 (if (not (org-at-table-p))
6586 (progn
6587 (goto-char pos)
6588 (error "Cannot move row further")))
6589 (goto-char pos)
6590 (beginning-of-line 1)
6591 (setq pos (point))
6592 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6593 (delete-region (point) (1+ (point-at-eol)))
6594 (beginning-of-line tonew)
6595 (insert txt)
6596 (beginning-of-line 0)
6597 (move-to-column col)))
6598
6599 (defun org-table-insert-row (&optional arg)
6600 "Insert a new row above the current line into the table.
6601 With prefix ARG, insert below the current line."
6602 (interactive "P")
6603 (if (not (org-at-table-p))
6604 (error "Not at a table"))
6605 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6606 new)
6607 (if (string-match "^[ \t]*|-" line)
6608 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6609 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6610 ;; Fix the first field if necessary
6611 (setq new (concat new))
6612 (if (string-match "^[ \t]*| *[#$] *|" line)
6613 (setq new (replace-match (match-string 0 line) t t new)))
6614 (beginning-of-line (if arg 2 1))
6615 (let (org-table-may-need-update)
6616 (insert-before-markers new)
6617 (insert-before-markers "\n"))
6618 (beginning-of-line 0)
6619 (re-search-forward "| ?" (point-at-eol) t)
6620 (and org-table-may-need-update (org-table-align))))
6621
6622 (defun org-table-insert-hline (&optional arg)
6623 "Insert a horizontal-line below the current line into the table.
6624 With prefix ARG, insert above the current line."
6625 (interactive "P")
6626 (if (not (org-at-table-p))
6627 (error "Not at a table"))
6628 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6629 (col (current-column))
6630 start)
6631 (if (string-match "^[ \t]*|-" line)
6632 (setq line
6633 (mapcar (lambda (x) (if (member x '(?| ?+))
6634 (prog1 (if start ?+ ?|) (setq start t))
6635 (if start ?- ?\ )))
6636 line))
6637 (setq line
6638 (mapcar (lambda (x) (if (equal x ?|)
6639 (prog1 (if start ?+ ?|) (setq start t))
6640 (if start ?- ?\ )))
6641 line)))
6642 (beginning-of-line (if arg 1 2))
6643 (apply 'insert line)
6644 (if (equal (char-before (point)) ?+)
6645 (progn (backward-delete-char 1) (insert "|")))
6646 (insert "\n")
6647 (beginning-of-line 0)
6648 (move-to-column col)))
6649
6650 (defun org-table-kill-row ()
6651 "Delete the current row or horizontal line from the table."
6652 (interactive)
6653 (if (not (org-at-table-p))
6654 (error "Not at a table"))
6655 (let ((col (current-column)))
6656 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6657 (if (not (org-at-table-p)) (beginning-of-line 0))
6658 (move-to-column col)))
6659
6660
6661 (defun org-table-cut-region (beg end)
6662 "Copy region in table to the clipboard and blank all relevant fields."
6663 (interactive "r")
6664 (org-table-copy-region beg end 'cut))
6665
6666 (defun org-table-copy-region (beg end &optional cut)
6667 "Copy rectangular region in table to clipboard.
6668 A special clipboard is used which can only be accessed
6669 with `org-table-paste-rectangle'"
6670 (interactive "rP")
6671 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6672 region cols
6673 (rpl (if cut " " nil)))
6674 (goto-char beg)
6675 (org-table-check-inside-data-field)
6676 (setq l01 (count-lines (point-min) (point))
6677 c01 (org-table-current-column))
6678 (goto-char end)
6679 (org-table-check-inside-data-field)
6680 (setq l02 (count-lines (point-min) (point))
6681 c02 (org-table-current-column))
6682 (setq l1 (min l01 l02) l2 (max l01 l02)
6683 c1 (min c01 c02) c2 (max c01 c02))
6684 (catch 'exit
6685 (while t
6686 (catch 'nextline
6687 (if (> l1 l2) (throw 'exit t))
6688 (goto-line l1)
6689 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6690 (setq cols nil ic1 c1 ic2 c2)
6691 (while (< ic1 (1+ ic2))
6692 (push (org-table-get-field ic1 rpl) cols)
6693 (setq ic1 (1+ ic1)))
6694 (push (nreverse cols) region)
6695 (setq l1 (1+ l1)))))
6696 (setq org-table-clip (nreverse region))
6697 (if cut (org-table-align))
6698 org-table-clip))
6699
6700 (defun org-table-paste-rectangle ()
6701 "Paste a rectangular region into a table.
6702 The upper right corner ends up in the current field. All involved fields
6703 will be overwritten. If the rectangle does not fit into the present table,
6704 the table is enlarged as needed. The process ignores horizontal separator
6705 lines."
6706 (interactive)
6707 (unless (and org-table-clip (listp org-table-clip))
6708 (error "First cut/copy a region to paste!"))
6709 (org-table-check-inside-data-field)
6710 (let* ((clip org-table-clip)
6711 (line (count-lines (point-min) (point)))
6712 (col (org-table-current-column))
6713 (org-enable-table-editor t)
6714 (org-table-automatic-realign nil)
6715 c cols field)
6716 (while (setq cols (pop clip))
6717 (while (org-at-table-hline-p) (beginning-of-line 2))
6718 (if (not (org-at-table-p))
6719 (progn (end-of-line 0) (org-table-next-field)))
6720 (setq c col)
6721 (while (setq field (pop cols))
6722 (org-table-goto-column c nil 'force)
6723 (org-table-get-field nil field)
6724 (setq c (1+ c)))
6725 (beginning-of-line 2))
6726 (goto-line line)
6727 (org-table-goto-column col)
6728 (org-table-align)))
6729
6730 (defun org-table-convert ()
6731 "Convert from `org-mode' table to table.el and back.
6732 Obviously, this only works within limits. When an Org-mode table is
6733 converted to table.el, all horizontal separator lines get lost, because
6734 table.el uses these as cell boundaries and has no notion of horizontal lines.
6735 A table.el table can be converted to an Org-mode table only if it does not
6736 do row or column spanning. Multiline cells will become multiple cells.
6737 Beware, Org-mode does not test if the table can be successfully converted - it
6738 blindly applies a recipe that works for simple tables."
6739 (interactive)
6740 (require 'table)
6741 (if (org-at-table.el-p)
6742 ;; convert to Org-mode table
6743 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6744 (end (move-marker (make-marker) (org-table-end t))))
6745 (table-unrecognize-region beg end)
6746 (goto-char beg)
6747 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6748 (replace-match ""))
6749 (goto-char beg))
6750 (if (org-at-table-p)
6751 ;; convert to table.el table
6752 (let ((beg (move-marker (make-marker) (org-table-begin)))
6753 (end (move-marker (make-marker) (org-table-end))))
6754 ;; first, get rid of all horizontal lines
6755 (goto-char beg)
6756 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6757 (replace-match ""))
6758 ;; insert a hline before first
6759 (goto-char beg)
6760 (org-table-insert-hline 'above)
6761 ;; insert a hline after each line
6762 (while (progn (beginning-of-line 2) (< (point) end))
6763 (org-table-insert-hline))
6764 (goto-char beg)
6765 (setq end (move-marker end (org-table-end)))
6766 ;; replace "+" at beginning and ending of hlines
6767 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6768 (replace-match "\\1+-"))
6769 (goto-char beg)
6770 (while (re-search-forward "-|[ \t]*$" end t)
6771 (replace-match "-+"))
6772 (goto-char beg)))))
6773
6774 (defun org-table-wrap-region (arg)
6775 "Wrap several fields in a column like a paragraph.
6776 This is useful if you'd like to spread the contents of a field over several
6777 lines, in order to keep the table compact.
6778
6779 If there is an active region, and both point and mark are in the same column,
6780 the text in the column is wrapped to minimum width for the given number of
6781 lines. Generally, this makes the table more compact. A prefix ARG may be
6782 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6783 formats the selected text to two lines. If the region was longer than 2
6784 lines, the remaining lines remain empty. A negative prefix argument reduces
6785 the current number of lines by that amount. The wrapped text is pasted back
6786 into the table. If you formatted it to more lines than it was before, fields
6787 further down in the table get overwritten - so you might need to make space in
6788 the table first.
6789
6790 If there is no region, the current field is split at the cursor position and
6791 the text fragment to the right of the cursor is prepended to the field one
6792 line down.
6793
6794 If there is no region, but you specify a prefix ARG, the current field gets
6795 blank, and the content is appended to the field above."
6796 (interactive "P")
6797 (org-table-check-inside-data-field)
6798 (if (org-region-active-p)
6799 ;; There is a region: fill as a paragraph
6800 (let ((beg (region-beginning))
6801 nlines)
6802 (org-table-cut-region (region-beginning) (region-end))
6803 (if (> (length (car org-table-clip)) 1)
6804 (error "Region must be limited to single column"))
6805 (setq nlines (if arg
6806 (if (< arg 1)
6807 (+ (length org-table-clip) arg)
6808 arg)
6809 (length org-table-clip)))
6810 (setq org-table-clip
6811 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6812 nil nlines)))
6813 (goto-char beg)
6814 (org-table-paste-rectangle))
6815 ;; No region, split the current field at point
6816 (if arg
6817 ;; combine with field above
6818 (let ((s (org-table-blank-field))
6819 (col (org-table-current-column)))
6820 (beginning-of-line 0)
6821 (while (org-at-table-hline-p) (beginning-of-line 0))
6822 (org-table-goto-column col)
6823 (skip-chars-forward "^|")
6824 (skip-chars-backward " ")
6825 (insert " " (org-trim s))
6826 (org-table-align))
6827 ;; split field
6828 (when (looking-at "\\([^|]+\\)+|")
6829 (let ((s (match-string 1)))
6830 (replace-match " |")
6831 (goto-char (match-beginning 0))
6832 (org-table-next-row)
6833 (insert (org-trim s) " ")
6834 (org-table-align))))))
6835
6836 (defun org-trim (s)
6837 "Remove whitespace at beginning and end of string."
6838 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6839 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6840 s)
6841
6842 (defun org-wrap (string &optional width lines)
6843 "Wrap string to either a number of lines, or a width in characters.
6844 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6845 that costs. If there is a word longer than WIDTH, the text is actually
6846 wrapped to the length of that word.
6847 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6848 many lines, whatever width that takes.
6849 The return value is a list of lines, without newlines at the end."
6850 (let* ((words (org-split-string string "[ \t\n]+"))
6851 (maxword (apply 'max (mapcar 'length words)))
6852 w ll)
6853 (cond (width
6854 (org-do-wrap words (max maxword width)))
6855 (lines
6856 (setq w maxword)
6857 (setq ll (org-do-wrap words maxword))
6858 (if (<= (length ll) lines)
6859 ll
6860 (setq ll words)
6861 (while (> (length ll) lines)
6862 (setq w (1+ w))
6863 (setq ll (org-do-wrap words w)))
6864 ll))
6865 (t (error "Cannot wrap this")))))
6866
6867
6868 (defun org-do-wrap (words width)
6869 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6870 (let (lines line)
6871 (while words
6872 (setq line (pop words))
6873 (while (and words (< (+ (length line) (length (car words))) width))
6874 (setq line (concat line " " (pop words))))
6875 (setq lines (push line lines)))
6876 (nreverse lines)))
6877
6878 ;; FIXME: I think I can make this more efficient
6879 (defun org-split-string (string &optional separators)
6880 "Splits STRING into substrings at SEPARATORS.
6881 No empty strings are returned if there are matches at the beginning
6882 and end of string."
6883 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6884 (start 0)
6885 notfirst
6886 (list nil))
6887 (while (and (string-match rexp string
6888 (if (and notfirst
6889 (= start (match-beginning 0))
6890 (< start (length string)))
6891 (1+ start) start))
6892 (< (match-beginning 0) (length string)))
6893 (setq notfirst t)
6894 (or (eq (match-beginning 0) 0)
6895 (and (eq (match-beginning 0) (match-end 0))
6896 (eq (match-beginning 0) start))
6897 (setq list
6898 (cons (substring string start (match-beginning 0))
6899 list)))
6900 (setq start (match-end 0)))
6901 (or (eq start (length string))
6902 (setq list
6903 (cons (substring string start)
6904 list)))
6905 (nreverse list)))
6906
6907 (defun org-table-add-invisible-to-vertical-lines ()
6908 "Add an `invisible' property to vertical lines of current table."
6909 (interactive)
6910 (let* ((beg (org-table-begin))
6911 (end (org-table-end))
6912 (end1))
6913 (save-excursion
6914 (goto-char beg)
6915 (while (< (point) end)
6916 (setq end1 (point-at-eol))
6917 (if (looking-at org-table-dataline-regexp)
6918 (while (re-search-forward "|" end1 t)
6919 (add-text-properties (1- (point)) (point)
6920 '(invisible org-table)))
6921 (while (re-search-forward "[+|]" end1 t)
6922 (add-text-properties (1- (point)) (point)
6923 '(invisible org-table))))
6924 (beginning-of-line 2)))))
6925
6926 (defun org-table-toggle-vline-visibility (&optional arg)
6927 "Toggle the visibility of table vertical lines.
6928 The effect is immediate and on all tables in the file.
6929 With prefix ARG, make lines invisible when ARG is positive, make lines
6930 visible when ARG is not positive"
6931 (interactive "P")
6932 (let ((action (cond
6933 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6934 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6935 (t (if (org-in-invisibility-spec-p '(org-table))
6936 'off
6937 'on)))))
6938 (if (eq action 'off)
6939 (progn
6940 (org-remove-from-invisibility-spec '(org-table))
6941 (org-table-map-tables 'org-table-align)
6942 (message "Vertical table lines visible")
6943 (if (org-at-table-p)
6944 (org-table-align)))
6945 (org-add-to-invisibility-spec '(org-table))
6946 (org-table-map-tables 'org-table-align)
6947 (message "Vertical table lines invisible"))
6948 (redraw-frame (selected-frame))))
6949
6950 (defun org-table-map-tables (function)
6951 "Apply FUNCTION to the start of all tables in the buffer."
6952 (save-excursion
6953 (save-restriction
6954 (widen)
6955 (goto-char (point-min))
6956 (while (re-search-forward org-table-any-line-regexp nil t)
6957 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6958 (beginning-of-line 1)
6959 (if (looking-at org-table-line-regexp)
6960 (save-excursion (funcall function)))
6961 (re-search-forward org-table-any-border-regexp nil 1)))))
6962
6963 (defun org-table-sum (&optional beg end nlast)
6964 "Sum numbers in region of current table column.
6965 The result will be displayed in the echo area, and will be available
6966 as kill to be inserted with \\[yank].
6967
6968 If there is an active region, it is interpreted as a rectangle and all
6969 numbers in that rectangle will be summed. If there is no active
6970 region and point is located in a table column, sum all numbers in that
6971 column.
6972
6973 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6974 numbers are assumed to be times as well (in decimal hours) and the
6975 numbers are added as such.
6976
6977 If NLAST is a number, only the NLAST fields will actually be summed."
6978 (interactive)
6979 (save-excursion
6980 (let (col (timecnt 0) diff h m s org-table-clip)
6981 (cond
6982 ((and beg end)) ; beg and end given explicitly
6983 ((org-region-active-p)
6984 (setq beg (region-beginning) end (region-end)))
6985 (t
6986 (setq col (org-table-current-column))
6987 (goto-char (org-table-begin))
6988 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6989 (error "No table data"))
6990 (org-table-goto-column col)
6991 ;not needed? (skip-chars-backward "^|")
6992 (setq beg (point))
6993 (goto-char (org-table-end))
6994 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6995 (error "No table data"))
6996 (org-table-goto-column col)
6997 ;not needed? (skip-chars-forward "^|")
6998 (setq end (point))))
6999 (let* ((items (apply 'append (org-table-copy-region beg end)))
7000 (items1 (cond ((not nlast) items)
7001 ((>= nlast (length items)) items)
7002 (t (setq items (reverse items))
7003 (setcdr (nthcdr (1- nlast) items) nil)
7004 (nreverse items))))
7005 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7006 items1)))
7007 (res (apply '+ numbers))
7008 (sres (if (= timecnt 0)
7009 (format "%g" res)
7010 (setq diff (* 3600 res)
7011 h (floor (/ diff 3600)) diff (mod diff 3600)
7012 m (floor (/ diff 60)) diff (mod diff 60)
7013 s diff)
7014 (format "%d:%02d:%02d" h m s))))
7015 (kill-new sres)
7016 (if (interactive-p)
7017 (message (substitute-command-keys
7018 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7019 (length numbers) sres))))
7020 sres))))
7021
7022 (defun org-table-get-number-for-summing (s)
7023 (let (n)
7024 (if (string-match "^ *|? *" s)
7025 (setq s (replace-match "" nil nil s)))
7026 (if (string-match " *|? *$" s)
7027 (setq s (replace-match "" nil nil s)))
7028 (setq n (string-to-number s))
7029 (cond
7030 ((and (string-match "0" s)
7031 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7032 ((string-match "\\`[ \t]+\\'" s) nil)
7033 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7034 (let ((h (string-to-number (or (match-string 1 s) "0")))
7035 (m (string-to-number (or (match-string 2 s) "0")))
7036 (s (string-to-number (or (match-string 4 s) "0"))))
7037 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7038 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7039 ((equal n 0) nil)
7040 (t n))))
7041
7042 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7043 "Get a calc vector from a column, accorting to desctiptor DESC.
7044 Optional arguments TBEG and COL can give the beginning of the table and
7045 the current column, to avoid unnecessary parsing."
7046 (save-excursion
7047 (or tbeg (setq tbeg (org-table-begin)))
7048 (or col (setq col (org-table-current-column)))
7049 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7050 (cond
7051 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7052 (setq n1 (- (match-end 1) (match-beginning 1)))
7053 (if (match-beginning 3)
7054 (setq n2 (- (match-end 2) (match-beginning 3))))
7055 (setq n (if n2 (max n1 n2) n1))
7056 (setq n1 (if n2 (min n1 n2)))
7057 (setq nn n)
7058 (while (and (> nn 0)
7059 (re-search-backward org-table-hline-regexp tbeg t))
7060 (push (org-current-line) hline-list)
7061 (setq nn (1- nn)))
7062 (setq hline-list (nreverse hline-list))
7063 (goto-line (nth (1- n) hline-list))
7064 (when (re-search-forward org-table-dataline-regexp)
7065 (org-table-goto-column col)
7066 (setq beg (point)))
7067 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7068 (when (re-search-backward org-table-dataline-regexp)
7069 (org-table-goto-column col)
7070 (setq end (point)))
7071 (setq l (apply 'append (org-table-copy-region beg end)))
7072 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7073 (if (equal x "") "0" x))
7074 l ",") "]"))
7075 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7076 (setq n1 (string-to-number (match-string 1 desc))
7077 n2 (string-to-number (match-string 2 desc)))
7078 (beginning-of-line 1)
7079 (save-excursion
7080 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7081 (org-table-goto-column col)
7082 (setq beg (point))))
7083 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7084 (org-table-goto-column col)
7085 (setq end (point)))
7086 (setq l (apply 'append (org-table-copy-region beg end)))
7087 (concat "[" (mapconcat
7088 (lambda (x) (setq x (org-trim x))
7089 (if (equal x "") "0" x))
7090 l ",") "]"))
7091 ((string-match "\\([0-9]+\\)" desc)
7092 (beginning-of-line 1)
7093 (when (re-search-backward org-table-dataline-regexp tbeg t
7094 (string-to-number (match-string 0 desc)))
7095 (org-table-goto-column col)
7096 (org-trim (org-table-get-field))))))))
7097
7098 (defvar org-table-formula-history nil)
7099
7100 (defvar org-table-column-names nil
7101 "Alist with column names, derived from the `!' line.")
7102 (defvar org-table-column-name-regexp nil
7103 "Regular expression matching the current column names.")
7104 (defvar org-table-local-parameters nil
7105 "Alist with parameter names, derived from the `$' line.")
7106 (defvar org-table-named-field-locations nil
7107 "Alist with locations of named fields.")
7108
7109 (defun org-table-get-formula (&optional equation named)
7110 "Read a formula from the minibuffer, offer stored formula as default."
7111 (let* ((name (car (rassoc (list (org-current-line)
7112 (org-table-current-column))
7113 org-table-named-field-locations)))
7114 (scol (if named
7115 (if name name
7116 (error "Not in a named field"))
7117 (int-to-string (org-table-current-column))))
7118 (dummy (and name (not named)
7119 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7120 (error "Abort")))
7121 (org-table-may-need-update nil)
7122 (stored-list (org-table-get-stored-formulas))
7123 (stored (cdr (assoc scol stored-list)))
7124 (eq (cond
7125 ((and stored equation (string-match "^ *= *$" equation))
7126 stored)
7127 ((stringp equation)
7128 equation)
7129 (t (read-string
7130 (format "%s formula $%s=" (if named "Field" "Column") scol)
7131 (or stored "") 'org-table-formula-history
7132 ;stored
7133 ))))
7134 mustsave)
7135 (when (not (string-match "\\S-" eq))
7136 ;; remove formula
7137 (setq stored-list (delq (assoc scol stored-list) stored-list))
7138 (org-table-store-formulas stored-list)
7139 (error "Formula removed"))
7140 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7141 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7142 (if (and name (not named))
7143 ;; We set the column equation, delete the named one.
7144 (setq stored-list (delq (assoc name stored-list) stored-list)
7145 mustsave t))
7146 (if stored
7147 (setcdr (assoc scol stored-list) eq)
7148 (setq stored-list (cons (cons scol eq) stored-list)))
7149 (if (or mustsave (not (equal stored eq)))
7150 (org-table-store-formulas stored-list))
7151 eq))
7152
7153 (defun org-table-store-formulas (alist)
7154 "Store the list of formulas below the current table."
7155 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7156 (save-excursion
7157 (goto-char (org-table-end))
7158 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7159 (delete-region (point) (match-end 0)))
7160 (insert "#+TBLFM: "
7161 (mapconcat (lambda (x)
7162 (concat "$" (car x) "=" (cdr x)))
7163 alist "::")
7164 "\n")))
7165
7166 (defun org-table-get-stored-formulas ()
7167 "Return an alist with the t=stored formulas directly after current table."
7168 (interactive)
7169 (let (scol eq eq-alist strings string seen)
7170 (save-excursion
7171 (goto-char (org-table-end))
7172 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7173 (setq strings (org-split-string (match-string 2) " *:: *"))
7174 (while (setq string (pop strings))
7175 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7176 (setq scol (match-string 1 string)
7177 eq (match-string 2 string)
7178 eq-alist (cons (cons scol eq) eq-alist))
7179 (if (member scol seen)
7180 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7181 (push scol seen))))))
7182 (nreverse eq-alist)))
7183
7184 (defun org-table-modify-formulas (action &rest columns)
7185 "Modify the formulas stored below the current table.
7186 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7187 expected, for the other action only a single column number is needed."
7188 (let ((list (org-table-get-stored-formulas))
7189 (nmax (length (org-split-string
7190 (buffer-substring (point-at-bol) (point-at-eol))
7191 "|")))
7192 col col1 col2 scol si sc1 sc2)
7193 (cond
7194 ((null list)) ; No action needed if there are no stored formulas
7195 ((eq action 'remove)
7196 (setq col (car columns)
7197 scol (int-to-string col))
7198 (org-table-replace-in-formulas list scol "INVALID")
7199 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7200 (loop for i from (1+ col) upto nmax by 1 do
7201 (setq si (int-to-string i))
7202 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7203 (if (assoc si list) (setcar (assoc si list)
7204 (int-to-string (1- i))))))
7205 ((eq action 'insert)
7206 (setq col (car columns))
7207 (loop for i from nmax downto col by 1 do
7208 (setq si (int-to-string i))
7209 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7210 (if (assoc si list) (setcar (assoc si list)
7211 (int-to-string (1+ i))))))
7212 ((eq action 'swap)
7213 (setq col1 (car columns) col2 (nth 1 columns)
7214 sc1 (int-to-string col1) sc2 (int-to-string col2))
7215 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7216 (org-table-replace-in-formulas list sc1 "ZqZ")
7217 (org-table-replace-in-formulas list sc2 sc1)
7218 (org-table-replace-in-formulas list "ZqZ" sc2)
7219 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7220 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7221 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7222 (t (error "Invalid action in `org-table-modify-formulas'")))
7223 (if list (org-table-store-formulas list))))
7224
7225 (defun org-table-replace-in-formulas (list s1 s2)
7226 (let (elt re s)
7227 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7228 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7229 re (concat (regexp-quote s1) "\\>"))
7230 (while (setq elt (pop list))
7231 (setq s (cdr elt))
7232 (while (string-match re s)
7233 (setq s (replace-match s2 t t s)))
7234 (setcdr elt s))))
7235
7236 (defun org-table-get-specials ()
7237 "Get the column nmaes and local parameters for this table."
7238 (save-excursion
7239 (let ((beg (org-table-begin)) (end (org-table-end))
7240 names name fields fields1 field cnt c v line col)
7241 (setq org-table-column-names nil
7242 org-table-local-parameters nil
7243 org-table-named-field-locations nil)
7244 (goto-char beg)
7245 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7246 (setq names (org-split-string (match-string 1) " *| *")
7247 cnt 1)
7248 (while (setq name (pop names))
7249 (setq cnt (1+ cnt))
7250 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7251 (push (cons name (int-to-string cnt)) org-table-column-names))))
7252 (setq org-table-column-names (nreverse org-table-column-names))
7253 (setq org-table-column-name-regexp
7254 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7255 (goto-char beg)
7256 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7257 (setq fields (org-split-string (match-string 1) " *| *"))
7258 (while (setq field (pop fields))
7259 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7260 (push (cons (match-string 1 field) (match-string 2 field))
7261 org-table-local-parameters))))
7262 (goto-char beg)
7263 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7264 (setq c (match-string 1)
7265 fields (org-split-string (match-string 2) " *| *"))
7266 (save-excursion
7267 (beginning-of-line (if (equal c "_") 2 0))
7268 (setq line (org-current-line) col 1)
7269 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7270 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7271 (while (and fields1 (setq field (pop fields)))
7272 (setq v (pop fields1) col (1+ col))
7273 (when (and (stringp field) (stringp v)
7274 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7275 (push (cons field v) org-table-local-parameters)
7276 (push (list field line col) org-table-named-field-locations)))))))
7277
7278 (defun org-this-word ()
7279 ;; Get the current word
7280 (save-excursion
7281 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7282 (end (progn (skip-chars-forward "^ \t\n") (point))))
7283 (buffer-substring-no-properties beg end))))
7284
7285 (defun org-table-maybe-eval-formula ()
7286 "Check if the current field starts with \"=\" or \":=\".
7287 If yes, store the formula and apply it."
7288 ;; We already know we are in a table. Get field will only return a formula
7289 ;; when appropriate. It might return a separator line, but no problem.
7290 (when org-table-formula-evaluate-inline
7291 (let* ((field (org-trim (or (org-table-get-field) "")))
7292 named eq)
7293 (when (string-match "^:?=\\(.+\\)" field)
7294 (setq named (equal (string-to-char field) ?:)
7295 eq (match-string 1 field))
7296 (if (fboundp 'calc-eval)
7297 (org-table-eval-formula (if named '(4) nil) eq))))))
7298
7299 (defvar org-recalc-commands nil
7300 "List of commands triggering the reccalculation of a line.
7301 Will be filled automatically during use.")
7302
7303 (defvar org-recalc-marks
7304 '((" " . "Unmarked: no special line, no automatic recalculation")
7305 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7306 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7307 ("!" . "Column name definition line. Reference in formula as $name.")
7308 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7309 ("_" . "Names for values in row below this one.")
7310 ("^" . "Names for values in row above this one.")))
7311
7312 (defun org-table-rotate-recalc-marks (&optional newchar)
7313 "Rotate the recalculation mark in the first column.
7314 If in any row, the first field is not consistent with a mark,
7315 insert a new column for the makers.
7316 When there is an active region, change all the lines in the region,
7317 after prompting for the marking character.
7318 After each change, a message will be displayed indication the meaning
7319 of the new mark."
7320 (interactive)
7321 (unless (org-at-table-p) (error "Not at a table"))
7322 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7323 (beg (org-table-begin))
7324 (end (org-table-end))
7325 (l (org-current-line))
7326 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7327 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7328 (have-col
7329 (save-excursion
7330 (goto-char beg)
7331 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7332 (col (org-table-current-column))
7333 (forcenew (car (assoc newchar org-recalc-marks)))
7334 epos new)
7335 (when l1
7336 (message "Change region to what mark? Type # * ! $ or SPC: ")
7337 (setq newchar (char-to-string (read-char-exclusive))
7338 forcenew (car (assoc newchar org-recalc-marks))))
7339 (if (and newchar (not forcenew))
7340 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7341 newchar))
7342 (if l1 (goto-line l1))
7343 (save-excursion
7344 (beginning-of-line 1)
7345 (unless (looking-at org-table-dataline-regexp)
7346 (error "Not at a table data line")))
7347 (unless have-col
7348 (org-table-goto-column 1)
7349 (org-table-insert-column)
7350 (org-table-goto-column (1+ col)))
7351 (setq epos (point-at-eol))
7352 (save-excursion
7353 (beginning-of-line 1)
7354 (org-table-get-field
7355 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7356 (concat " "
7357 (setq new (or forcenew
7358 (cadr (member (match-string 1) marks))))
7359 " ")
7360 " # ")))
7361 (if (and l1 l2)
7362 (progn
7363 (goto-line l1)
7364 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7365 (and (looking-at org-table-dataline-regexp)
7366 (org-table-get-field 1 (concat " " new " "))))
7367 (goto-line l1)))
7368 (if (not (= epos (point-at-eol))) (org-table-align))
7369 (goto-line l)
7370 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7371
7372 (defun org-table-maybe-recalculate-line ()
7373 "Recompute the current line if marked for it, and if we haven't just done it."
7374 (interactive)
7375 (and org-table-allow-automatic-line-recalculation
7376 (not (and (memq last-command org-recalc-commands)
7377 (equal org-last-recalc-line (org-current-line))))
7378 (save-excursion (beginning-of-line 1)
7379 (looking-at org-table-auto-recalculate-regexp))
7380 (fboundp 'calc-eval)
7381 (org-table-recalculate) t))
7382
7383 (defvar org-table-formula-debug nil
7384 "Non-nil means, debug table formulas.
7385 When nil, simply write \"#ERROR\" in corrupted fields.")
7386
7387 (defvar modes)
7388 (defsubst org-set-calc-mode (var &optional value)
7389 (if (stringp var)
7390 (setq var (assoc var '(("D" calc-angle-mode deg)
7391 ("R" calc-angle-mode rad)
7392 ("F" calc-prefer-frac t)
7393 ("S" calc-symbolic-mode t)))
7394 value (nth 2 var) var (nth 1 var)))
7395 (if (memq var modes)
7396 (setcar (cdr (memq var modes)) value)
7397 (cons var (cons value modes)))
7398 modes)
7399
7400 (defun org-table-eval-formula (&optional arg equation
7401 suppress-align suppress-const
7402 suppress-store)
7403 "Replace the table field value at the cursor by the result of a calculation.
7404
7405 This function makes use of Dave Gillespie's calc package, in my view the
7406 most exciting program ever written for GNU Emacs. So you need to have calc
7407 installed in order to use this function.
7408
7409 In a table, this command replaces the value in the current field with the
7410 result of a formula. It also installes the formula as the \"current\" column
7411 formula, by storing it in a special line below the table. When called
7412 with a `C-u' prefix, the current field must ba a named field, and the
7413 formula is installed as valid in only this specific field.
7414
7415 When called, the command first prompts for a formula, which is read in
7416 the minibuffer. Previously entered formulas are available through the
7417 history list, and the last used formula is offered as a default.
7418 These stored formulas are adapted correctly when moving, inserting, or
7419 deleting columns with the corresponding commands.
7420
7421 The formula can be any algebraic expression understood by the calc package.
7422 For details, see the Org-mode manual.
7423
7424 This function can also be called from Lisp programs and offers
7425 additional Arguments: EQUATION can be the formula to apply. If this
7426 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7427 used to speed-up recursive calls by by-passing unnecessary aligns.
7428 SUPPRESS-CONST suppresses the interpretation of constants in the
7429 formula, assuming that this has been done already outside the fuction.
7430 SUPPRESS-STORE means the formula should not be stored, either because
7431 it is already stored, or because it is a modified equation that should
7432 not overwrite the stored one."
7433 (interactive "P")
7434 (require 'calc)
7435 (org-table-check-inside-data-field)
7436 (org-table-get-specials)
7437 (let* (fields
7438 (ndown (if (integerp arg) arg 1))
7439 (org-table-automatic-realign nil)
7440 (case-fold-search nil)
7441 (down (> ndown 1))
7442 (formula (if (and equation suppress-store)
7443 equation
7444 (org-table-get-formula equation (equal arg '(4)))))
7445 (n0 (org-table-current-column))
7446 (modes (copy-sequence org-calc-default-modes))
7447 n form fmt x ev orig c)
7448 ;; Parse the format string. Since we have a lot of modes, this is
7449 ;; a lot of work. However, I think calc still uses most of the time.
7450 (if (string-match ";" formula)
7451 (let ((tmp (org-split-string formula ";")))
7452 (setq formula (car tmp)
7453 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7454 (nth 1 tmp)))
7455 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7456 (setq c (string-to-char (match-string 1 fmt))
7457 n (string-to-number (or (match-string 1 fmt) "")))
7458 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7459 (setq modes (org-set-calc-mode
7460 'calc-float-format
7461 (list (cdr (assoc c '((?n. float) (?f. fix)
7462 (?s. sci) (?e. eng))))
7463 n))))
7464 (setq fmt (replace-match "" t t fmt)))
7465 (while (string-match "[DRFS]" fmt)
7466 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7467 (setq fmt (replace-match "" t t fmt)))
7468 (unless (string-match "\\S-" fmt)
7469 (setq fmt nil))))
7470 (if (and (not suppress-const) org-table-formula-use-constants)
7471 (setq formula (org-table-formula-substitute-names formula)))
7472 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7473 (while (> ndown 0)
7474 (setq fields (org-split-string
7475 (buffer-substring
7476 (point-at-bol) (point-at-eol)) " *| *"))
7477 (if org-table-formula-numbers-only
7478 (setq fields (mapcar
7479 (lambda (x) (number-to-string (string-to-number x)))
7480 fields)))
7481 (setq ndown (1- ndown))
7482 (setq form (copy-sequence formula))
7483 ;; Insert the references to fields in same row
7484 (while (string-match "\\$\\([0-9]+\\)?" form)
7485 (setq n (if (match-beginning 1)
7486 (string-to-number (match-string 1 form))
7487 n0)
7488 x (nth (1- n) fields))
7489 (unless x (error "Invalid field specifier \"%s\""
7490 (match-string 0 form)))
7491 (if (equal x "") (setq x "0"))
7492 (setq form (replace-match (concat "(" x ")") t t form)))
7493 ;; Insert ranges in current column
7494 (while (string-match "\\&[-I0-9]+" form)
7495 (setq form (replace-match
7496 (save-match-data
7497 (org-table-get-vertical-vector (match-string 0 form)
7498 nil n0))
7499 t t form)))
7500 (setq ev (calc-eval (cons form modes)
7501 (if org-table-formula-numbers-only 'num)))
7502
7503 (when org-table-formula-debug
7504 (with-output-to-temp-buffer "*Help*"
7505 (princ (format "Substitution history of formula
7506 Orig: %s
7507 $xyz-> %s
7508 $1-> %s\n" orig formula form))
7509 (if (listp ev)
7510 (princ (format " %s^\nError: %s"
7511 (make-string (car ev) ?\-) (nth 1 ev)))
7512 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7513 ev (or fmt "NONE")
7514 (if fmt (format fmt (string-to-number ev)) ev)))))
7515 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7516 (unless (and (interactive-p) (not ndown))
7517 (unless (let (inhibit-redisplay)
7518 (y-or-n-p "Debugging Formula. Continue to next? "))
7519 (org-table-align)
7520 (error "Abort"))
7521 (delete-window (get-buffer-window "*Help*"))
7522 (message "")))
7523 (if (listp ev) (setq fmt nil ev "#ERROR"))
7524 (org-table-justify-field-maybe
7525 (if fmt (format fmt (string-to-number ev)) ev))
7526 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7527 (call-interactively 'org-return)
7528 (setq ndown 0)))
7529 (and down (org-table-maybe-recalculate-line))
7530 (or suppress-align (and org-table-may-need-update
7531 (org-table-align)))))
7532
7533 (defun org-table-recalculate (&optional all noalign)
7534 "Recalculate the current table line by applying all stored formulas."
7535 (interactive "P")
7536 (or (memq this-command org-recalc-commands)
7537 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7538 (unless (org-at-table-p) (error "Not at a table"))
7539 (org-table-get-specials)
7540 (let* ((eqlist (sort (org-table-get-stored-formulas)
7541 (lambda (a b) (string< (car a) (car b)))))
7542 (inhibit-redisplay t)
7543 (line-re org-table-dataline-regexp)
7544 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7545 (thiscol (org-table-current-column))
7546 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7547 ;; Insert constants in all formulas
7548 (setq eqlist
7549 (mapcar (lambda (x)
7550 (setcdr x (org-table-formula-substitute-names (cdr x)))
7551 x)
7552 eqlist))
7553 ;; Split the equation list
7554 (while (setq eq (pop eqlist))
7555 (if (<= (string-to-char (car eq)) ?9)
7556 (push eq eqlnum)
7557 (push eq eqlname)))
7558 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7559 (if all
7560 (progn
7561 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7562 (goto-char (setq beg (org-table-begin)))
7563 (if (re-search-forward org-table-calculate-mark-regexp end t)
7564 ;; This is a table with marked lines, only compute selected lines
7565 (setq line-re org-table-recalculate-regexp)
7566 ;; Move forward to the first non-header line
7567 (if (and (re-search-forward org-table-dataline-regexp end t)
7568 (re-search-forward org-table-hline-regexp end t)
7569 (re-search-forward org-table-dataline-regexp end t))
7570 (setq beg (match-beginning 0))
7571 nil))) ;; just leave beg where it is
7572 (setq beg (point-at-bol)
7573 end (move-marker (make-marker) (1+ (point-at-eol)))))
7574 (goto-char beg)
7575 (and all (message "Re-applying formulas to full table..."))
7576 (while (re-search-forward line-re end t)
7577 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7578 ;; Unprotected line, recalculate
7579 (and all (message "Re-applying formulas to full table...(line %d)"
7580 (setq cnt (1+ cnt))))
7581 (setq org-last-recalc-line (org-current-line))
7582 (setq eql eqlnum)
7583 (while (setq entry (pop eql))
7584 (goto-line org-last-recalc-line)
7585 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7586 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7587 (goto-line thisline)
7588 (org-table-goto-column thiscol)
7589 (or noalign (and org-table-may-need-update (org-table-align))
7590 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7591 ;; Now do the names fields
7592 (while (setq eq (pop eqlname))
7593 (setq name (car eq)
7594 a (assoc name org-table-named-field-locations))
7595 (when a
7596 (message "Re-applying formula to named field: %s" name)
7597 (goto-line (nth 1 a))
7598 (org-table-goto-column (nth 2 a))
7599 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7600 ;; back to initial position
7601 (goto-line thisline)
7602 (org-table-goto-column thiscol)
7603 (or noalign (and org-table-may-need-update (org-table-align))
7604 (and all (message "Re-applying formulas...done")))))
7605
7606 (defun org-table-formula-substitute-names (f)
7607 "Replace $const with values in string F."
7608 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7609 ;; First, check for column names
7610 (while (setq start (string-match org-table-column-name-regexp f start))
7611 (setq start (1+ start))
7612 (setq a (assoc (match-string 1 f) org-table-column-names))
7613 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7614 ;; Expand ranges to vectors
7615 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7616 (setq n1 (string-to-number (match-string 1 f))
7617 n2 (string-to-number (match-string 2 f))
7618 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7619 s (concat "[($" (number-to-string (1- nn1)) ")"))
7620 (loop for i from nn1 upto nn2 do
7621 (setq s (concat s ",($" (int-to-string i) ")")))
7622 (setq s (concat s "]"))
7623 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7624 (setq f (replace-match s t t f)))
7625 ;; Parameters and constants
7626 (setq start 0)
7627 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7628 (setq start (1+ start))
7629 (if (setq a (save-match-data
7630 (org-table-get-constant (match-string 1 f))))
7631 (setq f (replace-match (concat "(" a ")") t t f))))
7632 (if org-table-formula-debug
7633 (put-text-property 0 (length f) :orig-formula f1 f))
7634 f))
7635
7636 (defun org-table-get-constant (const)
7637 "Find the value for a parameter or constant in a formula.
7638 Parameters get priority."
7639 (or (cdr (assoc const org-table-local-parameters))
7640 (cdr (assoc const org-table-formula-constants))
7641 (and (fboundp 'constants-get) (constants-get const))
7642 "#UNDEFINED_NAME"))
7643
7644 (defvar org-edit-formulas-map (make-sparse-keymap))
7645 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7646 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7647 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7648
7649 (defvar org-pos)
7650 (defvar org-window-configuration)
7651
7652 (defun org-table-edit-formulas ()
7653 "Edit the formulas of the current table in a separate buffer."
7654 (interactive)
7655 (unless (org-at-table-p)
7656 (error "Not at a table"))
7657 (org-table-get-specials)
7658 (let ((eql (org-table-get-stored-formulas))
7659 (pos (move-marker (make-marker) (point)))
7660 (wc (current-window-configuration))
7661 entry loc s)
7662 (switch-to-buffer-other-window "*Edit Formulas*")
7663 (erase-buffer)
7664 (fundamental-mode)
7665 (set (make-local-variable 'org-pos) pos)
7666 (set (make-local-variable 'org-window-configuration) wc)
7667 (use-local-map org-edit-formulas-map)
7668 (setq s "# Edit formulas and finish with `C-c C-c'.
7669 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7670 # Use `C-c ?' to get information about $name at point.
7671 # To cancel editing, press `C-c C-q'.\n")
7672 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7673 (insert s)
7674 (while (setq entry (pop eql))
7675 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7676 (setq s (format "# Named formula, referring to column %d in line %d\n"
7677 (nth 2 loc) (nth 1 loc)))
7678 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7679 (insert s))
7680 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7681 (remove-text-properties 0 (length s) '(face nil) s)
7682 (insert s))
7683 (goto-char (point-min))
7684 (message "Edit formulas and finish with `C-c C-c'.")))
7685
7686 (defun org-show-variable ()
7687 "Show the location/value of the $ expression at point."
7688 (interactive)
7689 (let (var (pos org-pos) (win (selected-window)) e)
7690 (save-excursion
7691 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7692 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7693 (setq var (match-string 1))
7694 (error "No variable at point")))
7695 (cond
7696 ((setq e (assoc var org-table-named-field-locations))
7697 (switch-to-buffer-other-window (marker-buffer pos))
7698 (goto-line (nth 1 e))
7699 (org-table-goto-column (nth 2 e))
7700 (select-window win)
7701 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7702 ((setq e (assoc var org-table-column-names))
7703 (switch-to-buffer-other-window (marker-buffer pos))
7704 (goto-char pos)
7705 (goto-char (org-table-begin))
7706 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7707 (org-table-end) t)
7708 (progn
7709 (goto-char (match-beginning 1))
7710 (message "Named column (column %s)" (cdr e)))
7711 (error "Column name not found"))
7712 (select-window win))
7713 ((string-match "^[0-9]$" var)
7714 ;; column number
7715 (switch-to-buffer-other-window (marker-buffer pos))
7716 (goto-char pos)
7717 (goto-char (org-table-begin))
7718 (recenter 1)
7719 (if (re-search-forward org-table-dataline-regexp
7720 (org-table-end) t)
7721 (progn
7722 (goto-char (match-beginning 0))
7723 (org-table-goto-column (string-to-number var))
7724 (message "Column %s" var))
7725 (error "Column name not found"))
7726 (select-window win))
7727 ((setq e (assoc var org-table-local-parameters))
7728 (switch-to-buffer-other-window (marker-buffer pos))
7729 (goto-char pos)
7730 (goto-char (org-table-begin))
7731 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7732 (progn
7733 (goto-char (match-beginning 1))
7734 (message "Local parameter."))
7735 (error "Parameter not found"))
7736 (select-window win))
7737 (t
7738 (cond
7739 ((setq e (assoc var org-table-formula-constants))
7740 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7741 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7742 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7743 (t (error "Undefined name $%s" var)))))))
7744
7745 (defun org-finish-edit-formulas (&optional arg)
7746 "Parse the buffer for formula definitions and install them.
7747 With prefix ARG, apply the new formulas to the table."
7748 (interactive "P")
7749 (let ((pos org-pos) eql)
7750 (goto-char (point-min))
7751 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7752 (push (cons (match-string 1) (match-string 2)) eql))
7753 (set-window-configuration org-window-configuration)
7754 (select-window (get-buffer-window (marker-buffer pos)))
7755 (goto-char pos)
7756 (unless (org-at-table-p)
7757 (error "Lost table position - cannot install formulae"))
7758 (org-table-store-formulas eql)
7759 (move-marker pos nil)
7760 (kill-buffer "*Edit Formulas*")
7761 (if arg
7762 (org-table-recalculate 'all)
7763 (message "New formulas installed - press C-u C-c C-c to apply."))))
7764
7765 (defun org-abort-edit-formulas ()
7766 "Abort editing formulas, without installing the changes."
7767 (interactive)
7768 (let ((pos org-pos))
7769 (set-window-configuration org-window-configuration)
7770 (select-window (get-buffer-window (marker-buffer pos)))
7771 (goto-char pos)
7772 (message "Formula editing aborted without installing changes")))
7773
7774 ;;; The orgtbl minor mode
7775
7776 ;; Define a minor mode which can be used in other modes in order to
7777 ;; integrate the org-mode table editor.
7778
7779 ;; This is really a hack, because the org-mode table editor uses several
7780 ;; keys which normally belong to the major mode, for example the TAB and
7781 ;; RET keys. Here is how it works: The minor mode defines all the keys
7782 ;; necessary to operate the table editor, but wraps the commands into a
7783 ;; function which tests if the cursor is currently inside a table. If that
7784 ;; is the case, the table editor command is executed. However, when any of
7785 ;; those keys is used outside a table, the function uses `key-binding' to
7786 ;; look up if the key has an associated command in another currently active
7787 ;; keymap (minor modes, major mode, global), and executes that command.
7788 ;; There might be problems if any of the keys used by the table editor is
7789 ;; otherwise used as a prefix key.
7790
7791 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7792 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7793 ;; addresses this by checking explicitly for both bindings.
7794
7795 ;; The optimized version (see variable `orgtbl-optimized') takes over
7796 ;; all keys which are bound to `self-insert-command' in the *global map*.
7797 ;; Some modes bind other commands to simple characters, for example
7798 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7799 ;; active, this binding is ignored inside tables and replaced with a
7800 ;; modified self-insert.
7801
7802 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7803 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7804 In the optimized version, the table editor takes over all simple keys that
7805 normally just insert a character. In tables, the characters are inserted
7806 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7807 for empty fields). Outside tables, the correct binding of the keys is
7808 restored.
7809
7810 The default for this option is t if the optimized version is also used in
7811 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7812 this variable requires a restart of Emacs to become effective."
7813 :group 'org-table
7814 :type 'boolean)
7815
7816 (defvar orgtbl-mode nil
7817 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7818 table editor in arbitrary modes.")
7819 (make-variable-buffer-local 'orgtbl-mode)
7820
7821 (defvar orgtbl-mode-map (make-sparse-keymap)
7822 "Keymap for `orgtbl-mode'.")
7823
7824 ;;;###autoload
7825 (defun turn-on-orgtbl ()
7826 "Unconditionally turn on `orgtbl-mode'."
7827 (orgtbl-mode 1))
7828
7829 ;;;###autoload
7830 (defun orgtbl-mode (&optional arg)
7831 "The `org-mode' table editor as a minor mode for use in other modes."
7832 (interactive)
7833 (if (eq major-mode 'org-mode)
7834 ;; Exit without error, in case some hook functions calls this
7835 ;; by accident in org-mode.
7836 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7837 (setq orgtbl-mode
7838 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7839 (if orgtbl-mode
7840 (progn
7841 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7842 ;; Make sure we are first in minor-mode-map-alist
7843 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7844 (and c (setq minor-mode-map-alist
7845 (cons c (delq c minor-mode-map-alist)))))
7846 (set (make-local-variable (quote org-table-may-need-update)) t)
7847 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
7848 (add-hook 'before-change-functions 'org-before-change-function
7849 nil 'local)
7850 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7851 auto-fill-inhibit-regexp)
7852 (set (make-local-variable 'auto-fill-inhibit-regexp)
7853 (if auto-fill-inhibit-regexp
7854 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7855 "[ \t]*|"))
7856 (easy-menu-add orgtbl-mode-menu)
7857 (run-hooks 'orgtbl-mode-hook))
7858 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7859 (remove-hook 'before-change-functions 'org-before-change-function t)
7860 (easy-menu-remove orgtbl-mode-menu)
7861 (force-mode-line-update 'all))))
7862
7863 ;; Install it as a minor mode.
7864 (put 'orgtbl-mode :included t)
7865 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7866 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7867
7868 (defun orgtbl-make-binding (fun n &rest keys)
7869 "Create a function for binding in the table minor mode.
7870 FUN is the command to call inside a table. N is used to create a unique
7871 command name. KEYS are keys that should be checked in for a command
7872 to execute outside of tables."
7873 (eval
7874 (list 'defun
7875 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7876 '(arg)
7877 (concat "In tables, run `" (symbol-name fun) "'.\n"
7878 "Outside of tables, run the binding of `"
7879 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7880 "'.")
7881 '(interactive "p")
7882 (list 'if
7883 '(org-at-table-p)
7884 (list 'call-interactively (list 'quote fun))
7885 (list 'let '(orgtbl-mode)
7886 (list 'call-interactively
7887 (append '(or)
7888 (mapcar (lambda (k)
7889 (list 'key-binding k))
7890 keys)
7891 '('orgtbl-error))))))))
7892
7893 (defun orgtbl-error ()
7894 "Error when there is no default binding for a table key."
7895 (interactive)
7896 (error "This key is has no function outside tables"))
7897
7898 (defun orgtbl-setup ()
7899 "Setup orgtbl keymaps."
7900 (let ((nfunc 0)
7901 (bindings
7902 (list
7903 '([(meta shift left)] org-table-delete-column)
7904 '([(meta left)] org-table-move-column-left)
7905 '([(meta right)] org-table-move-column-right)
7906 '([(meta shift right)] org-table-insert-column)
7907 '([(meta shift up)] org-table-kill-row)
7908 '([(meta shift down)] org-table-insert-row)
7909 '([(meta up)] org-table-move-row-up)
7910 '([(meta down)] org-table-move-row-down)
7911 '("\C-c\C-w" org-table-cut-region)
7912 '("\C-c\M-w" org-table-copy-region)
7913 '("\C-c\C-y" org-table-paste-rectangle)
7914 '("\C-c-" org-table-insert-hline)
7915 '([(shift tab)] org-table-previous-field)
7916 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7917 '("\C-m" org-table-next-row)
7918 (list (org-key 'S-return) 'org-table-copy-down)
7919 '([(meta return)] org-table-wrap-region)
7920 '("\C-c\C-q" org-table-wrap-region)
7921 '("\C-c?" org-table-current-column)
7922 '("\C-c " org-table-blank-field)
7923 '("\C-c+" org-table-sum)
7924 '("\C-c|" org-table-toggle-vline-visibility)
7925 '("\C-c=" org-table-eval-formula)
7926 '("\C-c'" org-table-edit-formulas)
7927 '("\C-c*" org-table-recalculate)
7928 '([(control ?#)] org-table-rotate-recalc-marks)))
7929 elt key fun cmd)
7930 (while (setq elt (pop bindings))
7931 (setq nfunc (1+ nfunc))
7932 (setq key (car elt)
7933 fun (nth 1 elt)
7934 cmd (orgtbl-make-binding fun nfunc key))
7935 (define-key orgtbl-mode-map key cmd))
7936 ;; Special treatment needed for TAB and RET
7937 (define-key orgtbl-mode-map [(return)]
7938 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7939 (define-key orgtbl-mode-map "\C-m"
7940 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7941 (define-key orgtbl-mode-map [(tab)]
7942 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7943 (define-key orgtbl-mode-map "\C-i"
7944 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7945 (when orgtbl-optimized
7946 ;; If the user wants maximum table support, we need to hijack
7947 ;; some standard editing functions
7948 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7949 orgtbl-mode-map global-map)
7950 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7951 orgtbl-mode-map global-map)
7952 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7953 orgtbl-mode-map global-map)
7954 (define-key org-mode-map "|" 'self-insert-command))
7955 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7956 '("OrgTbl"
7957 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7958 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7959 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7960 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7961 "--"
7962 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7963 ["Copy Field from Above"
7964 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7965 "--"
7966 ("Column"
7967 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7968 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7969 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7970 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7971 ("Row"
7972 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7973 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7974 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7975 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7976 "--"
7977 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7978 ("Rectangle"
7979 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7980 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7981 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7982 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7983 "--"
7984 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7985 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7986 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
7987 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7988 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7989 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7990 ["Sum Column/Rectangle" org-table-sum
7991 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7992 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7993 ["Debug Formulas"
7994 (setq org-table-formula-debug (not org-table-formula-debug))
7995 :style toggle :selected org-table-formula-debug]
7996 ))
7997 t)
7998
7999 (defun orgtbl-tab ()
8000 "Justification and field motion for `orgtbl-mode'."
8001 (interactive)
8002 (org-table-justify-field-maybe)
8003 (org-table-next-field))
8004
8005 (defun orgtbl-ret ()
8006 "Justification and field motion for `orgtbl-mode'."
8007 (interactive)
8008 (org-table-justify-field-maybe)
8009 (org-table-next-row))
8010
8011 (defun orgtbl-self-insert-command (N)
8012 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8013 If the cursor is in a table looking at whitespace, the whitespace is
8014 overwritten, and the table is not marked as requiring realignment."
8015 (interactive "p")
8016 (if (and (org-at-table-p)
8017 (eq N 1)
8018 (looking-at "[^|\n]* +|"))
8019 (let (org-table-may-need-update)
8020 (goto-char (1- (match-end 0)))
8021 (delete-backward-char 1)
8022 (goto-char (match-beginning 0))
8023 (self-insert-command N))
8024 (setq org-table-may-need-update t)
8025 (let (orgtbl-mode)
8026 (call-interactively (key-binding (vector last-input-event))))))
8027
8028 (defun orgtbl-delete-backward-char (N)
8029 "Like `delete-backward-char', insert whitespace at field end in tables.
8030 When deleting backwards, in tables this function will insert whitespace in
8031 front of the next \"|\" separator, to keep the table aligned. The table will
8032 still be marked for re-alignment, because a narrow field may lead to a
8033 reduced column width."
8034 (interactive "p")
8035 (if (and (org-at-table-p)
8036 (eq N 1)
8037 (string-match "|" (buffer-substring (point-at-bol) (point)))
8038 (looking-at ".*?|"))
8039 (let ((pos (point)))
8040 (backward-delete-char N)
8041 (skip-chars-forward "^|")
8042 (insert " ")
8043 (goto-char (1- pos)))
8044 (delete-backward-char N)))
8045
8046 (defun orgtbl-delete-char (N)
8047 "Like `delete-char', but insert whitespace at field end in tables.
8048 When deleting characters, in tables this function will insert whitespace in
8049 front of the next \"|\" separator, to keep the table aligned. The table
8050 will still be marked for re-alignment, because a narrow field may lead to
8051 a reduced column width."
8052 (interactive "p")
8053 (if (and (org-at-table-p)
8054 (not (bolp))
8055 (not (= (char-after) ?|))
8056 (eq N 1))
8057 (if (looking-at ".*?|")
8058 (let ((pos (point)))
8059 (replace-match (concat
8060 (substring (match-string 0) 1 -1)
8061 " |"))
8062 (goto-char pos)))
8063 (delete-char N)))
8064
8065 ;;; Exporting
8066
8067 (defconst org-level-max 20)
8068
8069 (defun org-export-find-first-heading-line (list)
8070 "Remove all lines from LIST which are before the first headline."
8071 (let ((orig-list list)
8072 (re (concat "^" outline-regexp)))
8073 (while (and list
8074 (not (string-match re (car list))))
8075 (pop list))
8076 (or list orig-list)))
8077
8078 (defun org-skip-comments (lines)
8079 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8080 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8081 (re2 "^\\(\\*+\\)[ \t\n\r]")
8082 rtn line level)
8083 (while (setq line (pop lines))
8084 (cond
8085 ((and (string-match re1 line)
8086 (setq level (- (match-end 1) (match-beginning 1))))
8087 ;; Beginning of a COMMENT subtree. Skip it.
8088 (while (and (setq line (pop lines))
8089 (or (not (string-match re2 line))
8090 (> (- (match-end 1) (match-beginning 1)) level))))
8091 (setq lines (cons line lines)))
8092 ((string-match "^#" line)
8093 ;; an ordinary comment line
8094 )
8095 (t (setq rtn (cons line rtn)))))
8096 (nreverse rtn)))
8097
8098 ;; ASCII
8099
8100 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8101 "Characters for underlining headings in ASCII export.")
8102
8103 (defconst org-html-entities
8104 '(("nbsp")
8105 ("iexcl")
8106 ("cent")
8107 ("pound")
8108 ("curren")
8109 ("yen")
8110 ("brvbar")
8111 ("sect")
8112 ("uml")
8113 ("copy")
8114 ("ordf")
8115 ("laquo")
8116 ("not")
8117 ("shy")
8118 ("reg")
8119 ("macr")
8120 ("deg")
8121 ("plusmn")
8122 ("sup2")
8123 ("sup3")
8124 ("acute")
8125 ("micro")
8126 ("para")
8127 ("middot")
8128 ("odot"."o")
8129 ("star"."*")
8130 ("cedil")
8131 ("sup1")
8132 ("ordm")
8133 ("raquo")
8134 ("frac14")
8135 ("frac12")
8136 ("frac34")
8137 ("iquest")
8138 ("Agrave")
8139 ("Aacute")
8140 ("Acirc")
8141 ("Atilde")
8142 ("Auml")
8143 ("Aring") ("AA"."&Aring;")
8144 ("AElig")
8145 ("Ccedil")
8146 ("Egrave")
8147 ("Eacute")
8148 ("Ecirc")
8149 ("Euml")
8150 ("Igrave")
8151 ("Iacute")
8152 ("Icirc")
8153 ("Iuml")
8154 ("ETH")
8155 ("Ntilde")
8156 ("Ograve")
8157 ("Oacute")
8158 ("Ocirc")
8159 ("Otilde")
8160 ("Ouml")
8161 ("times")
8162 ("Oslash")
8163 ("Ugrave")
8164 ("Uacute")
8165 ("Ucirc")
8166 ("Uuml")
8167 ("Yacute")
8168 ("THORN")
8169 ("szlig")
8170 ("agrave")
8171 ("aacute")
8172 ("acirc")
8173 ("atilde")
8174 ("auml")
8175 ("aring")
8176 ("aelig")
8177 ("ccedil")
8178 ("egrave")
8179 ("eacute")
8180 ("ecirc")
8181 ("euml")
8182 ("igrave")
8183 ("iacute")
8184 ("icirc")
8185 ("iuml")
8186 ("eth")
8187 ("ntilde")
8188 ("ograve")
8189 ("oacute")
8190 ("ocirc")
8191 ("otilde")
8192 ("ouml")
8193 ("divide")
8194 ("oslash")
8195 ("ugrave")
8196 ("uacute")
8197 ("ucirc")
8198 ("uuml")
8199 ("yacute")
8200 ("thorn")
8201 ("yuml")
8202 ("fnof")
8203 ("Alpha")
8204 ("Beta")
8205 ("Gamma")
8206 ("Delta")
8207 ("Epsilon")
8208 ("Zeta")
8209 ("Eta")
8210 ("Theta")
8211 ("Iota")
8212 ("Kappa")
8213 ("Lambda")
8214 ("Mu")
8215 ("Nu")
8216 ("Xi")
8217 ("Omicron")
8218 ("Pi")
8219 ("Rho")
8220 ("Sigma")
8221 ("Tau")
8222 ("Upsilon")
8223 ("Phi")
8224 ("Chi")
8225 ("Psi")
8226 ("Omega")
8227 ("alpha")
8228 ("beta")
8229 ("gamma")
8230 ("delta")
8231 ("epsilon")
8232 ("varepsilon"."&epsilon;")
8233 ("zeta")
8234 ("eta")
8235 ("theta")
8236 ("iota")
8237 ("kappa")
8238 ("lambda")
8239 ("mu")
8240 ("nu")
8241 ("xi")
8242 ("omicron")
8243 ("pi")
8244 ("rho")
8245 ("sigmaf") ("varsigma"."&sigmaf;")
8246 ("sigma")
8247 ("tau")
8248 ("upsilon")
8249 ("phi")
8250 ("chi")
8251 ("psi")
8252 ("omega")
8253 ("thetasym") ("vartheta"."&thetasym;")
8254 ("upsih")
8255 ("piv")
8256 ("bull") ("bullet"."&bull;")
8257 ("hellip") ("dots"."&hellip;")
8258 ("prime")
8259 ("Prime")
8260 ("oline")
8261 ("frasl")
8262 ("weierp")
8263 ("image")
8264 ("real")
8265 ("trade")
8266 ("alefsym")
8267 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8268 ("uarr") ("uparrow"."&uarr;")
8269 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8270 ("darr")("downarrow"."&darr;")
8271 ("harr") ("leftrightarrow"."&harr;")
8272 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8273 ("lArr") ("Leftarrow"."&lArr;")
8274 ("uArr") ("Uparrow"."&uArr;")
8275 ("rArr") ("Rightarrow"."&rArr;")
8276 ("dArr") ("Downarrow"."&dArr;")
8277 ("hArr") ("Leftrightarrow"."&hArr;")
8278 ("forall")
8279 ("part") ("partial"."&part;")
8280 ("exist") ("exists"."&exist;")
8281 ("empty") ("emptyset"."&empty;")
8282 ("nabla")
8283 ("isin") ("in"."&isin;")
8284 ("notin")
8285 ("ni")
8286 ("prod")
8287 ("sum")
8288 ("minus")
8289 ("lowast") ("ast"."&lowast;")
8290 ("radic")
8291 ("prop") ("proptp"."&prop;")
8292 ("infin") ("infty"."&infin;")
8293 ("ang") ("angle"."&ang;")
8294 ("and") ("vee"."&and;")
8295 ("or") ("wedge"."&or;")
8296 ("cap")
8297 ("cup")
8298 ("int")
8299 ("there4")
8300 ("sim")
8301 ("cong") ("simeq"."&cong;")
8302 ("asymp")("approx"."&asymp;")
8303 ("ne") ("neq"."&ne;")
8304 ("equiv")
8305 ("le")
8306 ("ge")
8307 ("sub") ("subset"."&sub;")
8308 ("sup") ("supset"."&sup;")
8309 ("nsub")
8310 ("sube")
8311 ("supe")
8312 ("oplus")
8313 ("otimes")
8314 ("perp")
8315 ("sdot") ("cdot"."&sdot;")
8316 ("lceil")
8317 ("rceil")
8318 ("lfloor")
8319 ("rfloor")
8320 ("lang")
8321 ("rang")
8322 ("loz") ("Diamond"."&loz;")
8323 ("spades") ("spadesuit"."&spades;")
8324 ("clubs") ("clubsuit"."&clubs;")
8325 ("hearts") ("diamondsuit"."&hearts;")
8326 ("diams") ("diamondsuit"."&diams;")
8327 ("quot")
8328 ("amp")
8329 ("lt")
8330 ("gt")
8331 ("OElig")
8332 ("oelig")
8333 ("Scaron")
8334 ("scaron")
8335 ("Yuml")
8336 ("circ")
8337 ("tilde")
8338 ("ensp")
8339 ("emsp")
8340 ("thinsp")
8341 ("zwnj")
8342 ("zwj")
8343 ("lrm")
8344 ("rlm")
8345 ("ndash")
8346 ("mdash")
8347 ("lsquo")
8348 ("rsquo")
8349 ("sbquo")
8350 ("ldquo")
8351 ("rdquo")
8352 ("bdquo")
8353 ("dagger")
8354 ("Dagger")
8355 ("permil")
8356 ("lsaquo")
8357 ("rsaquo")
8358 ("euro")
8359
8360 ("arccos"."arccos")
8361 ("arcsin"."arcsin")
8362 ("arctan"."arctan")
8363 ("arg"."arg")
8364 ("cos"."cos")
8365 ("cosh"."cosh")
8366 ("cot"."cot")
8367 ("coth"."coth")
8368 ("csc"."csc")
8369 ("deg"."deg")
8370 ("det"."det")
8371 ("dim"."dim")
8372 ("exp"."exp")
8373 ("gcd"."gcd")
8374 ("hom"."hom")
8375 ("inf"."inf")
8376 ("ker"."ker")
8377 ("lg"."lg")
8378 ("lim"."lim")
8379 ("liminf"."liminf")
8380 ("limsup"."limsup")
8381 ("ln"."ln")
8382 ("log"."log")
8383 ("max"."max")
8384 ("min"."min")
8385 ("Pr"."Pr")
8386 ("sec"."sec")
8387 ("sin"."sin")
8388 ("sinh"."sinh")
8389 ("sup"."sup")
8390 ("tan"."tan")
8391 ("tanh"."tanh")
8392 )
8393 "Entities for TeX->HTML translation.
8394 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8395 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8396 In that case, \"\\ent\" will be translated to \"&other;\".
8397 The list contains HTML entities for Latin-1, Greek and other symbols.
8398 It is supplemented by a number of commonly used TeX macros with appropriate
8399 translations. There is currently no way for users to extend this.")
8400
8401 (defvar org-last-level nil) ; dynamically scoped variable
8402
8403 (defun org-export-as-ascii (arg)
8404 "Export the outline as a pretty ASCII file.
8405 If there is an active region, export only the region.
8406 The prefix ARG specifies how many levels of the outline should become
8407 underlined headlines. The default is 3."
8408 (interactive "P")
8409 (setq-default org-todo-line-regexp org-todo-line-regexp)
8410 (let* ((region
8411 (buffer-substring
8412 (if (org-region-active-p) (region-beginning) (point-min))
8413 (if (org-region-active-p) (region-end) (point-max))))
8414 (lines (org-export-find-first-heading-line
8415 (org-skip-comments (org-split-string region "[\r\n]"))))
8416 (org-startup-with-deadline-check nil)
8417 (level 0) line txt
8418 (umax nil)
8419 (case-fold-search nil)
8420 (filename (concat (file-name-sans-extension (buffer-file-name))
8421 ".txt"))
8422 (buffer (find-file-noselect filename))
8423 (levels-open (make-vector org-level-max nil))
8424 (date (format-time-string "%Y/%m/%d" (current-time)))
8425 (time (format-time-string "%X" (current-time)))
8426 (author user-full-name)
8427 (title (buffer-name))
8428 (options nil)
8429 (email user-mail-address)
8430 (language org-export-default-language)
8431 (text nil)
8432 (todo nil)
8433 (lang-words nil))
8434
8435 (setq org-last-level 1)
8436 (org-init-section-numbers)
8437
8438 (find-file-noselect filename)
8439
8440 ;; Search for the export key lines
8441 (org-parse-key-lines)
8442
8443 (setq lang-words (or (assoc language org-export-language-setup)
8444 (assoc "en" org-export-language-setup)))
8445 (if org-export-ascii-show-new-buffer
8446 (switch-to-buffer-other-window buffer)
8447 (set-buffer buffer))
8448 (erase-buffer)
8449 (fundamental-mode)
8450 (if options (org-parse-export-options options))
8451 (setq umax (if arg (prefix-numeric-value arg)
8452 org-export-headline-levels))
8453
8454 ;; File header
8455 (if title (org-insert-centered title ?=))
8456 (insert "\n")
8457 (if (or author email)
8458 (insert (concat (nth 1 lang-words) ": " (or author "")
8459 (if email (concat " <" email ">") "")
8460 "\n")))
8461 (if (and date time)
8462 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8463 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8464
8465 (insert "\n\n")
8466
8467 (if org-export-with-toc
8468 (progn
8469 (insert (nth 3 lang-words) "\n"
8470 (make-string (length (nth 3 lang-words)) ?=) "\n")
8471 (mapcar '(lambda (line)
8472 (if (string-match org-todo-line-regexp
8473 line)
8474 ;; This is a headline
8475 (progn
8476 (setq level (- (match-end 1) (match-beginning 1))
8477 txt (match-string 3 line)
8478 todo
8479 (or (and (match-beginning 2)
8480 (not (equal (match-string 2 line)
8481 org-done-string)))
8482 ; TODO, not DONE
8483 (and (= level umax)
8484 (org-search-todo-below
8485 line lines level))))
8486 (setq txt (org-html-expand-for-ascii txt))
8487
8488 (if org-export-with-section-numbers
8489 (setq txt (concat (org-section-number level)
8490 " " txt)))
8491 (if (<= level umax)
8492 (progn
8493 (insert
8494 (make-string (* (1- level) 4) ?\ )
8495 (format (if todo "%s (*)\n" "%s\n") txt))
8496 (setq org-last-level level))
8497 ))))
8498 lines)))
8499
8500 (org-init-section-numbers)
8501 (while (setq line (pop lines))
8502 ;; Remove the quoted HTML tags.
8503 (setq line (org-html-expand-for-ascii line))
8504 (cond
8505 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8506 ;; a Headline
8507 (setq level (- (match-end 1) (match-beginning 1))
8508 txt (match-string 2 line))
8509 (org-ascii-level-start level txt umax))
8510 (t (insert line "\n"))))
8511 (normal-mode)
8512 (save-buffer)
8513 (goto-char (point-min))))
8514
8515 (defun org-search-todo-below (line lines level)
8516 "Search the subtree below LINE for any TODO entries."
8517 (let ((rest (cdr (memq line lines)))
8518 (re org-todo-line-regexp)
8519 line lv todo)
8520 (catch 'exit
8521 (while (setq line (pop rest))
8522 (if (string-match re line)
8523 (progn
8524 (setq lv (- (match-end 1) (match-beginning 1))
8525 todo (and (match-beginning 2)
8526 (not (equal (match-string 2 line)
8527 org-done-string))))
8528 ; TODO, not DONE
8529 (if (<= lv level) (throw 'exit nil))
8530 (if todo (throw 'exit t))))))))
8531
8532 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8533 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8534 (defun org-html-expand-for-ascii (line)
8535 "Handle quoted HTML for ASCII export."
8536 (if org-export-html-expand
8537 (while (string-match "@<[^<>\n]*>" line)
8538 ;; We just remove the tags for now.
8539 (setq line (replace-match "" nil nil line))))
8540 line)
8541
8542 (defun org-insert-centered (s &optional underline)
8543 "Insert the string S centered and underline it with character UNDERLINE."
8544 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8545 (insert (make-string ind ?\ ) s "\n")
8546 (if underline
8547 (insert (make-string ind ?\ )
8548 (make-string (length s) underline)
8549 "\n"))))
8550
8551 (defun org-ascii-level-start (level title umax)
8552 "Insert a new level in ASCII export."
8553 (let (char)
8554 (if (> level umax)
8555 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8556 (if (or (not (equal (char-before) ?\n))
8557 (not (equal (char-before (1- (point))) ?\n)))
8558 (insert "\n"))
8559 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8560 (if org-export-with-section-numbers
8561 (setq title (concat (org-section-number level) " " title)))
8562 (insert title "\n" (make-string (string-width title) char) "\n"))))
8563
8564 (defun org-export-copy-visible ()
8565 "Copy the visible part of the buffer to another buffer, for printing.
8566 Also removes the first line of the buffer if it specifies a mode,
8567 and all options lines."
8568 (interactive)
8569 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8570 ".txt"))
8571 (buffer (find-file-noselect filename))
8572 (ore (concat
8573 (org-make-options-regexp
8574 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8575 "STARTUP" "ARCHIVE"
8576 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8577 (if org-noutline-p "\\(\n\\|$\\)" "")))
8578 s e)
8579 (with-current-buffer buffer
8580 (erase-buffer)
8581 (text-mode))
8582 (save-excursion
8583 (setq s (goto-char (point-min)))
8584 (while (not (= (point) (point-max)))
8585 (goto-char (org-find-invisible))
8586 (append-to-buffer buffer s (point))
8587 (setq s (goto-char (org-find-visible)))))
8588 (switch-to-buffer-other-window buffer)
8589 (newline)
8590 (goto-char (point-min))
8591 (if (looking-at ".*-\\*- mode:.*\n")
8592 (replace-match ""))
8593 (while (re-search-forward ore nil t)
8594 (replace-match ""))
8595 (goto-char (point-min))))
8596
8597 (defun org-find-visible ()
8598 (if (featurep 'noutline)
8599 (let ((s (point)))
8600 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8601 (get-char-property s 'invisible)))
8602 s)
8603 (skip-chars-forward "^\n")
8604 (point)))
8605 (defun org-find-invisible ()
8606 (if (featurep 'noutline)
8607 (let ((s (point)))
8608 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8609 (not (get-char-property s 'invisible))))
8610 s)
8611 (skip-chars-forward "^\r")
8612 (point)))
8613
8614 ;; HTML
8615
8616 (defun org-get-current-options ()
8617 "Return a string with current options as keyword options.
8618 Does include HTML export options as well as TODO and CATEGORY stuff."
8619 (format
8620 "#+TITLE: %s
8621 #+AUTHOR: %s
8622 #+EMAIL: %s
8623 #+LANGUAGE: %s
8624 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8625 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8626 #+CATEGORY: %s
8627 #+SEQ_TODO: %s
8628 #+TYP_TODO: %s
8629 #+STARTUP: %s %s
8630 #+ARCHIVE: %s
8631 "
8632 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8633 org-export-headline-levels
8634 org-export-with-section-numbers
8635 org-export-with-toc
8636 org-export-preserve-breaks
8637 org-export-html-expand
8638 org-export-with-fixed-width
8639 org-export-with-tables
8640 org-export-with-sub-superscripts
8641 org-export-with-emphasize
8642 org-export-with-TeX-macros
8643 (file-name-nondirectory (buffer-file-name))
8644 (if (equal org-todo-interpretation 'sequence)
8645 (mapconcat 'identity org-todo-keywords " ")
8646 "TODO FEEDBACK VERIFY DONE")
8647 (if (equal org-todo-interpretation 'type)
8648 (mapconcat 'identity org-todo-keywords " ")
8649 "Me Jason Marie DONE")
8650 (cdr (assoc org-startup-folded
8651 '((nil . "nofold")(t . "fold")(content . "content"))))
8652 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8653 org-archive-location
8654 ))
8655
8656 (defun org-insert-export-options-template ()
8657 "Insert into the buffer a template with information for exporting."
8658 (interactive)
8659 (if (not (bolp)) (newline))
8660 (let ((s (org-get-current-options)))
8661 (and (string-match "#\\+CATEGORY" s)
8662 (setq s (substring s 0 (match-beginning 0))))
8663 (insert s)))
8664
8665 (defun org-toggle-fixed-width-section (arg)
8666 "Toggle the fixed-width export.
8667 If there is no active region, the QUOTE keyword at the current headline is
8668 inserted or removed. When present, it causes the text between this headline
8669 and the next to be exported as fixed-width text, and unmodified.
8670 If there is an active region, this command adds or removes a colon as the
8671 first character of this line. If the first character of a line is a colon,
8672 this line is also exported in fixed-width font."
8673 (interactive "P")
8674 (let* ((cc 0)
8675 (regionp (org-region-active-p))
8676 (beg (if regionp (region-beginning) (point)))
8677 (end (if regionp (region-end)))
8678 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8679 (re "[ \t]*\\(:\\)")
8680 off)
8681 (if regionp
8682 (save-excursion
8683 (goto-char beg)
8684 (setq cc (current-column))
8685 (beginning-of-line 1)
8686 (setq off (looking-at re))
8687 (while (> nlines 0)
8688 (setq nlines (1- nlines))
8689 (beginning-of-line 1)
8690 (cond
8691 (arg
8692 (move-to-column cc t)
8693 (insert ":\n")
8694 (forward-line -1))
8695 ((and off (looking-at re))
8696 (replace-match "" t t nil 1))
8697 ((not off) (move-to-column cc t) (insert ":")))
8698 (forward-line 1)))
8699 (save-excursion
8700 (org-back-to-heading)
8701 (if (looking-at (concat outline-regexp
8702 "\\( +\\<" org-quote-string "\\>\\)"))
8703 (replace-match "" t t nil 1)
8704 (if (looking-at outline-regexp)
8705 (progn
8706 (goto-char (match-end 0))
8707 (insert " " org-quote-string))))))))
8708
8709 (defun org-export-as-html-and-open (arg)
8710 "Export the outline as HTML and immediately open it with a browser.
8711 If there is an active region, export only the region.
8712 The prefix ARG specifies how many levels of the outline should become
8713 headlines. The default is 3. Lower levels will become bulleted lists."
8714 (interactive "P")
8715 (org-export-as-html arg 'hidden)
8716 (org-open-file (buffer-file-name)))
8717
8718 (defun org-export-as-html-batch ()
8719 "Call `org-export-as-html', may be used in batch processing as
8720 emacs --batch
8721 --load=$HOME/lib/emacs/org.el
8722 --eval \"(setq org-export-headline-levels 2)\"
8723 --visit=MyFile --funcall org-export-as-html-batch"
8724 (org-export-as-html org-export-headline-levels 'hidden))
8725
8726 (defun org-export-as-html (arg &optional hidden)
8727 "Export the outline as a pretty HTML file.
8728 If there is an active region, export only the region.
8729 The prefix ARG specifies how many levels of the outline should become
8730 headlines. The default is 3. Lower levels will become bulleted lists."
8731 (interactive "P")
8732 (setq-default org-todo-line-regexp org-todo-line-regexp)
8733 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8734 (setq-default org-done-string org-done-string)
8735 (let* ((region-p (org-region-active-p))
8736 (region
8737 (buffer-substring
8738 (if region-p (region-beginning) (point-min))
8739 (if region-p (region-end) (point-max))))
8740 (all_lines
8741 (org-skip-comments (org-split-string region "[\r\n]")))
8742 (lines (org-export-find-first-heading-line all_lines))
8743 (level 0) (line "") (origline "") txt todo
8744 (umax nil)
8745 (filename (concat (file-name-sans-extension (buffer-file-name))
8746 ".html"))
8747 (buffer (find-file-noselect filename))
8748 (levels-open (make-vector org-level-max nil))
8749 (date (format-time-string "%Y/%m/%d" (current-time)))
8750 (time (format-time-string "%X" (current-time)))
8751 (author user-full-name)
8752 (title (buffer-name))
8753 (options nil)
8754 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
8755 (inquote nil)
8756 (email user-mail-address)
8757 (language org-export-default-language)
8758 (text nil)
8759 (lang-words nil)
8760 (head-count 0) cnt
8761 (start 0)
8762 table-open type
8763 table-buffer table-orig-buffer
8764 )
8765 (message "Exporting...")
8766
8767 (setq org-last-level 1)
8768 (org-init-section-numbers)
8769
8770 ;; Search for the export key lines
8771 (org-parse-key-lines)
8772 (setq lang-words (or (assoc language org-export-language-setup)
8773 (assoc "en" org-export-language-setup)))
8774
8775 ;; Switch to the output buffer
8776 (if (or hidden (not org-export-html-show-new-buffer))
8777 (set-buffer buffer)
8778 (switch-to-buffer-other-window buffer))
8779 (erase-buffer)
8780 (fundamental-mode)
8781 (let ((case-fold-search nil))
8782 (if options (org-parse-export-options options))
8783 (setq umax (if arg (prefix-numeric-value arg)
8784 org-export-headline-levels))
8785
8786 ;; File header
8787 (insert (format
8788 "<html lang=\"%s\"><head>
8789 <title>%s</title>
8790 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8791 <meta name=generator content=\"Org-mode\">
8792 <meta name=generated content=\"%s %s\">
8793 <meta name=author content=\"%s\">
8794 </head><body>
8795 "
8796 language (org-html-expand title) date time author))
8797 (if title (insert (concat "<H1 align=\"center\">"
8798 (org-html-expand title) "</H1>\n")))
8799 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8800 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8801 email "&gt;</a>\n")))
8802 (if (or author email) (insert "<br>\n"))
8803 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8804 date " " time "<br>\n")))
8805 (if text (insert (concat "<p>\n" (org-html-expand text))))
8806 (if org-export-with-toc
8807 (progn
8808 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8809 (insert "<ul>\n")
8810 (mapcar '(lambda (line)
8811 (if (string-match org-todo-line-regexp line)
8812 ;; This is a headline
8813 (progn
8814 (setq level (- (match-end 1) (match-beginning 1))
8815 txt (save-match-data
8816 (org-html-expand
8817 (match-string 3 line)))
8818 todo
8819 (or (and (match-beginning 2)
8820 (not (equal (match-string 2 line)
8821 org-done-string)))
8822 ; TODO, not DONE
8823 (and (= level umax)
8824 (org-search-todo-below
8825 line lines level))))
8826 (if org-export-with-section-numbers
8827 (setq txt (concat (org-section-number level)
8828 " " txt)))
8829 (if (<= level umax)
8830 (progn
8831 (setq head-count (+ head-count 1))
8832 (if (> level org-last-level)
8833 (progn
8834 (setq cnt (- level org-last-level))
8835 (while (>= (setq cnt (1- cnt)) 0)
8836 (insert "<ul>"))
8837 (insert "\n")))
8838 (if (< level org-last-level)
8839 (progn
8840 (setq cnt (- org-last-level level))
8841 (while (>= (setq cnt (1- cnt)) 0)
8842 (insert "</ul>"))
8843 (insert "\n")))
8844 (insert
8845 (format
8846 (if todo
8847 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8848 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8849 head-count txt))
8850 (setq org-last-level level))
8851 ))))
8852 lines)
8853 (while (> org-last-level 0)
8854 (setq org-last-level (1- org-last-level))
8855 (insert "</ul>\n"))
8856 ))
8857 (setq head-count 0)
8858 (org-init-section-numbers)
8859
8860 (while (setq line (pop lines) origline line)
8861 ;; end of quote?
8862 (when (and inquote (string-match "^\\*+" line))
8863 (insert "</pre>\n")
8864 (setq inquote nil))
8865 ;; inquote
8866 (if inquote
8867 (progn
8868 (insert line "\n")
8869 (setq line (org-html-expand line))) ;;????? FIXME: not needed?
8870
8871 ;; Protect the links
8872 (setq start 0)
8873 (while (string-match org-link-maybe-angles-regexp line start)
8874 (setq start (match-end 0))
8875 (setq line (replace-match
8876 (concat "\000" (match-string 1 line) "\000")
8877 t t line)))
8878
8879 ;; replace "<" and ">" by "&lt;" and "&gt;"
8880 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8881 (setq line (org-html-expand line))
8882
8883 ;; Verbatim lines
8884 (if (and org-export-with-fixed-width
8885 (string-match "^[ \t]*:\\(.*\\)" line))
8886 (progn
8887 (let ((l (match-string 1 line)))
8888 (while (string-match " " l)
8889 (setq l (replace-match "&nbsp;" t t l)))
8890 (insert "\n<span style='font-family:Courier'>"
8891 l "</span>"
8892 (if (and lines
8893 (not (string-match "^[ \t]+\\(:.*\\)"
8894 (car lines))))
8895 "<br>\n" "\n"))))
8896
8897 (setq start 0)
8898 (while (string-match org-protected-link-regexp line start)
8899 (setq start (- (match-end 0) 2))
8900 (setq type (match-string 1 line))
8901 (cond
8902 ((member type '("http" "https" "ftp" "mailto" "news"))
8903 ;; standard URL
8904 (setq line (replace-match
8905 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8906 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8907 nil nil line)))
8908 ((string= type "file")
8909 ;; FILE link
8910 (let* ((filename (match-string 2 line))
8911 (abs-p (file-name-absolute-p filename))
8912 (thefile (if abs-p (expand-file-name filename) filename))
8913 (thefile (save-match-data
8914 (if (string-match ":[0-9]+$" thefile)
8915 (replace-match "" t t thefile)
8916 thefile)))
8917 (file-is-image-p
8918 (save-match-data
8919 (string-match (org-image-file-name-regexp) thefile))))
8920 (setq line (replace-match
8921 (if (and org-export-html-inline-images
8922 file-is-image-p)
8923 (concat "<img src=\"" thefile "\"/>")
8924 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8925 nil nil line))))
8926
8927 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8928 (setq line (replace-match
8929 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
8930
8931 ;; TODO items
8932 (if (and (string-match org-todo-line-regexp line)
8933 (match-beginning 2))
8934 (if (equal (match-string 2 line) org-done-string)
8935 (setq line (replace-match
8936 "<span style='color:green'>\\2</span>"
8937 nil nil line 2))
8938 (setq line (replace-match "<span style='color:red'>\\2</span>"
8939 nil nil line 2))))
8940
8941 ;; DEADLINES
8942 (if (string-match org-deadline-line-regexp line)
8943 (progn
8944 (if (save-match-data
8945 (string-match "<a href"
8946 (substring line 0 (match-beginning 0))))
8947 nil ; Don't do the replacement - it is inside a link
8948 (setq line (replace-match "<span style='color:red'>\\&</span>"
8949 nil nil line 1)))))
8950
8951
8952 (cond
8953 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8954 ;; This is a headline
8955 (setq level (- (match-end 1) (match-beginning 1))
8956 txt (match-string 2 line))
8957 (if (<= level umax) (setq head-count (+ head-count 1)))
8958 (org-html-level-start level txt umax
8959 (and org-export-with-toc (<= level umax))
8960 head-count)
8961 ;; QUOTES
8962 (when (string-match quote-re line)
8963 (insert "<pre>")
8964 (setq inquote t)))
8965
8966 ((and org-export-with-tables
8967 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8968 (if (not table-open)
8969 ;; New table starts
8970 (setq table-open t table-buffer nil table-orig-buffer nil))
8971 ;; Accumulate lines
8972 (setq table-buffer (cons line table-buffer)
8973 table-orig-buffer (cons origline table-orig-buffer))
8974 (when (or (not lines)
8975 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8976 (car lines))))
8977 (setq table-open nil
8978 table-buffer (nreverse table-buffer)
8979 table-orig-buffer (nreverse table-orig-buffer))
8980 (insert (org-format-table-html table-buffer table-orig-buffer))))
8981 (t
8982 ;; Normal lines
8983 ;; Lines starting with "-", and empty lines make new paragraph.
8984 ;; FIXME: Should we add + and *?
8985 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8986 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8987 )))
8988 (if org-export-html-with-timestamp
8989 (insert org-export-html-html-helper-timestamp))
8990 (insert "</body>\n</html>\n")
8991 (normal-mode)
8992 (save-buffer)
8993 (goto-char (point-min)))))
8994
8995 (defun org-format-table-html (lines olines)
8996 "Find out which HTML converter to use and return the HTML code."
8997 (if (string-match "^[ \t]*|" (car lines))
8998 ;; A normal org table
8999 (org-format-org-table-html lines)
9000 ;; Table made by table.el - test for spanning
9001 (let* ((hlines (delq nil (mapcar
9002 (lambda (x)
9003 (if (string-match "^[ \t]*\\+-" x) x
9004 nil))
9005 lines)))
9006 (first (car hlines))
9007 (ll (and (string-match "\\S-+" first)
9008 (match-string 0 first)))
9009 (re (concat "^[ \t]*" (regexp-quote ll)))
9010 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9011 hlines))))
9012 (if (and (not spanning)
9013 (not org-export-prefer-native-exporter-for-tables))
9014 ;; We can use my own converter with HTML conversions
9015 (org-format-table-table-html lines)
9016 ;; Need to use the code generator in table.el, with the original text.
9017 (org-format-table-table-html-using-table-generate-source olines)))))
9018
9019 (defun org-format-org-table-html (lines)
9020 "Format a table into html."
9021 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9022 (setq lines (nreverse lines))
9023 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9024 (setq lines (nreverse lines))
9025 (let ((head (and org-export-highlight-first-table-line
9026 (delq nil (mapcar
9027 (lambda (x) (string-match "^[ \t]*|-" x))
9028 (cdr lines)))))
9029 line fields html)
9030 (setq html (concat org-export-html-table-tag "\n"))
9031 (while (setq line (pop lines))
9032 (catch 'next-line
9033 (if (string-match "^[ \t]*|-" line)
9034 (progn
9035 (setq head nil) ;; head ends here, first time around
9036 ;; ignore this line
9037 (throw 'next-line t)))
9038 ;; Break the line into fields
9039 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9040 (setq html (concat
9041 html
9042 "<tr>"
9043 (mapconcat (lambda (x)
9044 (if head
9045 (concat "<th>" x "</th>")
9046 (concat "<td valign=\"top\">" x "</td>")))
9047 fields "")
9048 "</tr>\n"))))
9049 (setq html (concat html "</table>\n"))
9050 html))
9051
9052 (defun org-fake-empty-table-line (line)
9053 "Replace everything except \"|\" with spaces."
9054 (let ((i (length line))
9055 (newstr (copy-sequence line)))
9056 (while (> i 0)
9057 (setq i (1- i))
9058 (if (not (eq (aref newstr i) ?|))
9059 (aset newstr i ?\ )))
9060 newstr))
9061
9062 (defun org-format-table-table-html (lines)
9063 "Format a table generated by table.el into html.
9064 This conversion does *not* use `table-generate-source' from table.el.
9065 This has the advantage that Org-mode's HTML conversions can be used.
9066 But it has the disadvantage, that no cell- or row-spanning is allowed."
9067 (let (line field-buffer
9068 (head org-export-highlight-first-table-line)
9069 fields html empty)
9070 (setq html (concat org-export-html-table-tag "\n"))
9071 (while (setq line (pop lines))
9072 (setq empty "&nbsp")
9073 (catch 'next-line
9074 (if (string-match "^[ \t]*\\+-" line)
9075 (progn
9076 (if field-buffer
9077 (progn
9078 (setq html (concat
9079 html
9080 "<tr>"
9081 (mapconcat
9082 (lambda (x)
9083 (if (equal x "") (setq x empty))
9084 (if head
9085 (concat "<th valign=\"top\">" x
9086 "</th>\n")
9087 (concat "<td valign=\"top\">" x
9088 "</td>\n")))
9089 field-buffer "\n")
9090 "</tr>\n"))
9091 (setq head nil)
9092 (setq field-buffer nil)))
9093 ;; Ignore this line
9094 (throw 'next-line t)))
9095 ;; Break the line into fields and store the fields
9096 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9097 (if field-buffer
9098 (setq field-buffer (mapcar
9099 (lambda (x)
9100 (concat x "<br>" (pop fields)))
9101 field-buffer))
9102 (setq field-buffer fields))))
9103 (setq html (concat html "</table>\n"))
9104 html))
9105
9106 (defun org-format-table-table-html-using-table-generate-source (lines)
9107 "Format a table into html, using `table-generate-source' from table.el.
9108 This has the advantage that cell- or row-spanning is allowed.
9109 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9110 (require 'table)
9111 (with-current-buffer (get-buffer-create " org-tmp1 ")
9112 (erase-buffer)
9113 (insert (mapconcat 'identity lines "\n"))
9114 (goto-char (point-min))
9115 (if (not (re-search-forward "|[^+]" nil t))
9116 (error "Error processing table"))
9117 (table-recognize-table)
9118 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9119 (table-generate-source 'html " org-tmp2 ")
9120 (set-buffer " org-tmp2 ")
9121 (buffer-substring (point-min) (point-max))))
9122
9123 (defun org-html-expand (string)
9124 "Prepare STRING for HTML export. Applies all active conversions."
9125 ;; First check if there is a link in the line - if yes, apply conversions
9126 ;; only before the start of the link.
9127 (let* ((m (string-match org-link-regexp string))
9128 (s (if m (substring string 0 m) string))
9129 (r (if m (substring string m) "")))
9130 ;; convert < to &lt; and > to &gt;
9131 (while (string-match "<" s)
9132 (setq s (replace-match "&lt;" t t s)))
9133 (while (string-match ">" s)
9134 (setq s (replace-match "&gt;" t t s)))
9135 (if org-export-html-expand
9136 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9137 (setq s (replace-match "<\\1>" nil nil s))))
9138 (if org-export-with-emphasize
9139 (setq s (org-export-html-convert-emphasize s)))
9140 (if org-export-with-sub-superscripts
9141 (setq s (org-export-html-convert-sub-super s)))
9142 (if org-export-with-TeX-macros
9143 (let ((start 0) wd ass)
9144 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9145 (setq wd (match-string 1 s))
9146 (if (setq ass (assoc wd org-html-entities))
9147 (setq s (replace-match (or (cdr ass)
9148 (concat "&" (car ass) ";"))
9149 t t s))
9150 (setq start (+ start (length wd)))))))
9151 (concat s r)))
9152
9153 (defun org-create-multibrace-regexp (left right n)
9154 "Create a regular expression which will match a balanced sexp.
9155 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9156 as single character strings.
9157 The regexp returned will match the entire expression including the
9158 delimiters. It will also define a single group which contains the
9159 match except for the outermost delimiters. The maximum depth of
9160 stacked delimiters is N. Escaping delimiters is not possible."
9161 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9162 (or "\\|")
9163 (re nothing)
9164 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9165 (while (> n 1)
9166 (setq n (1- n)
9167 re (concat re or next)
9168 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9169 (concat left "\\(" re "\\)" right)))
9170
9171 (defvar org-match-substring-regexp
9172 (concat
9173 "\\([^\\]\\)\\([_^]\\)\\("
9174 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9175 "\\|"
9176 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9177 "\\|"
9178 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9179 "The regular expression matching a sub- or superscript.")
9180
9181 (defun org-export-html-convert-sub-super (string)
9182 "Convert sub- and superscripts in STRING to HTML."
9183 (let (key c)
9184 (while (string-match org-match-substring-regexp string)
9185 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9186 (setq c (or (match-string 8 string)
9187 (match-string 6 string)
9188 (match-string 5 string)))
9189 (setq string (replace-match
9190 (concat (match-string 1 string)
9191 "<" key ">" c "</" key ">")
9192 t t string)))
9193 (while (string-match "\\\\\\([_^]\\)" string)
9194 (setq string (replace-match (match-string 1 string) t t string))))
9195 string)
9196
9197 (defun org-export-html-convert-emphasize (string)
9198 (while (string-match
9199 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9200 string)
9201 (setq string (replace-match
9202 (concat "<b>" (match-string 3 string) "</b>")
9203 t t string 2)))
9204 (while (string-match
9205 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9206 string)
9207 (setq string (replace-match
9208 (concat "<i>" (match-string 3 string) "</i>")
9209 t t string 2)))
9210 (while (string-match
9211 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9212 string)
9213 (setq string (replace-match
9214 (concat "<u>" (match-string 3 string) "</u>")
9215 t t string 2)))
9216 string)
9217
9218 (defun org-parse-key-lines ()
9219 "Find the special key lines with the information for exporters."
9220 (save-excursion
9221 (goto-char 0)
9222 (let ((re (org-make-options-regexp
9223 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9224 key)
9225 (while (re-search-forward re nil t)
9226 (setq key (match-string 1))
9227 (cond ((string-equal key "TITLE")
9228 (setq title (match-string 2)))
9229 ((string-equal key "AUTHOR")
9230 (setq author (match-string 2)))
9231 ((string-equal key "EMAIL")
9232 (setq email (match-string 2)))
9233 ((string-equal key "LANGUAGE")
9234 (setq language (match-string 2)))
9235 ((string-equal key "TEXT")
9236 (setq text (concat text "\n" (match-string 2))))
9237 ((string-equal key "OPTIONS")
9238 (setq options (match-string 2))))))))
9239
9240 (defun org-parse-export-options (s)
9241 "Parse the export options line."
9242 (let ((op '(("H" . org-export-headline-levels)
9243 ("num" . org-export-with-section-numbers)
9244 ("toc" . org-export-with-toc)
9245 ("\\n" . org-export-preserve-breaks)
9246 ("@" . org-export-html-expand)
9247 (":" . org-export-with-fixed-width)
9248 ("|" . org-export-with-tables)
9249 ("^" . org-export-with-sub-superscripts)
9250 ("*" . org-export-with-emphasize)
9251 ("TeX" . org-export-with-TeX-macros)))
9252 o)
9253 (while (setq o (pop op))
9254 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9255 s)
9256 (set (make-local-variable (cdr o))
9257 (car (read-from-string (match-string 1 s))))))))
9258
9259 (defun org-html-level-start (level title umax with-toc head-count)
9260 "Insert a new level in HTML export."
9261 (let ((l (1+ (max level umax))))
9262 (while (<= l org-level-max)
9263 (if (aref levels-open (1- l))
9264 (progn
9265 (org-html-level-close l)
9266 (aset levels-open (1- l) nil)))
9267 (setq l (1+ l)))
9268 (if (> level umax)
9269 (progn
9270 (if (aref levels-open (1- level))
9271 (insert "<li>" title "<p>\n")
9272 (aset levels-open (1- level) t)
9273 (insert "<ul><li>" title "<p>\n")))
9274 (if org-export-with-section-numbers
9275 (setq title (concat (org-section-number level) " " title)))
9276 (setq level (+ level 1))
9277 (if with-toc
9278 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9279 level head-count title level))
9280 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9281
9282 (defun org-html-level-close (&rest args)
9283 "Terminate one level in HTML export."
9284 (insert "</ul>"))
9285
9286
9287 ;; Variable holding the vector with section numbers
9288 (defvar org-section-numbers (make-vector org-level-max 0))
9289
9290 (defun org-init-section-numbers ()
9291 "Initialize the vector for the section numbers."
9292 (let* ((level -1)
9293 (numbers (nreverse (org-split-string "" "\\.")))
9294 (depth (1- (length org-section-numbers)))
9295 (i depth) number-string)
9296 (while (>= i 0)
9297 (if (> i level)
9298 (aset org-section-numbers i 0)
9299 (setq number-string (or (car numbers) "0"))
9300 (if (string-match "\\`[A-Z]\\'" number-string)
9301 (aset org-section-numbers i
9302 (- (string-to-char number-string) ?A -1))
9303 (aset org-section-numbers i (string-to-number number-string)))
9304 (pop numbers))
9305 (setq i (1- i)))))
9306
9307 (defun org-section-number (&optional level)
9308 "Return a string with the current section number.
9309 When LEVEL is non-nil, increase section numbers on that level."
9310 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9311 (when level
9312 (when (> level -1)
9313 (aset org-section-numbers
9314 level (1+ (aref org-section-numbers level))))
9315 (setq idx (1+ level))
9316 (while (<= idx depth)
9317 (if (not (= idx 1))
9318 (aset org-section-numbers idx 0))
9319 (setq idx (1+ idx))))
9320 (setq idx 0)
9321 (while (<= idx depth)
9322 (setq n (aref org-section-numbers idx))
9323 (setq string (concat string (if (not (string= string "")) "." "")
9324 (int-to-string n)))
9325 (setq idx (1+ idx)))
9326 (save-match-data
9327 (if (string-match "\\`\\([@0]\\.\\)+" string)
9328 (setq string (replace-match "" nil nil string)))
9329 (if (string-match "\\(\\.0\\)+\\'" string)
9330 (setq string (replace-match "" nil nil string))))
9331 string))
9332
9333
9334 ;;; Key bindings
9335
9336 ;; - Bindings in Org-mode map are currently
9337 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9338 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9339 ;; e (?) useful from outline-mode
9340 ;; i k @ expendable from outline-mode
9341 ;; 0123456789 ! %^& ()_{} " `' free
9342
9343 (define-key org-mode-map "\C-i" 'org-cycle)
9344 (define-key org-mode-map [(meta tab)] 'org-complete)
9345 (define-key org-mode-map "\M-\C-i" 'org-complete)
9346 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9347 (define-key org-mode-map [(meta left)] 'org-metaleft)
9348 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9349 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9350 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9351 (define-key org-mode-map [(meta right)] 'org-metaright)
9352 (define-key org-mode-map [(meta up)] 'org-metaup)
9353 (define-key org-mode-map [(meta down)] 'org-metadown)
9354 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9355 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9356 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9357 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9358 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9359 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9360 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9361 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9362 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9363 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9364 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9365 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9366 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9367 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9368 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9369 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9370 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9371 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9372 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9373 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9374 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9375 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9376 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9377 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9378 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9379 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9380 (define-key org-mode-map "\C-c[" 'org-add-file)
9381 (define-key org-mode-map "\C-c]" 'org-remove-file)
9382 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9383 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9384 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9385 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9386 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9387 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9388 ;; The following line is necessary for German keyboards under Suse GNU/Linux
9389 (unless org-xemacs-p
9390 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9391 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9392 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9393 (define-key org-mode-map "\C-m" 'org-return)
9394 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9395 (define-key org-mode-map [(meta return)] 'org-meta-return)
9396 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9397 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9398 (define-key org-mode-map "\C-c+" 'org-table-sum)
9399 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9400 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9401 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9402 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9403 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9404 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9405 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9406 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9407 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9408 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9409 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9410 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9411 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9412 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9413 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9414 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9415 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9416
9417 (defsubst org-table-p () (org-at-table-p))
9418
9419 (defun org-self-insert-command (N)
9420 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9421 If the cursor is in a table looking at whitespace, the whitespace is
9422 overwritten, and the table is not marked as requiring realignment."
9423 (interactive "p")
9424 (if (and (org-table-p)
9425 (eq N 1)
9426 (looking-at "[^|\n]* +|"))
9427 (let (org-table-may-need-update)
9428 (goto-char (1- (match-end 0)))
9429 (delete-backward-char 1)
9430 (goto-char (match-beginning 0))
9431 (self-insert-command N))
9432 (setq org-table-may-need-update t)
9433 (self-insert-command N)))
9434
9435 ;; FIXME:
9436 ;; The following two functions might still be optimized to trigger
9437 ;; re-alignment less frequently.
9438
9439 (defun org-delete-backward-char (N)
9440 "Like `delete-backward-char', insert whitespace at field end in tables.
9441 When deleting backwards, in tables this function will insert whitespace in
9442 front of the next \"|\" separator, to keep the table aligned. The table will
9443 still be marked for re-alignment, because a narrow field may lead to a
9444 reduced column width."
9445 (interactive "p")
9446 (if (and (org-table-p)
9447 (eq N 1)
9448 (string-match "|" (buffer-substring (point-at-bol) (point)))
9449 (looking-at ".*?|"))
9450 (let ((pos (point)))
9451 (backward-delete-char N)
9452 (skip-chars-forward "^|")
9453 (insert " ")
9454 (goto-char (1- pos)))
9455 (backward-delete-char N)))
9456
9457 (defun org-delete-char (N)
9458 "Like `delete-char', but insert whitespace at field end in tables.
9459 When deleting characters, in tables this function will insert whitespace in
9460 front of the next \"|\" separator, to keep the table aligned. The table
9461 will still be marked for re-alignment, because a narrow field may lead to
9462 a reduced column width."
9463 (interactive "p")
9464 (if (and (org-table-p)
9465 (not (bolp))
9466 (not (= (char-after) ?|))
9467 (eq N 1))
9468 (if (looking-at ".*?|")
9469 (let ((pos (point)))
9470 (replace-match (concat
9471 (substring (match-string 0) 1 -1)
9472 " |"))
9473 (goto-char pos)))
9474 (delete-char N)))
9475
9476 ;; How to do this: Measure non-white length of current string
9477 ;; If equal to column width, we should realign.
9478
9479 (when (eq org-enable-table-editor 'optimized)
9480 ;; If the user wants maximum table support, we need to hijack
9481 ;; some standard editing functions
9482 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9483 org-mode-map global-map)
9484 (substitute-key-definition 'delete-char 'org-delete-char
9485 org-mode-map global-map)
9486 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9487 org-mode-map global-map)
9488 (define-key org-mode-map "|" 'self-insert-command))
9489
9490 (defun org-shiftcursor-error ()
9491 "Throw an error because Shift-Cursor command was applied in wrong context."
9492 (error "This command is only active in tables and on headlines"))
9493
9494 (defun org-shifttab ()
9495 "Call `(org-cycle t)' or `org-table-previous-field'."
9496 (interactive)
9497 (cond
9498 ((org-at-table-p) (org-table-previous-field))
9499 (t (org-cycle '(4)))))
9500
9501 (defun org-shiftmetaleft ()
9502 "Call `org-promote-subtree' or `org-table-delete-column'."
9503 (interactive)
9504 (cond
9505 ((org-at-table-p) (org-table-delete-column))
9506 ((org-on-heading-p) (org-promote-subtree))
9507 (t (org-shiftcursor-error))))
9508
9509 (defun org-shiftmetaright ()
9510 "Call `org-demote-subtree' or `org-table-insert-column'."
9511 (interactive)
9512 (cond
9513 ((org-at-table-p) (org-table-insert-column))
9514 ((org-on-heading-p) (org-demote-subtree))
9515 (t (org-shiftcursor-error))))
9516
9517 (defun org-shiftmetaup (&optional arg)
9518 "Call `org-move-subtree-up' or `org-table-kill-row'."
9519 (interactive "P")
9520 (cond
9521 ((org-at-table-p) (org-table-kill-row))
9522 ((org-on-heading-p) (org-move-subtree-up arg))
9523 (t (org-shiftcursor-error))))
9524 (defun org-shiftmetadown (&optional arg)
9525 "Call `org-move-subtree-down' or `org-table-insert-row'."
9526 (interactive "P")
9527 (cond
9528 ((org-at-table-p) (org-table-insert-row arg))
9529 ((org-on-heading-p) (org-move-subtree-down arg))
9530 (t (org-shiftcursor-error))))
9531
9532 (defun org-metaleft (&optional arg)
9533 "Call `org-do-promote' or `org-table-move-column' to left."
9534 (interactive "P")
9535 (cond
9536 ((org-at-table-p) (org-table-move-column 'left))
9537 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9538 (t (backward-word (prefix-numeric-value arg)))))
9539
9540 (defun org-metaright (&optional arg)
9541 "Call `org-do-demote' or `org-table-move-column' to right."
9542 (interactive "P")
9543 (cond
9544 ((org-at-table-p) (org-table-move-column nil))
9545 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9546 (t (forward-word (prefix-numeric-value arg)))))
9547
9548 (defun org-metaup (&optional arg)
9549 "Call `org-move-subtree-up' or `org-table-move-row' up."
9550 (interactive "P")
9551 (cond
9552 ((org-at-table-p) (org-table-move-row 'up))
9553 ((org-on-heading-p) (org-move-subtree-up arg))
9554 (t (org-shiftcursor-error))))
9555
9556 (defun org-metadown (&optional arg)
9557 "Call `org-move-subtree-down' or `org-table-move-row' down."
9558 (interactive "P")
9559 (cond
9560 ((org-at-table-p) (org-table-move-row nil))
9561 ((org-on-heading-p) (org-move-subtree-down arg))
9562 (t (org-shiftcursor-error))))
9563
9564 (defun org-shiftup (&optional arg)
9565 "Call `org-timestamp-up' or `org-priority-up'."
9566 (interactive "P")
9567 (cond
9568 ((org-at-timestamp-p) (org-timestamp-up arg))
9569 (t (org-priority-up))))
9570
9571 (defun org-shiftdown (&optional arg)
9572 "Call `org-timestamp-down' or `org-priority-down'."
9573 (interactive "P")
9574 (cond
9575 ((org-at-timestamp-p) (org-timestamp-down arg))
9576 (t (org-priority-down))))
9577
9578 (defun org-copy-special ()
9579 "Call either `org-table-copy' or `org-copy-subtree'."
9580 (interactive)
9581 (call-interactively
9582 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9583
9584 (defun org-cut-special ()
9585 "Call either `org-table-copy' or `org-cut-subtree'."
9586 (interactive)
9587 (call-interactively
9588 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9589
9590 (defun org-paste-special (arg)
9591 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9592 (interactive "P")
9593 (if (org-at-table-p)
9594 (org-table-paste-rectangle)
9595 (org-paste-subtree arg)))
9596
9597 (defun org-ctrl-c-ctrl-c (&optional arg)
9598 "Call realign table, or recognize a table.el table, or update keywords.
9599 When the cursor is inside a table created by the table.el package,
9600 activate that table. Otherwise, if the cursor is at a normal table
9601 created with org.el, re-align that table. This command works even if
9602 the automatic table editor has been turned off.
9603 If the cursor is in one of the special #+KEYWORD lines, this triggers
9604 scanning the buffer for these lines and updating the information."
9605 (interactive "P")
9606 (let ((org-enable-table-editor t))
9607 (cond
9608 ((org-at-table.el-p)
9609 (require 'table)
9610 (beginning-of-line 1)
9611 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9612 (table-recognize-table))
9613 ((org-at-table-p)
9614 (org-table-maybe-eval-formula)
9615 (if arg
9616 (org-table-recalculate t)
9617 (org-table-maybe-recalculate-line))
9618 (org-table-align))
9619 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9620 (cond
9621 ((equal (match-string 1) "TBLFM")
9622 ;; Recalculate the table before this line
9623 (save-excursion
9624 (beginning-of-line 1)
9625 (skip-chars-backward " \r\n\t")
9626 (if (org-at-table-p) (org-table-recalculate t))))
9627 (t
9628 (let ((org-inhibit-startup t)) (org-mode)))))
9629 ((org-region-active-p)
9630 (org-table-convert-region (region-beginning) (region-end) arg))
9631 ((and (region-beginning) (region-end))
9632 (if (y-or-n-p "Convert inactive region to table? ")
9633 (org-table-convert-region (region-beginning) (region-end) arg)
9634 (error "Abort")))
9635 (t (error "No table at point, and no region to make one")))))
9636
9637 (defun org-return ()
9638 "Call `org-table-next-row' or `newline'."
9639 (interactive)
9640 (cond
9641 ((org-at-table-p)
9642 (org-table-justify-field-maybe)
9643 (org-table-next-row))
9644 (t (newline))))
9645
9646 (defun org-meta-return (&optional arg)
9647 "Call `org-insert-heading' or `org-table-wrap-region'."
9648 (interactive "P")
9649 (cond
9650 ((org-at-table-p)
9651 (org-table-wrap-region arg))
9652 (t (org-insert-heading))))
9653
9654 ;;; Menu entries
9655
9656 ;; Define the Org-mode menus
9657 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9658 '("Tbl"
9659 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9660 ["Next Field" org-cycle (org-at-table-p)]
9661 ["Previous Field" org-shifttab (org-at-table-p)]
9662 ["Next Row" org-return (org-at-table-p)]
9663 "--"
9664 ["Blank Field" org-table-blank-field (org-at-table-p)]
9665 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9666 "--"
9667 ("Column"
9668 ["Move Column Left" org-metaleft (org-at-table-p)]
9669 ["Move Column Right" org-metaright (org-at-table-p)]
9670 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9671 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9672 ("Row"
9673 ["Move Row Up" org-metaup (org-at-table-p)]
9674 ["Move Row Down" org-metadown (org-at-table-p)]
9675 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9676 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9677 "--"
9678 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9679 ("Rectangle"
9680 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9681 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9682 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9683 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9684 "--"
9685 ("Calculate"
9686 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
9687 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9688 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
9689 "--"
9690 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9691 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9692 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9693 "--"
9694 ["Sum Column/Rectangle" org-table-sum
9695 (or (org-at-table-p) (org-region-active-p))]
9696 ["Which Column?" org-table-current-column (org-at-table-p)])
9697 ["Debug Formulas"
9698 (setq org-table-formula-debug (not org-table-formula-debug))
9699 :style toggle :selected org-table-formula-debug]
9700 "--"
9701 ["Invisible Vlines" org-table-toggle-vline-visibility
9702 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9703 "--"
9704 ["Create" org-table-create (and (not (org-at-table-p))
9705 org-enable-table-editor)]
9706 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9707 ["Import from File" org-table-import (not (org-at-table-p))]
9708 ["Export to File" org-table-export (org-at-table-p)]
9709 "--"
9710 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9711
9712 (easy-menu-define org-org-menu org-mode-map "Org menu"
9713 '("Org"
9714 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9715 ["Sparse Tree" org-occur t]
9716 ["Show All" show-all t]
9717 "--"
9718 ["New Heading" org-insert-heading t]
9719 ("Navigate Headings"
9720 ["Up" outline-up-heading t]
9721 ["Next" outline-next-visible-heading t]
9722 ["Previous" outline-previous-visible-heading t]
9723 ["Next Same Level" outline-forward-same-level t]
9724 ["Previous Same Level" outline-backward-same-level t]
9725 "--"
9726 ["Jump" org-goto t])
9727 ("Edit Structure"
9728 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9729 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9730 "--"
9731 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9732 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9733 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9734 "--"
9735 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9736 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9737 ["Demote Heading" org-metaright (not (org-at-table-p))]
9738 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9739 "--"
9740 ["Archive Subtree" org-archive-subtree t])
9741 "--"
9742 ("TODO Lists"
9743 ["TODO/DONE/-" org-todo t]
9744 ["Show TODO Tree" org-show-todo-tree t]
9745 "--"
9746 ["Set Priority" org-priority t]
9747 ["Priority Up" org-shiftup t]
9748 ["Priority Down" org-shiftdown t])
9749 ("Dates and Scheduling"
9750 ["Timestamp" org-time-stamp t]
9751 ("Change Date"
9752 ["1 Day Later" org-timestamp-up-day t]
9753 ["1 Day Earlier" org-timestamp-down-day t]
9754 ["1 ... Later" org-shiftup t]
9755 ["1 ... Earlier" org-shiftdown t])
9756 ["Compute Time Range" org-evaluate-time-range t]
9757 ["Schedule Item" org-schedule t]
9758 ["Deadline" org-deadline t]
9759 "--"
9760 ["Goto Calendar" org-goto-calendar t]
9761 ["Date from Calendar" org-date-from-calendar t])
9762 "--"
9763 ("Timeline/Agenda"
9764 ["Show TODO Tree this File" org-show-todo-tree t]
9765 ["Check Deadlines this File" org-check-deadlines t]
9766 ["Timeline Current File" org-timeline t]
9767 "--"
9768 ["Agenda" org-agenda t])
9769 ("File List for Agenda")
9770 "--"
9771 ("Hyperlinks"
9772 ["Store Link (Global)" org-store-link t]
9773 ["Insert Link" org-insert-link t]
9774 ["Follow Link" org-open-at-point t])
9775 "--"
9776 ("Export"
9777 ["ASCII" org-export-as-ascii t]
9778 ["Extract Visible Text" org-export-copy-visible t]
9779 ["HTML" org-export-as-html t]
9780 ["HTML and Open" org-export-as-html-and-open t]
9781 ; ["OPML" org-export-as-opml nil]
9782 "--"
9783 ["Option Template" org-insert-export-options-template t]
9784 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9785 "--"
9786 ("Documentation"
9787 ["Show Version" org-version t]
9788 ["Info Documentation" org-info t])
9789 ("Customize"
9790 ["Browse Org Group" org-customize t]
9791 "--"
9792 ["Build Full Customize Menu" org-create-customize-menu
9793 (fboundp 'customize-menu-create)])
9794 ))
9795
9796 (defun org-info (&optional node)
9797 "Read documentation for Org-mode in the info system.
9798 With optional NODE, go directly to that node."
9799 (interactive)
9800 (require 'info)
9801 (Info-goto-node (format "(org)%s" (or node ""))))
9802
9803 (defun org-install-agenda-files-menu ()
9804 (easy-menu-change
9805 '("Org") "File List for Agenda"
9806 (append
9807 (list
9808 ["Edit File List" (customize-variable 'org-agenda-files) t]
9809 ["Add Current File to List" org-add-file t]
9810 ["Remove Current File from List" org-remove-file t]
9811 "--")
9812 (mapcar 'org-file-menu-entry org-agenda-files))))
9813
9814 ;;; Documentation
9815
9816 (defun org-customize ()
9817 "Call the customize function with org as argument."
9818 (interactive)
9819 (customize-browse 'org))
9820
9821 (defun org-create-customize-menu ()
9822 "Create a full customization menu for Org-mode, insert it into the menu."
9823 (interactive)
9824 (if (fboundp 'customize-menu-create)
9825 (progn
9826 (easy-menu-change
9827 '("Org") "Customize"
9828 `(["Browse Org group" org-customize t]
9829 "--"
9830 ,(customize-menu-create 'org)
9831 ["Set" Custom-set t]
9832 ["Save" Custom-save t]
9833 ["Reset to Current" Custom-reset-current t]
9834 ["Reset to Saved" Custom-reset-saved t]
9835 ["Reset to Standard Settings" Custom-reset-standard t]))
9836 (message "\"Org\"-menu now contains full customization menu"))
9837 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9838
9839 ;;; Miscellaneous stuff
9840
9841 (defun org-move-line-down (arg)
9842 "Move the current line down. With prefix argument, move it past ARG lines."
9843 (interactive "p")
9844 (let ((col (current-column))
9845 beg end pos)
9846 (beginning-of-line 1) (setq beg (point))
9847 (beginning-of-line 2) (setq end (point))
9848 (beginning-of-line (+ 1 arg))
9849 (setq pos (move-marker (make-marker) (point)))
9850 (insert (delete-and-extract-region beg end))
9851 (goto-char pos)
9852 (move-to-column col)))
9853
9854 (defun org-move-line-up (arg)
9855 "Move the current line up. With prefix argument, move it past ARG lines."
9856 (interactive "p")
9857 (let ((col (current-column))
9858 beg end pos)
9859 (beginning-of-line 1) (setq beg (point))
9860 (beginning-of-line 2) (setq end (point))
9861 (beginning-of-line (- arg))
9862 (setq pos (move-marker (make-marker) (point)))
9863 (insert (delete-and-extract-region beg end))
9864 (goto-char pos)
9865 (move-to-column col)))
9866
9867 ;; Functions needed for Emacs/XEmacs region compatibility
9868
9869 (defun org-region-active-p ()
9870 "Is `transient-mark-mode' on and the region active?
9871 Works on both Emacs and XEmacs."
9872 (if org-ignore-region
9873 nil
9874 (if org-xemacs-p
9875 (and zmacs-regions (region-active-p))
9876 (and transient-mark-mode mark-active))))
9877
9878 (defun org-add-to-invisibility-spec (arg)
9879 "Add elements to `buffer-invisibility-spec'.
9880 See documentation for `buffer-invisibility-spec' for the kind of elements
9881 that can be added."
9882 (cond
9883 ((fboundp 'add-to-invisibility-spec)
9884 (add-to-invisibility-spec arg))
9885 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9886 (setq buffer-invisibility-spec (list arg)))
9887 (t
9888 (setq buffer-invisibility-spec
9889 (cons arg buffer-invisibility-spec)))))
9890
9891 (defun org-remove-from-invisibility-spec (arg)
9892 "Remove elements from `buffer-invisibility-spec'."
9893 (if (fboundp 'remove-from-invisibility-spec)
9894 (remove-from-invisibility-spec arg)
9895 (if (consp buffer-invisibility-spec)
9896 (setq buffer-invisibility-spec
9897 (delete arg buffer-invisibility-spec)))))
9898
9899 (defun org-in-invisibility-spec-p (arg)
9900 "Is ARG a member of `buffer-invisibility-spec'?."
9901 (if (consp buffer-invisibility-spec)
9902 (member arg buffer-invisibility-spec)
9903 nil))
9904
9905 (defun org-image-file-name-regexp ()
9906 "Return regexp matching the file names of images."
9907 (if (fboundp 'image-file-name-regexp)
9908 (image-file-name-regexp)
9909 (let ((image-file-name-extensions
9910 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9911 "xbm" "xpm" "pbm" "pgm" "ppm")))
9912 (concat "\\."
9913 (regexp-opt (nconc (mapcar 'upcase
9914 image-file-name-extensions)
9915 image-file-name-extensions)
9916 t)
9917 "\\'"))))
9918
9919 ;; Functions needed for compatibility with old outline.el
9920
9921 ;; The following functions capture almost the entire compatibility code
9922 ;; between the different versions of outline-mode. The only other place
9923 ;; where this is important are the font-lock-keywords. Search for
9924 ;; `org-noutline-p' to find it.
9925
9926 ;; C-a should go to the beginning of a *visible* line, also in the
9927 ;; new outline.el. I guess this should be patched into Emacs?
9928 (defun org-beginning-of-line ()
9929 "Go to the beginning of the current line. If that is invisible, continue
9930 to a visible line beginning. This makes the function of C-a more intuitive."
9931 (interactive)
9932 (beginning-of-line 1)
9933 (if (bobp)
9934 nil
9935 (backward-char 1)
9936 (if (org-invisible-p)
9937 (while (and (not (bobp)) (org-invisible-p))
9938 (backward-char 1)
9939 (beginning-of-line 1))
9940 (forward-char 1))))
9941 (when org-noutline-p
9942 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9943
9944 (defun org-invisible-p ()
9945 "Check if point is at a character currently not visible."
9946 (if org-noutline-p
9947 ;; Early versions of noutline don't have `outline-invisible-p'.
9948 (if (fboundp 'outline-invisible-p)
9949 (outline-invisible-p)
9950 (get-char-property (point) 'invisible))
9951 (save-excursion
9952 (skip-chars-backward "^\r\n")
9953 (equal (char-before) ?\r))))
9954
9955 (defun org-back-to-heading (&optional invisible-ok)
9956 "Move to previous heading line, or beg of this line if it's a heading.
9957 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9958 (if org-noutline-p
9959 (outline-back-to-heading invisible-ok)
9960 (if (looking-at outline-regexp)
9961 t
9962 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9963 outline-regexp)
9964 nil t)
9965 (if invisible-ok
9966 (progn (goto-char (match-end 1))
9967 (looking-at outline-regexp)))
9968 (error "Before first heading")))))
9969
9970 (defun org-on-heading-p (&optional invisible-ok)
9971 "Return t if point is on a (visible) heading line.
9972 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9973 (if org-noutline-p
9974 (outline-on-heading-p 'invisible-ok)
9975 (save-excursion
9976 (skip-chars-backward "^\n\r")
9977 (and (looking-at outline-regexp)
9978 (or invisible-ok
9979 (bobp)
9980 (equal (char-before) ?\n))))))
9981
9982 (defun org-up-heading-all (arg)
9983 "Move to the heading line of which the present line is a subheading.
9984 This function considers both visible and invisible heading lines.
9985 With argument, move up ARG levels."
9986 (if org-noutline-p
9987 (if (fboundp 'outline-up-heading-all)
9988 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9989 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9990 (org-back-to-heading t)
9991 (looking-at outline-regexp)
9992 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9993 (error "Cannot move up %d levels" arg)
9994 (re-search-backward
9995 (concat "[\n\r]" (regexp-quote
9996 (make-string (- (match-end 0) (match-beginning 0) arg)
9997 ?*))
9998 "[^*]"))
9999 (forward-char 1))))
10000
10001 (defun org-show-hidden-entry ()
10002 "Show an entry where even the heading is hidden."
10003 (save-excursion
10004 (if (not org-noutline-p)
10005 (progn
10006 (org-back-to-heading t)
10007 (org-flag-heading nil)))
10008 (org-show-entry)))
10009
10010 (defun org-check-occur-regexp (regexp)
10011 "If REGEXP starts with \"^\", modify it to check for \\r as well.
10012 Of course, only for the old outline mode."
10013 (if org-noutline-p
10014 regexp
10015 (if (string-match "^\\^" regexp)
10016 (concat "[\n\r]" (substring regexp 1))
10017 regexp)))
10018
10019 (defun org-flag-heading (flag &optional entry)
10020 "Flag the current heading. FLAG non-nil means make invisible.
10021 When ENTRY is non-nil, show the entire entry."
10022 (save-excursion
10023 (org-back-to-heading t)
10024 (if (not org-noutline-p)
10025 ;; Make the current headline visible
10026 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
10027 ;; Check if we should show the entire entry
10028 (if entry
10029 (progn
10030 (org-show-entry)
10031 (save-excursion ;; FIXME: Is this the fix for points in the -|
10032 ;; middle of text? |
10033 (and (outline-next-heading) ;; |
10034 (org-flag-heading nil)))) ; show the next heading _|
10035 (outline-flag-region (max 1 (1- (point)))
10036 (save-excursion (outline-end-of-heading) (point))
10037 (if org-noutline-p
10038 flag
10039 (if flag ?\r ?\n))))))
10040
10041 (defun org-show-subtree ()
10042 "Show everything after this heading at deeper levels."
10043 (outline-flag-region
10044 (point)
10045 (save-excursion
10046 (outline-end-of-subtree) (outline-next-heading) (point))
10047 (if org-noutline-p nil ?\n)))
10048
10049 (defun org-show-entry ()
10050 "Show the body directly following this heading.
10051 Show the heading too, if it is currently invisible."
10052 (interactive)
10053 (save-excursion
10054 (org-back-to-heading t)
10055 (outline-flag-region
10056 (1- (point))
10057 (save-excursion
10058 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
10059 (or (match-beginning 1) (point-max)))
10060 (if org-noutline-p nil ?\n))))
10061
10062
10063 (defun org-make-options-regexp (kwds)
10064 "Make a regular expression for keyword lines."
10065 (concat
10066 (if org-noutline-p "^" "[\n\r]")
10067 "#?[ \t]*\\+\\("
10068 (mapconcat 'regexp-quote kwds "\\|")
10069 "\\):[ \t]*"
10070 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10071
10072 ;; Make `bookmark-jump' show the jump location if it was hidden.
10073 (eval-after-load "bookmark"
10074 '(if (boundp 'bookmark-after-jump-hook)
10075 ;; We can use the hook
10076 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
10077 ;; Hook not available, use advice
10078 (defadvice bookmark-jump (after org-make-visible activate)
10079 "Make the position visible."
10080 (org-bookmark-jump-unhide))))
10081
10082 (defun org-bookmark-jump-unhide ()
10083 "Unhide the current position, to show the bookmark location."
10084 (and (eq major-mode 'org-mode)
10085 (or (org-invisible-p)
10086 (save-excursion (goto-char (max (point-min) (1- (point))))
10087 (org-invisible-p)))
10088 (org-show-hierarchy-above)))
10089
10090 ;;; Finish up
10091
10092 (provide 'org)
10093
10094 (run-hooks 'org-load-hook)
10095
10096 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10097 ;;; org.el ends here