]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Update years in copyright notice; nfc.
[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
4 ;; Copyright (C) 2004, 2005 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
7 ;; Keywords: outlines, hypermedia, calendar
8 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
9 ;; Version: 3.14
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;
29 ;;; Commentary:
30 ;;
31 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
32 ;; project planning with a fast and effective plain-text system.
33 ;;
34 ;; Org-mode develops organizational tasks around a NOTES file that contains
35 ;; information about projects as plain text. Org-mode is implemented on top
36 ;; of outline-mode - ideal to keep the content of large files well structured.
37 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
38 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
39 ;; calendar. Tables are easily created with a built-in table editor. Plain
40 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
41 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
42 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
43 ;; of it) can be exported as a structured ASCII file, or as HTML.
44 ;;
45 ;; Installation
46 ;; ------------
47 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
48 ;; only need to copy the following lines to your .emacs file. The last two
49 ;; lines define *global* keys for the commands `org-store-link' and
50 ;; `org-agenda' - please choose suitable keys yourself.
51 ;;
52 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
53 ;; (define-key global-map "\C-cl" 'org-store-link)
54 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;;
56 ;; If you have downloaded Org-mode from the Web, you must byte-compile
57 ;; org.el and put it on your load path. In addition to the Emacs Lisp
58 ;; lines above, you also need to add the following lines to .emacs:
59 ;;
60 ;; (autoload 'org-mode "org" "Org mode" t)
61 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
62 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
63 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
64 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
65 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;;
67 ;; This setup will put all files with extension ".org" into Org-mode. As
68 ;; an alternative, make the first line of a file look like this:
69 ;;
70 ;; MY PROJECTS -*- mode: org; -*-
71 ;;
72 ;; which will select Org-mode for this buffer no matter what the file's
73 ;; name is.
74 ;;
75 ;; Documentation
76 ;; -------------
77 ;; The documentation of Org-mode can be found in the TeXInfo file. The
78 ;; distribution also contains a PDF version of it. At the homepage of
79 ;; Org-mode, you can read the same text online as HTML. There is also an
80 ;; excellent reference card made by Philip Rooke.
81 ;;
82 ;; Changes:
83 ;; -------
84 ;; Version 3.14
85 ;; - Formulas for individual fields in table.
86 ;; - Automatic recalculation in calculating tables.
87 ;; - Named fields and columns in tables.
88 ;; - Fixed bug with calling `org-archive' several times in a row.
89 ;;
90 ;; Version 3.13
91 ;; - Efficiency improvements: Fewer table re-alignments needed.
92 ;; - New special lines in tables, for defining names for individual cells.
93 ;;
94 ;; Version 3.12
95 ;; - Tables can store formulas (one per column) and compute fields.
96 ;; Not quite like a full spreadsheet, but very powerful.
97 ;; - table.el keybinding is now `C-c ~'.
98 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
99 ;; - Small changes to keys in agenda buffer. Affected keys:
100 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
101 ;; - Bug fixes.
102 ;;
103 ;; Version 3.11
104 ;; - Links inserted with C-c C-l are now by default enclosed in angle
105 ;; brackets. See the new variable `org-link-format'.
106 ;; - ">" terminates a link, this is a way to have several links in a line.
107 ;; Both "<" and ">" are no longer allowed as characters in a link.
108 ;; - Archiving of finished tasks.
109 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
110 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
111 ;; - Compatibility problems with viper-mode fixed.
112 ;; - Improved html export of tables.
113 ;; - Various clean-up changes.
114 ;;
115 ;; Version 3.10
116 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
117 ;;
118 ;; Version 3.09
119 ;; - Time-of-day specifications in agenda are extracted and placed
120 ;; into the prefix. Timed entries can be placed into a time grid for
121 ;; day.
122 ;;
123 ;; Version 3.08
124 ;; - "|" no longer allowed as part of a link, to allow links in tables.
125 ;; - The prefix of items in the agenda buffer can be configured.
126 ;; - Cleanup.
127 ;;
128 ;; Version 3.07
129 ;; - Some folding incinsistencies removed.
130 ;; - BBDB links to company-only entries.
131 ;; - Bug fixes and global cleanup.
132 ;;
133 ;; Version 3.06
134 ;; - M-S-RET inserts a new TODO heading.
135 ;; - New startup option `content'.
136 ;; - Better visual response when TODO items in agenda change status.
137 ;; - Window positioning after visibility state changes optimized and made
138 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
139 ;;
140 ;; Version 3.05
141 ;; - Agenda entries from the diary are linked to the diary file, so
142 ;; adding and editing diary entries can be done directly from the agenda.
143 ;; - Many calendar/diary commands available directly from agenda.
144 ;; - Field copying in tables with S-RET does increment.
145 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
146 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
147 ;;
148 ;; Version 3.04
149 ;; - Table editor optimized to need fewer realignments, and to keep
150 ;; table shape when typing in fields.
151 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
152 ;; into arbitrary major modes.
153 ;; - Fixed bug with realignment in XEmacs.
154 ;; - Startup options can be set with special #+STARTUP line.
155 ;; - Heading following a match in org-occur can be suppressed.
156 ;;
157 ;; Version 3.03
158 ;; - Copyright transfer to the FSF.
159 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
160 ;; - Timeline now always contains today, and `.' jumps to it.
161 ;; - Table editor:
162 ;; - cut and paste of rectangular regions in tables
163 ;; - command to convert org-mode table to table.el table and back
164 ;; - command to treat several cells like a paragraph and fill it
165 ;; - command to convert a buffer region to a table
166 ;; - import/export tables as tab-separated files (exchange with Excel)
167 ;; - Agenda:
168 ;; - Sorting mechanism for agenda items rewritten from scratch.
169 ;; - Sorting fully configurable.
170 ;; - Entries specifying a time are sorted together.
171 ;; - Completion also covers option keywords after `#-'.
172 ;; - Bug fixes.
173 ;;
174 ;; Version 3.01
175 ;; - New reference card, thanks to Philip Rooke for creating it.
176 ;; - Single file agenda renamed to "Timeline". It no longer shows
177 ;; warnings about upcoming deadlines/overdue scheduled items.
178 ;; That functionality is now limited to the (multifile) agenda.
179 ;; - When reading a date, the calendar can be manipulated with keys.
180 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
181 ;; - Minor bug fixes and documentation improvements.
182
183 ;;; Code:
184
185 (eval-when-compile (require 'cl) (require 'calendar))
186 (require 'outline)
187 (require 'time-date)
188 (require 'easymenu)
189
190 ;;; Customization variables
191
192 (defvar org-version "3.14"
193 "The version number of the file org.el.")
194 (defun org-version ()
195 (interactive)
196 (message "Org-mode version %s" org-version))
197
198 ;; The following two constants are for compatibility with different Emacs
199 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
200 ;; The compatibility code in org.el is based on these two constants.
201 (defconst org-xemacs-p (featurep 'xemacs)
202 "Are we running xemacs?")
203 (defconst org-noutline-p (featurep 'noutline)
204 "Are we using the new outline mode?")
205
206 (defgroup org nil
207 "Outline-based notes management and organizer "
208 :tag "Org"
209 :group 'outlines
210 :group 'hypermedia
211 :group 'calendar)
212
213 (defgroup org-startup nil
214 "Options concerning startup of Org-mode."
215 :tag "Org Startup"
216 :group 'org)
217
218 (defcustom org-CUA-compatible nil
219 "Non-nil means use alternative key bindings for S-<cursor movement>.
220 Org-mode used S-<cursor movement> for changing timestamps and priorities.
221 S-<cursor movement> is also used for example by `CUA-mode' to select text.
222 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
223 alternative bindings. Setting this variable to t will replace the following
224 keys both in Org-mode and in the Org-agenda buffer.
225
226 S-RET -> C-S-RET
227 S-up -> M-p
228 S-down -> M-n
229 S-left -> M--
230 S-right -> M-+
231
232 If you do not like the alternative keys, take a look at the variable
233 `org-disputed-keys'.
234
235 This option is only relevant at load-time of Org-mode. Changing it requires
236 a restart of Emacs to become effective."
237 :group 'org-startup
238 :type 'boolean)
239
240 (defvar org-disputed-keys
241 '((S-up [(shift up)] [(meta ?p)])
242 (S-down [(shift down)] [(meta ?n)])
243 (S-left [(shift left)] [(meta ?-)])
244 (S-right [(shift right)] [(meta ?+)])
245 (S-return [(shift return)] [(control shift return)]))
246 "Keys for which Org-mode and other modes compete.
247 This is an alist, cars are symbols for lookup, 1st element is the default key,
248 second element will be used when `org-CUA-compatible' is t.")
249
250 (defun org-key (key)
251 "Select a key according to `org-CUA-compatible'."
252 (nth (if org-CUA-compatible 2 1)
253 (or (assq key org-disputed-keys)
254 (error "Invalid Key %s in `org-key'" key))))
255
256 (defcustom org-startup-folded t
257 "Non-nil means, entering Org-mode will switch to OVERVIEW.
258 This can also be configured on a per-file basis by adding one of
259 the following lines anywhere in the buffer:
260
261 #+STARTUP: fold
262 #+STARTUP: nofold
263 #+STARTUP: content"
264 :group 'org-startup
265 :type '(choice
266 (const :tag "nofold: show all" nil)
267 (const :tag "fold: overview" t)
268 (const :tag "content: all headlines" content)))
269
270 (defcustom org-startup-truncated t
271 "Non-nil means, entering Org-mode will set `truncate-lines'.
272 This is useful since some lines containing links can be very long and
273 uninteresting. Also tables look terrible when wrapped."
274 :group 'org-startup
275 :type 'boolean)
276
277 (defcustom org-startup-with-deadline-check nil
278 "Non-nil means, entering Org-mode will run the deadline check.
279 This means, if you start editing an org file, you will get an
280 immediate reminder of any due deadlines.
281 This can also be configured on a per-file basis by adding one of
282 the following lines anywhere in the buffer:
283
284 #+STARTUP: dlcheck
285 #+STARTUP: nodlcheck"
286 :group 'org-startup
287 :type 'boolean)
288
289 (defcustom org-insert-mode-line-in-empty-file nil
290 "Non-nil means insert the first line setting Org-mode in empty files.
291 When the function `org-mode' is called interactively in an empty file, this
292 normally means that the file name does not automatically trigger Org-mode.
293 To ensure that the file will always be in Org-mode in the future, a
294 line enforcing Org-mode will be inserted into the buffer, if this option
295 has been set."
296 :group 'org-startup
297 :type 'boolean)
298
299 (defgroup org-keywords nil
300 "Options concerning TODO items in Org-mode."
301 :tag "Org Keywords"
302 :group 'org)
303
304 (defcustom org-todo-keywords '("TODO" "DONE")
305 "List of TODO entry keywords.
306 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
307 considered to mean that the entry is \"done\". All the other mean that
308 action is required, and will make the entry show up in todo lists, diaries
309 etc.
310 The command \\[org-todo] cycles an entry through these states, and an
311 additional state where no keyword is present. For details about this
312 cycling, see also the variable `org-todo-interpretation'
313 Changes become only effective after restarting Emacs."
314 :group 'org-keywords
315 :type '(repeat (string :tag "Keyword")))
316
317 (defcustom org-todo-interpretation 'sequence
318 "Controls how TODO keywords are interpreted.
319 \\<org-mode-map>Possible values are `sequence' and `type'.
320 This variable is only relevant if `org-todo-keywords' contains more than two
321 states. There are two ways how these keywords can be used:
322
323 - As a sequence in the process of working on a TODO item, for example
324 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
325 org-todo-interpretation 'sequence)
326
327 - As different types of TODO items, for example
328 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
329 org-todo-interpretation 'type)
330
331 When the states are interpreted as a sequence, \\[org-todo] always cycles
332 to the next state, in order to walk through all different states. So with
333 \\[org-todo], you turn an empty entry into the state TODO. When you started
334 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
335 later to VERIFY and finally to DONE.
336
337 When the states are interpreted as types, \\[org-todo] still cycles through
338 when it is called several times in direct succession, in order to initially
339 select the type. However, if not called immediately after a previous
340 \\[org-todo], it switches from each type directly to DONE. So with the
341 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
342 RELAXED. If you later return to this entry and press \\[org-todo] again,
343 RELAXED will not be changed REMIND, but directly to DONE.
344
345 You can create a large number of types. To initially select a
346 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
347 type with completion. Of course, you can also type the keyword
348 directly into the buffer. M-TAB completes TODO keywords at the
349 beginning of a headline."
350 :group 'org-keywords
351 :type '(choice (const sequence)
352 (const type)))
353
354 (defcustom org-default-priority ?B
355 "The default priority of TODO items.
356 This is the priority an item get if no explicit priority is given."
357 :group 'org-keywords
358 :type 'character)
359
360 (defcustom org-lowest-priority ?C
361 "The lowest priority of TODO items. A character like ?A, ?B etc."
362 :group 'org-keywords
363 :type 'character)
364
365 (defcustom org-deadline-string "DEADLINE:"
366 "String to mark deadline entries.
367 A deadline is this string, followed by a time stamp. Should be a word,
368 terminated by a colon. You can insert a schedule keyword and
369 a timestamp with \\[org-deadline].
370 Changes become only effective after restarting Emacs."
371 :group 'org-keywords
372 :type 'string)
373
374 (defcustom org-scheduled-string "SCHEDULED:"
375 "String to mark scheduled TODO entries.
376 A schedule is this string, followed by a time stamp. Should be a word,
377 terminated by a colon. You can insert a schedule keyword and
378 a timestamp with \\[org-schedule].
379 Changes become only effective after restarting Emacs."
380 :group 'org-keywords
381 :type 'string)
382
383 (defcustom org-comment-string "COMMENT"
384 "Entries starting with this keyword will never be exported.
385 An entry can be toggled between COMMENT and normal with
386 \\[org-toggle-comment].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
390
391 (defcustom org-after-todo-state-change-hook nil
392 "Hook which is run after the state of a TODO item was changed.
393 The new state (a string with a todo keyword, or nil) is available in the
394 Lisp variable `state'."
395 :group 'org-keywords
396 :type 'hook)
397
398 ;; Variables for pre-computed regular expressions, all buffer local
399 (defvar org-todo-kwd-priority-p nil
400 "Do TODO items have priorities?")
401 (make-variable-buffer-local 'org-todo-kwd-priority-p)
402 (defvar org-todo-kwd-max-priority nil
403 "Maximum priority of TODO items.")
404 (make-variable-buffer-local 'org-todo-kwd-max-priority)
405 (defvar org-ds-keyword-length 12
406 "Maximum length of the Deadline and SCHEDULED keywords.")
407 (make-variable-buffer-local 'org-ds-keyword-length)
408 (defvar org-done-string nil
409 "The last string in `org-todo-keywords', indicating an item is DONE.")
410 (make-variable-buffer-local 'org-done-string)
411 (defvar org-todo-regexp nil
412 "Matches any of the TODO state keywords.")
413 (make-variable-buffer-local 'org-todo-regexp)
414 (defvar org-not-done-regexp nil
415 "Matches any of the TODO state keywords except the last one.")
416 (make-variable-buffer-local 'org-not-done-regexp)
417 (defvar org-todo-line-regexp nil
418 "Matches a headline and puts TODO state into group 2 if present.")
419 (make-variable-buffer-local 'org-todo-line-regexp)
420 (defvar org-nl-done-regexp nil
421 "Matches newline followed by a headline with the DONE keyword.")
422 (make-variable-buffer-local 'org-nl-done-regexp)
423 (defvar org-looking-at-done-regexp nil
424 "Matches the DONE keyword a point.")
425 (make-variable-buffer-local 'org-looking-at-done-regexp)
426 (defvar org-deadline-regexp nil
427 "Matches the DEADLINE keyword.")
428 (make-variable-buffer-local 'org-deadline-regexp)
429 (defvar org-deadline-time-regexp nil
430 "Matches the DEADLINE keyword together with a time stamp.")
431 (make-variable-buffer-local 'org-deadline-time-regexp)
432 (defvar org-deadline-line-regexp nil
433 "Matches the DEADLINE keyword and the rest of the line.")
434 (make-variable-buffer-local 'org-deadline-line-regexp)
435 (defvar org-scheduled-regexp nil
436 "Matches the SCHEDULED keyword.")
437 (make-variable-buffer-local 'org-scheduled-regexp)
438 (defvar org-scheduled-time-regexp nil
439 "Matches the SCHEDULED keyword together with a time stamp.")
440 (make-variable-buffer-local 'org-scheduled-time-regexp)
441
442 (defvar org-category nil
443 "Variable used by org files to set a category for agenda display.
444 Such files should use a file variable to set it, for example
445
446 -*- mode: org; org-category: \"ELisp\"
447
448 or contain a special line
449
450 #+CATEGORY: ELisp
451
452 If the file does not specify a category, then file's base name
453 is used instead.")
454
455 (defun org-set-regexps-and-options ()
456 "Precompute regular expressions for current buffer."
457 (when (eq major-mode 'org-mode)
458 (let ((re (org-make-options-regexp
459 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
460 "STARTUP" "ARCHIVE")))
461 (splitre "[ \t]+")
462 kwds int key value cat arch)
463 (save-excursion
464 (save-restriction
465 (widen)
466 (goto-char (point-min))
467 (while (re-search-forward re nil t)
468 (setq key (match-string 1) value (match-string 2))
469 (cond
470 ((equal key "CATEGORY")
471 (if (string-match "[ \t]+$" value)
472 (setq value (replace-match "" t t value)))
473 (setq cat (intern value)))
474 ((equal key "SEQ_TODO")
475 (setq int 'sequence
476 kwds (append kwds (org-split-string value splitre))))
477 ((equal key "PRI_TODO")
478 (setq int 'priority
479 kwds (append kwds (org-split-string value splitre))))
480 ((equal key "TYP_TODO")
481 (setq int 'type
482 kwds (append kwds (org-split-string value splitre))))
483 ((equal key "STARTUP")
484 (let ((opts (org-split-string value splitre))
485 (set '(("fold" org-startup-folded t)
486 ("nofold" org-startup-folded nil)
487 ("content" org-startup-folded content)
488 ("dlcheck" org-startup-with-deadline-check t)
489 ("nodlcheck" org-startup-with-deadline-check nil)))
490 l var val)
491 (while (setq l (assoc (pop opts) set))
492 (setq var (nth 1 l) val (nth 2 l))
493 (set (make-local-variable var) val))))
494 ((equal key "ARCHIVE")
495 (string-match " *$" value)
496 (setq arch (replace-match "" t t value))
497 (remove-text-properties 0 (length arch)
498 '(face t fontified t) arch)))
499 )))
500 (and cat (set (make-local-variable 'org-category) cat))
501 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
502 (and arch (set (make-local-variable 'org-archive-location) arch))
503 (and int (set (make-local-variable 'org-todo-interpretation) int)))
504 ;; Compute the regular expressions and other local variables
505 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
506 org-todo-kwd-max-priority (1- (length org-todo-keywords))
507 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
508 (length org-scheduled-string)))
509 org-done-string
510 (nth (1- (length org-todo-keywords)) org-todo-keywords)
511 org-todo-regexp
512 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
513 "\\|") "\\)\\>")
514 org-not-done-regexp
515 (concat "\\<\\("
516 (mapconcat 'regexp-quote
517 (nreverse (cdr (reverse org-todo-keywords)))
518 "\\|")
519 "\\)\\>")
520 org-todo-line-regexp
521 (concat "^\\(\\*+\\)[ \t]*\\("
522 (mapconcat 'regexp-quote org-todo-keywords "\\|")
523 "\\)? *\\(.*\\)")
524 org-nl-done-regexp
525 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
526 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
527 org-deadline-regexp (concat "\\<" org-deadline-string)
528 org-deadline-time-regexp
529 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
530 org-deadline-line-regexp
531 (concat "\\<\\(" org-deadline-string "\\).*")
532 org-scheduled-regexp
533 (concat "\\<" org-scheduled-string)
534 org-scheduled-time-regexp
535 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
536 (org-set-font-lock-defaults)))
537
538 (defgroup org-time nil
539 "Options concerning time stamps and deadlines in Org-mode."
540 :tag "Org Time"
541 :group 'org)
542
543 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
544 "Formats for `format-time-string' which are used for time stamps.
545 It is not recommended to change this constant.")
546
547
548 (defcustom org-deadline-warning-days 30
549 "No. of days before expiration during which a deadline becomes active.
550 This variable governs the display in the org file."
551 :group 'org-time
552 :type 'number)
553
554 (defcustom org-popup-calendar-for-date-prompt t
555 "Non-nil means, pop up a calendar when prompting for a date.
556 In the calendar, the date can be selected with mouse-1. However, the
557 minibuffer will also be active, and you can simply enter the date as well.
558 When nil, only the minibuffer will be available."
559 :group 'org-time
560 :type 'number)
561
562 (defcustom org-calendar-follow-timestamp-change t
563 "Non-nil means, make the calendar window follow timestamp changes.
564 When a timestamp is modified and the calendar window is visible, it will be
565 moved to the new date."
566 :group 'org-time
567 :type 'boolean)
568
569 (defgroup org-agenda nil
570 "Options concerning agenda display Org-mode."
571 :tag "Org Agenda"
572 :group 'org)
573
574 (defcustom org-agenda-files nil
575 "A list of org files for agenda/diary display.
576 Entries are added to this list with \\[org-add-file] and removed with
577 \\[org-remove-file]. You can also use customize to edit the list."
578 :group 'org-agenda
579 :type '(repeat file))
580
581 (defcustom org-select-timeline-window t
582 "Non-nil means, after creating a timeline, move cursor into Timeline window.
583 When nil, cursor will remain in the current window."
584 :group 'org-agenda
585 :type 'boolean)
586
587 (defcustom org-select-agenda-window t
588 "Non-nil means, after creating an agenda, move cursor into Agenda window.
589 When nil, cursor will remain in the current window."
590 :group 'org-agenda
591 :type 'boolean)
592
593 (defcustom org-fit-agenda-window t
594 "Non-nil means, change window size of agenda to fit content."
595 :group 'org-agenda
596 :type 'boolean)
597
598 (defcustom org-agenda-show-all-dates t
599 "Non-nil means, `org-agenda' shows every day in the selected range.
600 When nil, only the days which actually have entries are shown."
601 :group 'org-agenda
602 :type 'boolean)
603
604 ;; FIXME: First day of month works only for current month because it would
605 ;; require a variable ndays treatment.
606 (defcustom org-agenda-start-on-weekday 1
607 "Non-nil means, start the overview always on the specified weekday.
608 0 Denotes Sunday, 1 denotes Monday etc.
609 When nil, always start on the current day."
610 :group 'org-agenda
611 :type '(choice (const :tag "Today" nil)
612 (const :tag "First day of month" t)
613 (number :tag "Weekday No.")))
614
615 (defcustom org-agenda-ndays 7
616 "Number of days to include in overview display."
617 :group 'org-agenda
618 :type 'number)
619
620 (defcustom org-agenda-include-all-todo t
621 "Non-nil means, the agenda will always contain all TODO entries.
622 When nil, date-less entries will only be shown if `org-agenda' is called
623 with a prefix argument.
624 When non-nil, the TODO entries will be listed at the top of the agenda, before
625 the entries for specific days."
626 :group 'org-agenda
627 :type 'boolean)
628
629 (defcustom org-agenda-include-diary nil
630 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
631 :group 'org-agenda
632 :type 'boolean)
633
634 (defcustom org-calendar-to-agenda-key [?c]
635 "The key to be installed in `calendar-mode-map' for switching to the agenda.
636 The command `org-calendar-goto-agenda' will be bound to this key. The
637 default is the character `c' because then`c' can be used to switch back and
638 force between agenda and calendar."
639 :group 'org-agenda
640 :type 'sexp)
641
642 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
643 "Sorting structure for the agenda items of a single day.
644 This is a list of symbols which will be used in sequence to determine
645 if an entry should be listed before another entry. The following
646 symbols are recognized.
647
648 time-up Put entries with time-of-day indications first, early first
649 time-down Put entries with time-of-day indications first, late first
650 category-keep Keep the default order of categories, corresponding to the
651 sequence in `org-agenda-files'.
652 category-up Sort alphabetically by category, A-Z.
653 category-down Sort alphabetically by category, Z-A.
654 priority-up Sort numerically by priority, high priority last.
655 priority-down Sort numerically by priority, high priority first.
656
657 The different possibilities will be tried in sequence, and testing stops
658 if one comparison returns a \"not-equal\". For example, the default
659 '(time-up category-keep priority-down)
660 means: Pull out all entries having a specified time of day and sort them,
661 in order to make a time schedule for the current day the first thing in the
662 agenda listing for the day. Of the entries without a time indication, keep
663 the grouped in categories, don't sort the categories, but keep them in
664 the sequence given in `org-agenda-files'. Within each category sort by
665 priority.
666
667 Leaving out `category-keep' would mean that items will be sorted across
668 categories by priority."
669 :group 'org-agenda
670 :type '(repeat
671 (choice
672 (const time-up)
673 (const time-down)
674 (const category-keep)
675 (const category-up)
676 (const category-down)
677 (const priority-up)
678 (const priority-down))))
679
680 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
681 "Format specification for the prefix of items in the agenda buffer.
682 This format works similar to a printf format, with the following meaning:
683
684 %c the category of the item, \"Diary\" for entries from the diary, or
685 as given by the CATEGORY keyword or derived from the file name.
686 %t the time-of-day specification if one applies to the entry, in the
687 format HH:MM
688 %s Scheduling/Deadline information, a short string
689
690 All specifiers work basically like the standard `%s' of printf, but may
691 contain two additional characters: A question mark just after the `%' and
692 a whitespace/punctuation character just before the final letter.
693
694 If the first character after `%' is a question mark, the entire field
695 will only be included if the corresponding value applies to the
696 current entry. This is useful for fields which should have fixed
697 width when present, but zero width when absent. For example,
698 \"%?-12t\" will result in a 12 character time field if a time of the
699 day is specified, but will completely disappear in entries which do
700 not contain a time.
701
702 If there is punctuation or whitespace character just before the final
703 format letter, this character will be appended to the field value if
704 the value is not empty. For example, the format \"%-12:c\" leads to
705 \"Diary: \" if the category is \"Diary\". If the category were be
706 empty, no additional colon would be interted.
707
708 The default value of this option is \" %-12:c%?-12t% s\", meaning:
709 - Indent the line with two space characters
710 - Give the category in a 12 chars wide field, padded with whitespace on
711 the right (because of `-'). Append a colon if there is a category
712 (because of `:').
713 - If there is a time-of-day, put it into a 12 chars wide field. If no
714 time, don't put in an empty field, just skip it (because of '?').
715 - Finally, put the scheduling information and append a whitespace.
716
717 As another example, if you don't want the time-of-day of entries in
718 the prefix, you could use:
719
720 (setq org-agenda-prefix-format \" %-11:c% s\")
721
722 See also the variable `org-agenda-remove-times-when-in-prefix'."
723 :type 'string
724 :group 'org-agenda)
725
726 (defcustom org-timeline-prefix-format " % s"
727 "Like `org-agenda-prefix-format', but for the timeline of a single file."
728 :type 'string
729 :group 'org-agenda)
730
731 (defvar org-prefix-format-compiled nil
732 "The compiled version of the most recently used prefix format.
733 Depending on which command was used last, this may be the compiled version
734 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
735
736 (defcustom org-agenda-use-time-grid t
737 "Non-nil means, show a time grid in the agenda schedule.
738 A time grid is a set of lines for specific times (like every two hours between
739 8:00 and 20:00. The items scheduled for a day at specific times are
740 sorted in between these lines.
741 For deails about when the grid will be shown, and what it will look like, see
742 the variable `org-agenda-time-grid'."
743 :group 'org-agenda
744 :type 'boolean)
745
746 (defcustom org-agenda-time-grid
747 '((daily today require-timed)
748 "----------------"
749 (800 1000 1200 1400 1600 1800 2000))
750
751 "The settings for time grid for agenda display.
752 This is a list of three items. The first item is again a list. It contains
753 symbols specifying conditions when the grid should be displayed:
754
755 daily if the agenda shows a single day
756 weekly if the agenda shows an entire week
757 today show grid on current date, independent of daily/weekly display
758 require-timed show grid only if at least on item has a time specification
759
760 The second item is a string which will be places behing the grid time.
761
762 The third item is a list of integers, indicating the times that should have
763 a grid line."
764 :group 'org-agenda
765 :type
766 '(list
767 (set :greedy t :tag "Grid Display Options"
768 (const :tag "Show grid in single day agenda display" daily)
769 (const :tag "Show grid in weekly agenda display" weekly)
770 (const :tag "Always show grid for today" today)
771 (const :tag "Show grid only if any timed entries are present"
772 require-timed)
773 (const :tag "Skip grid times already present in an entry"
774 remove-match))
775 (string :tag "Grid String")
776 (repeat :tag "Grid Times" (integer :tag "Time"))))
777
778 (defcustom org-agenda-remove-times-when-in-prefix t
779 "Non-nil means, remove duplicate time specifications in agenda items.
780 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
781 time-of-day specification in a headline or diary entry is extracted and
782 placed into the prefix. If this option is non-nil, the original specification
783 \(a timestamp or -range, or just a plain time(range) specification like
784 11:30-4pm) will be removed for agenda display. This makes the agenda less
785 cluttered.
786 The option can be t or nil. It may also be the symbol `beg', indicating
787 that the time should only be removed what it is located at the beginning of
788 the headline/diary entry."
789 :group 'org-agenda
790 :type '(choice
791 (const :tag "Always" t)
792 (const :tag "Never" nil)
793 (const :tag "When at beginning of entry" beg)))
794
795 (defcustom org-sort-agenda-notime-is-late t
796 "Non-nil means, items without time are considered late.
797 This is only relevant for sorting. When t, items which have no explicit
798 time like 15:30 will be considered as 24:01, i.e. later than any items which
799 do have a time. When nil, the default time is before 0:00. You can use this
800 option to decide if the schedule for today should come before or after timeless
801 agenda entries."
802 :group 'org-agenda
803 :type 'boolean)
804
805 (defgroup org-structure nil
806 "Options concerning structure editing in Org-mode."
807 :tag "Org Structure"
808 :group 'org)
809
810 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
811 "Hook that is run after `org-cycle' has changed the buffer visibility.
812 The function(s) in this hook must accept a single argument which indicates
813 the new state that was set by the most recent `org-cycle' command. The
814 argument is a symbol. After a global state change, it can have the values
815 `overview', `content', or `all'. After a local state change, it can have
816 the values `folded', `children', or `subtree'."
817 :group 'org-structure
818 :type 'hook)
819
820 (defcustom org-occur-hook '(org-first-headline-recenter)
821 "Hook that is run after `org-occur' has constructed a sparse tree.
822 This can be used to recenter the window to show as much of the structure
823 as possible."
824 :group 'org-structure
825 :type 'hook)
826
827 (defcustom org-adapt-indentation t
828 "Non-nil means, adapt indentation when promoting and demoting.
829 When this is set and the *entire* text in an entry is indented, the
830 indentation is increased by one space in a demotion command, and
831 decreased by one in a promotion command. If any line in the entry
832 body starts at column 0, indentation is not changed at all."
833 :group 'org-structure
834 :type 'boolean)
835
836 (defcustom org-cycle-emulate-tab t
837 "Where should `org-cycle' emulate TAB.
838 nil Never
839 white Only in completely white lines
840 t Everywhere except in headlines"
841 :group 'org-structure
842 :type '(choice (const :tag "Never" nil)
843 (const :tag "Only in completely white lines" white)
844 (const :tag "Everywhere except in headlines" t)
845 ))
846
847 (defcustom org-show-following-heading t
848 "Non-nil means, show heading following match in `org-occur'.
849 When doing an `org-occur' it is useful to show the headline which
850 follows the match, even if they do not match the regexp. This makes it
851 easier to edit directly inside the sparse tree. However, if you use
852 org-occur mainly as an overview, the following headlines are
853 unnecessary clutter."
854 :group 'org-structure
855 :type 'boolean)
856
857 (defcustom org-archive-location "%s_archive::"
858 "The location where subtrees should be archived.
859 This string consists of two parts, separated by a double-colon.
860
861 The first part is a file name - when omitted, archiving happens in the same
862 file. %s will be replaced by the current file name (without directory part).
863 Archiving to a different file is useful to keep archived entries from
864 contributing to the Org-mode Agenda.
865
866 The part after the double colon is a headline. The archived entries will be
867 filed under that headline. When omitted, the subtrees are simply filed away
868 at the end of the file, as top-level entries.
869
870 Here are a few examples:
871 \"%s_archive::\"
872 If the current file is Projects.org, archive in file
873 Projects.org_archive, as top-level trees. This is the default.
874
875 \"::* Archived Tasks\"
876 Archive in the current file, under the top-level headline
877 \"* Archived Tasks\".
878
879 \"~/org/archive.org::\"
880 Archive in file ~/org/archive.org (absolute path), as top-level trees.
881
882 \"basement::** Finished Tasks\"
883 Archive in file ./basement (relative path), as level 3 trees
884 below the level 2 heading \"** Finished Tasks\".
885
886 You may set this option on a per-file basis by adding to the buffer a
887 line like
888
889 #+ARCHIVE: basement::** Finished Tasks"
890 :group 'org-structure
891 :type 'string)
892
893 (defcustom org-archive-mark-done t
894 "Non-nil means, mark archived entries as DONE."
895 :group 'org-structure
896 :type 'boolean)
897
898 (defcustom org-archive-stamp-time t
899 "Non-nil means, add a time stamp to archived entries.
900 The time stamp will be added directly after the TODO state keyword in the
901 first line, so it is probably best to use this in combinations with
902 `org-archive-mark-done'."
903 :group 'org-structure
904 :type 'boolean)
905
906 (defgroup org-link nil
907 "Options concerning links in Org-mode."
908 :tag "Org Link"
909 :group 'org)
910
911 (defcustom org-link-format "<%s>"
912 "Default format for linkes in the buffer.
913 This is a format string for printf, %s will be replaced by the link text.
914 If you want to make sure that your link is always properly terminated,
915 include angle brackets into this format, like \"<%s>\". Some people also
916 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
917 :group 'org-link
918 :type '(choice
919 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
920 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
921 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
922 (string :tag "Other" :value "<%s>")))
923
924 (defcustom org-allow-space-in-links t
925 "Non-nil means, file names in links may contain space characters.
926 When nil, it becomes possible to put several links into a line.
927 Note that in tables, a link never extends accross fields, so in a table
928 it is always possible to put several links into a line.
929 Changing this varable requires a re-launch of Emacs of become effective."
930 :group 'org-link
931 :type 'boolean)
932
933 (defcustom org-line-numbers-in-file-links t
934 "Non-nil means, file links from `org-store-link' contain line numbers.
935 The line number will be added to the file name with :NNN and interpreted
936 by the command `org-open-at-point'.
937 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
938 negates this setting for the duration of the command."
939 :group 'org-link
940 :type 'boolean)
941
942 (defcustom org-keep-stored-link-after-insertion nil
943 "Non-nil means, keep link in list for entire session.
944
945 The command `org-store-link' adds a link pointing to the current
946 location to an internal list. These links accumulate during a session.
947 The command `org-insert-link' can be used to insert links into any
948 Org-mode file (offering completion for all stored links). When this
949 option is nil, every link which has been inserted once using \\[org-insert-link]
950 will be removed from the list, to make completing the unused links
951 more efficient."
952 :group 'org-link
953 :type 'boolean)
954
955 (defcustom org-link-frame-setup
956 '((vm . vm-visit-folder-other-frame)
957 (gnus . gnus-other-frame)
958 (file . find-file-other-window))
959 "Setup the frame configuration for following links.
960 When following a link with Emacs, it may often be useful to display
961 this link in another window or frame. This variable can be used to
962 set this up for the different types of links.
963 For VM, use any of
964 `vm-visit-folder'
965 `vm-visit-folder-other-frame'
966 For Gnus, use any of
967 `gnus'
968 `gnus-other-frame'
969 For FILE, use any of
970 `find-file'
971 `find-file-other-window'
972 `find-file-other-frame'
973 For the calendar, use the variable `calendar-setup'.
974 For BBDB, it is currently only possible to display the matches in
975 another window."
976 :group 'org-link
977 :type '(list
978 (cons (const vm)
979 (choice
980 (const vm-visit-folder)
981 (const vm-visit-folder-other-window)
982 (const vm-visit-folder-other-frame)))
983 (cons (const gnus)
984 (choice
985 (const gnus)
986 (const gnus-other-frame)))
987 (cons (const file)
988 (choice
989 (const find-file)
990 (const find-file-other-window)
991 (const find-file-other-frame)))))
992
993 (defcustom org-usenet-links-prefer-google nil
994 "Non-nil means, `org-store-link' will create web links to google groups.
995 When nil, Gnus will be used for such links.
996 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
997 negates this setting for the duration of the command."
998 :group 'org-link
999 :type 'boolean)
1000
1001 (defcustom org-open-non-existing-files nil
1002 "Non-nil means, `org-open-file' will open non-existing file.
1003 When nil, an error will be generated."
1004 :group 'org-link
1005 :type 'boolean)
1006
1007 (defcustom org-confirm-shell-links t
1008 "Non-nil means, ask for confirmation before executing shell links.
1009 The default is true, to keep new users from shooting into their own foot."
1010 :group 'org-link
1011 :type 'boolean)
1012
1013 (defconst org-file-apps-defaults-gnu
1014 '((t . emacs)
1015 ("jpg" . "xv %s")
1016 ("gif" . "xv %s")
1017 ("ppm" . "xv %s")
1018 ("pgm" . "xv %s")
1019 ("pbm" . "xv %s")
1020 ("tif" . "xv %s")
1021 ("png" . "xv %s")
1022 ("ps" . "gv %s")
1023 ("ps.gz" . "gv %s")
1024 ("eps" . "gv %s")
1025 ("eps.gz" . "gv %s")
1026 ("dvi" . "xdvi %s")
1027 ("mpeg" . "plaympeg %s")
1028 ("mp3" . "plaympeg %s")
1029 ("fig" . "xfig %s")
1030 ("pdf" . "acroread %s")
1031 ("doc" . "soffice %s")
1032 ("ppt" . "soffice %s")
1033 ("pps" . "soffice %s")
1034 ("html" . "netscape -remote openURL(%s,new-window)")
1035 ("htm" . "netscape -remote openURL(%s,new-window)")
1036 ("xs" . "soffice %s"))
1037 "Default file applications on a UNIX/LINUX system.
1038 See `org-file-apps'.")
1039
1040 (defconst org-file-apps-defaults-macosx
1041 '((t . "open %s")
1042 ("ps" . "gv %s")
1043 ("ps.gz" . "gv %s")
1044 ("eps" . "gv %s")
1045 ("eps.gz" . "gv %s")
1046 ("dvi" . "xdvi %s")
1047 ("fig" . "xfig %s"))
1048 "Default file applications on a MacOS X system.
1049 The system \"open\" is known as a default, but we use X11 applications
1050 for some files for which the OS does not have a good default.
1051 See `org-file-apps'.")
1052
1053 (defconst org-file-apps-defaults-windowsnt
1054 '((t . (w32-shell-execute "open" file)))
1055 "Default file applications on a Windows NT system.
1056 The system \"open\" is used for most files.
1057 See `org-file-apps'.")
1058
1059 (defcustom org-file-apps
1060 '(
1061 ("txt" . emacs)
1062 ("tex" . emacs)
1063 ("ltx" . emacs)
1064 ("org" . emacs)
1065 ("el" . emacs)
1066 )
1067 "External applications for opening `file:path' items in a document.
1068 Org-mode uses system defaults for different file types, but
1069 you can use this variable to set the application for a given file
1070 extension. The entries in this list are cons cells with a file extension
1071 and the corresponding command. Possible values for the command are:
1072 `emacs' The file will be visited by the current Emacs process.
1073 `default' Use the default application for this file type.
1074 string A command to be executed by a shell; %s will be replaced
1075 by the path to the file.
1076 sexp A Lisp form which will be evaluated. The file path will
1077 be available in the Lisp variable `file'.
1078 For more examples, see the system specific constants
1079 `org-file-apps-defaults-macosx'
1080 `org-file-apps-defaults-windowsnt'
1081 `org-file-apps-defaults-gnu'."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons (string :tag "Extension")
1085 (choice :value ""
1086 (const :tag "Visit with Emacs" 'emacs)
1087 (const :tag "Use system default" 'default)
1088 (string :tag "Command")
1089 (sexp :tag "Lisp form")))))
1090
1091
1092 (defgroup org-remember nil
1093 "Options concerning interaction with remember.el."
1094 :tag "Org Remember"
1095 :group 'org)
1096
1097 (defcustom org-directory "~/org"
1098 "Directory with org files.
1099 This directory will be used as default to prompt for org files.
1100 Used by the hooks for remember.el."
1101 :group 'org-remember
1102 :type 'directory)
1103
1104 (defcustom org-default-notes-file "~/.notes"
1105 "Default target for storing notes.
1106 Used by the hooks for remember.el. This can be a string, or nil to mean
1107 the value of `remember-data-file'."
1108 :group 'org-remember
1109 :type '(choice
1110 (const :tag "Default from remember-data-file" nil)
1111 file))
1112
1113 (defcustom org-reverse-note-order nil
1114 "Non-nil means, store new notes at the beginning of a file or entry.
1115 When nil, new notes will be filed to the end of a file or entry."
1116 :group 'org-remember
1117 :type '(choice
1118 (const :tag "Reverse always" t)
1119 (const :tag "Reverse never" nil)
1120 (repeat :tag "By file name regexp"
1121 (cons regexp boolean))))
1122
1123 (defgroup org-table nil
1124 "Options concerning tables in Org-mode."
1125 :tag "Org Table"
1126 :group 'org)
1127
1128 (defcustom org-enable-table-editor 'optimized
1129 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1130 When nil, such lines will be treated like ordinary lines.
1131
1132 When equal to the symbol `optimized', the table editor will be optimized to
1133 do the following
1134 - Use automatic overwrite mode in front of whitespace in table fields.
1135 This make the structure of the table stay in tact as long as the edited
1136 field does not exceed the column width.
1137 - Minimize the number of realigns. Normally, the table is aligned each time
1138 TAB or RET are pressed to move to another field. With optimization this
1139 happens only if changes to a field might have changed the column width.
1140 Optimization requires replacing the functions `self-insert-command',
1141 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1142 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1143 very good at guessing when a re-align will be necessary, but you can always
1144 force one with `C-c C-c'.
1145
1146 If you would like to use the optimized version in Org-mode, but the
1147 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1148
1149 This variable can be used to turn on and off the table editor during a session,
1150 but in order to toggle optimization, a restart is required."
1151 :group 'org-table
1152 :type '(choice
1153 (const :tag "off" nil)
1154 (const :tag "on" t)
1155 (const :tag "on, optimized" optimized)))
1156
1157 (defcustom org-table-default-size "5x2"
1158 "The default size for newly created tables, Columns x Rows."
1159 :group 'org-table
1160 :type 'string)
1161
1162 (defcustom org-table-automatic-realign t
1163 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1164 When nil, aligning is only done with \\[org-table-align], or after column
1165 removal/insertion."
1166 :group 'org-table
1167 :type 'boolean)
1168
1169 (defcustom org-table-spaces-around-separators '(1 . 1)
1170 "The number of spaces to be placed before and after separators."
1171 :group 'org-table
1172 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1173
1174 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1175 "The number of spaces to be placed before and after separators.
1176 This option applies when the column separators have been made invisible."
1177 :group 'org-table
1178 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1179
1180 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1181 "Regular expression for recognizing numbers in table columns.
1182 If a table column contains mostly numbers, it will be aligned to the
1183 right. If not, it will be aligned to the left.
1184
1185 The default value of this option is a regular expression which allows
1186 anything which looks remotely like a number as used in scientific
1187 context. For example, all of the following will be considered a
1188 number:
1189 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1190
1191 Other options offered by the customize interface are more restrictive."
1192 :group 'org-table
1193 :type '(choice
1194 (const :tag "Positive Integers"
1195 "^[0-9]+$")
1196 (const :tag "Integers"
1197 "^[-+]?[0-9]+$")
1198 (const :tag "Floating Point Numbers"
1199 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1200 (const :tag "Floating Point Number or Integer"
1201 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1202 (const :tag "Exponential, Floating point, Integer"
1203 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1204 (const :tag "Very General Number-Like"
1205 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1206 (string :tag "Regexp:")))
1207
1208 (defcustom org-table-number-fraction 0.5
1209 "Fraction of numbers in a column required to make the column align right.
1210 In a column all non-white fields are considered. If at least this
1211 fraction of fields is matched by `org-table-number-fraction',
1212 alignment to the right border applies."
1213 :group 'org-table
1214 :type 'number)
1215
1216 (defcustom org-export-highlight-first-table-line t
1217 "Non-nil means, highlight the first table line.
1218 In HTML export, this means use <th> instead of <td>.
1219 In tables created with table.el, this applies to the first table line.
1220 In Org-mode tables, all lines before the first horizontal separator
1221 line will be formatted with <th> tags."
1222 :group 'org-table
1223 :type 'boolean)
1224
1225 (defcustom org-table-tab-recognizes-table.el t
1226 "Non-nil means, TAB will automatically notice a table.el table.
1227 When it sees such a table, it moves point into it and - if necessary -
1228 calls `table-recognize-table'."
1229 :group 'org-table
1230 :type 'boolean)
1231
1232 ;; FIXME: Should this one be in another group? Which one?
1233 (defcustom org-enable-fixed-width-editor t
1234 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1235 This currently only means, they are never auto-wrapped.
1236 When nil, such lines will be treated like ordinary lines."
1237 :group 'org-table
1238 :type 'boolean)
1239
1240 (defgroup org-table-calculation nil
1241 "Options concerning tables in Org-mode."
1242 :tag "Org Table Calculation"
1243 :group 'org)
1244
1245 (defcustom org-table-copy-increment t
1246 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1247 :group 'org-table-calculation
1248 :type 'boolean)
1249
1250 (defcustom org-calc-default-modes
1251 '(calc-internal-prec 12
1252 calc-float-format (float 5)
1253 calc-angle-mode deg
1254 calc-prefer-frac nil
1255 calc-symbolic-mode nil
1256 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1257 calc-display-working-message t
1258 )
1259 "List with Calc mode settings for use in calc-eval for table formulas.
1260 The list must contain alternating symbols (calc modes variables and values.
1261 Don't remove any of the default settings, just change the values. Org-mode
1262 relies on the variables to be present in the list."
1263 :group 'org-table-calculation
1264 :type 'plist)
1265
1266 (defcustom org-table-formula-evaluate-inline t
1267 "Non-nil means, TAB and RET evaluate a formula in current table field.
1268 If the current field starts with an equal sign, it is assumed to be a formula
1269 which should be evaluated as described in the manual and in the documentation
1270 string of the command `org-table-eval-formula'. This feature requires the
1271 Emacs calc package.
1272 When this variable is nil, formula calculation is only available through
1273 the command \\[org-table-eval-formula]."
1274 :group 'org-table-calculation
1275 :type 'boolean)
1276
1277
1278 (defcustom org-table-formula-use-constants t
1279 "Non-nil means, interpret constants in formulas in tables.
1280 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1281 by the value given in `org-table-formula-constants', or by a value obtained
1282 from the `constants.el' package."
1283 :group 'org-table-calculation
1284 :type 'boolean)
1285
1286 (defcustom org-table-formula-constants nil
1287 "Alist with constant names and values, for use in table formulas.
1288 The car of each element is a name of a constant, without the `$' before it.
1289 The cdr is the value as a string. For example, if you'd like to use the
1290 speed of light in a formula, you would configure
1291
1292 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1293
1294 and then use it in an equation like `$1*$c'."
1295 :group 'org-table-calculation
1296 :type '(repeat
1297 (cons (string :tag "name")
1298 (string :tag "value"))))
1299
1300 (defcustom org-table-formula-numbers-only nil
1301 "Non-nil means, calculate only with numbers in table formulas.
1302 Then all input fields will be converted to a number, and the result
1303 must also be a number. When nil, calc's full potential is available
1304 in table calculations, including symbolics etc."
1305 :group 'org-table-calculation
1306 :type 'boolean)
1307
1308 (defcustom org-table-allow-automatic-line-recalculation t
1309 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1310 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1311 :group 'org-table-calculation
1312 :type 'boolean)
1313
1314 (defgroup org-export nil
1315 "Options for exporting org-listings."
1316 :tag "Org Export"
1317 :group 'org)
1318
1319 (defcustom org-export-language-setup
1320 '(("en" "Author" "Date" "Table of Contents")
1321 ("da" "Ophavsmand" "Dato" "Indhold")
1322 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1323 ("es" "Autor" "Fecha" "\xccndice")
1324 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1325 ("it" "Autore" "Data" "Indice")
1326 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1327 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1328 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1329 "Terms used in export text, translated to different languages.
1330 Use the variable `org-export-default-language' to set the language,
1331 or use the +OPTION lines for a per-file setting."
1332 :group 'org-export
1333 :type '(repeat
1334 (list
1335 (string :tag "HTML language tag")
1336 (string :tag "Author")
1337 (string :tag "Date")
1338 (string :tag "Table of Contents"))))
1339
1340 (defcustom org-export-default-language "en"
1341 "The default language of HTML export, as a string.
1342 This should have an association in `org-export-language-setup'"
1343 :group 'org-export
1344 :type 'string)
1345
1346 (defcustom org-export-headline-levels 3
1347 "The last level which is still exported as a headline.
1348 Inferior levels will produce itemize lists when exported.
1349 Note that a numeric prefix argument to an exporter function overrides
1350 this setting.
1351
1352 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1353 :group 'org-export
1354 :type 'number)
1355
1356 (defcustom org-export-with-section-numbers t
1357 "Non-nil means, add section numbers to headlines when exporting.
1358
1359 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1360 :group 'org-export
1361 :type 'boolean)
1362
1363 (defcustom org-export-with-toc t
1364 "Non-nil means, create a table of contents in exported files.
1365 The TOC contains headlines with levels up to`org-export-headline-levels'.
1366
1367 Headlines which contain any TODO items will be marked with \"(*)\" in
1368 ASCII export, and with red color in HTML output.
1369
1370 In HTML output, the TOC will be clickable.
1371
1372 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1373 :group 'org-export
1374 :type 'boolean)
1375
1376 (defcustom org-export-preserve-breaks nil
1377 "Non-nil means, preserve all line breaks when exporting.
1378 Normally, in HTML output paragraphs will be reformatted. In ASCII
1379 export, line breaks will always be preserved, regardless of this variable.
1380
1381 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1382 :group 'org-export
1383 :type 'boolean)
1384
1385 (defcustom org-export-html-inline-images t
1386 "Non-nil means, inline images into exported HTML pages.
1387 The link will still be to the original location of the image file.
1388 So if you are moving the page, lets say to your public HTML site,
1389 you will have to move the image and maybe change the link."
1390 :group 'org-export
1391 :type 'boolean)
1392
1393 (defcustom org-export-html-expand t
1394 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1395 When nil, these tags will be exported as plain text and therefore
1396 not be interpreted by a browser.
1397
1398 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1399 :group 'org-export
1400 :type 'boolean)
1401
1402 (defcustom org-export-with-fixed-width t
1403 "Non-nil means, lines starting with \":\" will be in fixed width font.
1404 This can be used to have pre-formatted text, fragments of code etc. For
1405 example
1406 : ;; Some Lisp examples
1407 : (while (defc cnt)
1408 : (ding))
1409 will be looking just like this in also HTML. In ASCII export, this option
1410 has no effect.
1411
1412 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1413 :group 'org-export
1414 :type 'boolean)
1415
1416 (defcustom org-export-with-tables t
1417 "If non-nil, lines starting with \"|\" define a table.
1418 For example:
1419
1420 | Name | Address | Birthday |
1421 |-------------+----------+-----------|
1422 | Arthur Dent | England | 29.2.2100 |
1423
1424 In ASCII export, this option has no effect.
1425
1426 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1427 :group 'org-export
1428 :type 'boolean)
1429
1430 (defcustom org-export-prefer-native-exporter-for-tables nil
1431 "Non-nil means, always export tables created with table.el natively.
1432 Natively means, use the HTML code generator in table.el.
1433 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1434 the table does not use row- or column-spanning). This has the
1435 advantage, that the automatic HTML conversions for math symbols and
1436 sub/superscripts can be applied. Org-mode's HTML generator is also
1437 much faster."
1438 :group 'org-export
1439 :type 'boolean)
1440
1441 (defcustom org-export-html-table-tag
1442 "<table border=1 cellspacing=0 cellpadding=6>"
1443 "The HTML tag used to start a table.
1444 This must be a <table> tag, but you may change the options like
1445 borders and spacing."
1446 :group 'org-export
1447 :type 'string)
1448
1449 (defcustom org-export-with-emphasize t
1450 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1451 If the export target supports emphasizing text, the word will be
1452 typeset in bold, italic, or underlined, respectively. Works only for
1453 single words, but you can say: I *really* *mean* *this*.
1454 In ASCII export, this option has no effect.
1455
1456 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1457 :group 'org-export
1458 :type 'boolean)
1459
1460 (defcustom org-match-sexp-depth 3
1461 "Number of stacked braces for sub/superscript matching.
1462 This has to be set before loading org.el to be effective."
1463 :group 'org-export
1464 :type 'integer)
1465
1466 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1467 (defcustom org-export-with-sub-superscripts t
1468 "Non-nil means, interpret \"_\" and \"^\" for export.
1469 When this option is turned on, you can use TeX-like syntax for sub- and
1470 superscripts. Several characters after \"_\" or \"^\" will be
1471 considered as a single item - so grouping with {} is normally not
1472 needed. For example, the following things will be parsed as single
1473 sub- or superscripts.
1474
1475 10^24 or 10^tau several digits will be considered 1 item
1476 10^-12 or 10^-tau a leading sign with digits or a word
1477 x^2-y^3 will be read as x^2 - y^3, because items are
1478 terminated by almost any nonword/nondigit char.
1479 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1480
1481 Still, ambiguity is possible - so when in doubt use {} to enclose the
1482 sub/superscript.
1483 In ASCII export, this option has no effect.
1484
1485 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1486 :group 'org-export
1487 :type 'boolean)
1488
1489 (defcustom org-export-with-TeX-macros t
1490 "Non-nil means, interpret simple TeX-like macros when exporting.
1491 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1492 No only real TeX macros will work here, but the standard HTML entities
1493 for math can be used as macro names as well. For a list of supported
1494 names in HTML export, see the constant `org-html-entities'.
1495 In ASCII export, this option has no effect.
1496
1497 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1498 :group 'org-export
1499 :type 'boolean)
1500
1501 (defcustom org-export-html-with-timestamp nil
1502 "If non-nil, write `org-export-html-html-helper-timestamp'
1503 into the exported html text. Otherwise, the buffer will just be saved
1504 to a file."
1505 :group 'org-export
1506 :type 'boolean)
1507
1508 (defcustom org-export-html-html-helper-timestamp
1509 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1510 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1511 :group 'org-export
1512 :type 'string)
1513
1514 (defcustom org-export-ascii-show-new-buffer t
1515 "Non-nil means, popup buffer containing the exported ASCII text.
1516 Otherwise the buffer will just be saved to a file and stay hidden."
1517 :group 'org-export
1518 :type 'boolean)
1519
1520 (defcustom org-export-html-show-new-buffer nil
1521 "Non-nil means, popup buffer containing the exported html text.
1522 Otherwise, the buffer will just be saved to a file and stay hidden."
1523 :group 'org-export
1524 :type 'boolean)
1525
1526 (defgroup org-faces nil
1527 "Faces for highlighting in Org-mode."
1528 :tag "Org Faces"
1529 :group 'org)
1530
1531 (defface org-level-1 ;; font-lock-function-name-face
1532 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1533 (((class color) (background light)) (:foreground "Blue"))
1534 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1535 (t (:inverse-video t :bold t)))
1536 "Face used for level 1 headlines."
1537 :group 'org-faces)
1538
1539 (defface org-level-2 ;; font-lock-variable-name-face
1540 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1541 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1542 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1543 (t (:bold t :italic t)))
1544 "Face used for level 2 headlines."
1545 :group 'org-faces)
1546
1547 (defface org-level-3 ;; font-lock-keyword-face
1548 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1549 (((class color) (background light)) (:foreground "Purple"))
1550 (((class color) (background dark)) (:foreground "Cyan"))
1551 (t (:bold t)))
1552 "Face used for level 3 headlines."
1553 :group 'org-faces)
1554
1555 (defface org-level-4 ;; font-lock-comment-face
1556 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1557 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1558 (((class color) (background light)) (:foreground "Firebrick"))
1559 (((class color) (background dark)) (:foreground "chocolate1"))
1560 (t (:bold t :italic t)))
1561 "Face used for level 4 headlines."
1562 :group 'org-faces)
1563
1564 (defface org-level-5 ;; font-lock-type-face
1565 '((((type tty) (class color)) (:foreground "green"))
1566 (((class color) (background light)) (:foreground "ForestGreen"))
1567 (((class color) (background dark)) (:foreground "PaleGreen"))
1568 (t (:bold t :underline t)))
1569 "Face used for level 5 headlines."
1570 :group 'org-faces)
1571
1572 (defface org-level-6 ;; font-lock-constant-face
1573 '((((type tty) (class color)) (:foreground "magenta"))
1574 (((class color) (background light)) (:foreground "CadetBlue"))
1575 (((class color) (background dark)) (:foreground "Aquamarine"))
1576 (t (:bold t :underline t)))
1577 "Face used for level 6 headlines."
1578 :group 'org-faces)
1579
1580 (defface org-level-7 ;; font-lock-builtin-face
1581 '((((type tty) (class color)) (:foreground "blue" :weight light))
1582 (((class color) (background light)) (:foreground "Orchid"))
1583 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1584 (t (:bold t)))
1585 "Face used for level 7 headlines."
1586 :group 'org-faces)
1587
1588 (defface org-level-8 ;; font-lock-string-face
1589 '((((type tty) (class color)) (:foreground "green"))
1590 (((class color) (background light)) (:foreground "RosyBrown"))
1591 (((class color) (background dark)) (:foreground "LightSalmon"))
1592 (t (:italic t)))
1593 "Face used for level 8 headlines."
1594 :group 'org-faces)
1595
1596 (defface org-warning ;; font-lock-warning-face
1597 '((((type tty) (class color)) (:foreground "red"))
1598 (((class color) (background light)) (:foreground "Red" :bold t))
1599 (((class color) (background dark)) (:foreground "Red1" :bold t))
1600 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1601 (t (:inverse-video t :bold t)))
1602 "Face for deadlines and TODO keywords."
1603 :group 'org-faces)
1604
1605 (defcustom org-fontify-done-headline nil
1606 "Non-nil means, change the face of a headline if it is marked DONE.
1607 Normally, only the TODO/DONE keyword indicates the state of a headline.
1608 When this is non-nil, the headline after the keyword is set to the
1609 `org-headline-done' as an additional indication."
1610 :group 'org-faces
1611 :type 'boolean)
1612
1613 (defface org-headline-done ;; font-lock-string-face
1614 '((((type tty) (class color)) (:foreground "green"))
1615 (((class color) (background light)) (:foreground "RosyBrown"))
1616 (((class color) (background dark)) (:foreground "LightSalmon"))
1617 (t (:italic t)))
1618 "Face used to indicate that a headline is DONE. See also the variable
1619 `org-fontify-done-headline'."
1620 :group 'org-faces)
1621
1622 ;; Inheritance does not yet work for xemacs. So we just copy...
1623
1624 (defface org-deadline-announce
1625 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1626 (((class color) (background light)) (:foreground "Blue"))
1627 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1628 (t (:inverse-video t :bold t)))
1629 "Face for upcoming deadlines."
1630 :group 'org-faces)
1631
1632 (defface org-scheduled-today
1633 '((((type tty) (class color)) (:foreground "green"))
1634 (((class color) (background light)) (:foreground "DarkGreen"))
1635 (((class color) (background dark)) (:foreground "PaleGreen"))
1636 (t (:bold t :underline t)))
1637 "Face for items scheduled for a certain day."
1638 :group 'org-faces)
1639
1640 (defface org-scheduled-previously
1641 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1642 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1643 (((class color) (background light)) (:foreground "Firebrick"))
1644 (((class color) (background dark)) (:foreground "chocolate1"))
1645 (t (:bold t :italic t)))
1646 "Face for items scheduled previously, and not yet done."
1647 :group 'org-faces)
1648
1649 (defface org-formula
1650 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1651 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1652 (((class color) (background light)) (:foreground "Firebrick"))
1653 (((class color) (background dark)) (:foreground "chocolate1"))
1654 (t (:bold t :italic t)))
1655 "Face for items scheduled previously, and not yet done."
1656 :group 'org-faces)
1657
1658 (defface org-link
1659 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1660 (((class color) (background light)) (:foreground "Purple"))
1661 (((class color) (background dark)) (:foreground "Cyan"))
1662 (t (:bold t)))
1663 "Face for links."
1664 :group 'org-faces)
1665
1666 (defface org-done ;; font-lock-type-face
1667 '((((type tty) (class color)) (:foreground "green"))
1668 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1669 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1670 (t (:bold t :underline t)))
1671 "Face used for DONE."
1672 :group 'org-faces)
1673
1674 (defface org-table ;; font-lock-function-name-face
1675 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1676 (((class color) (background light)) (:foreground "Blue"))
1677 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1678 (t (:inverse-video t :bold t)))
1679 "Face used for tables."
1680 :group 'org-faces)
1681
1682 (defface org-time-grid ;; font-lock-variable-name-face
1683 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1684 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1685 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1686 (t (:bold t :italic t)))
1687 "Face used for level 2 headlines."
1688 :group 'org-faces)
1689
1690 (defvar org-level-faces
1691 '(
1692 org-level-1
1693 org-level-2
1694 org-level-3
1695 org-level-4
1696 org-level-5
1697 org-level-6
1698 org-level-7
1699 org-level-8
1700 ))
1701 (defvar org-n-levels (length org-level-faces))
1702
1703 ;; Tell the compiler about dynamically scoped variables,
1704 ;; and variables from other packages
1705 (eval-when-compile
1706 (defvar zmacs-regions)
1707 (defvar original-date)
1708 (defvar org-transient-mark-mode)
1709 (defvar org-old-auto-fill-inhibit-regexp)
1710 (defvar orgtbl-mode-menu)
1711 (defvar org-html-entities)
1712 (defvar org-goto-start-pos)
1713 (defvar org-cursor-color)
1714 (defvar org-time-was-given)
1715 (defvar org-ts-what)
1716 (defvar mark-active)
1717 (defvar timecnt)
1718 (defvar levels-open)
1719 (defvar title)
1720 (defvar author)
1721 (defvar email)
1722 (defvar text)
1723 (defvar entry)
1724 (defvar date)
1725 (defvar language)
1726 (defvar options)
1727 (defvar ans1)
1728 (defvar ans2)
1729 (defvar starting-day)
1730 (defvar include-all-loc)
1731 (defvar vm-message-pointer)
1732 (defvar vm-folder-directory)
1733 (defvar wl-summary-buffer-elmo-folder)
1734 (defvar wl-summary-buffer-folder-name)
1735 (defvar gnus-group-name)
1736 (defvar gnus-article-current)
1737 (defvar w3m-current-url)
1738 (defvar org-selected-point)
1739 (defvar calendar-mode-map)
1740 (defvar remember-save-after-remembering)
1741 (defvar remember-data-file))
1742
1743
1744 ;;; Define the mode
1745
1746 (defvar org-mode-map (copy-keymap outline-mode-map)
1747 "Keymap for Org-mode.")
1748
1749 (defvar org-struct-menu)
1750 (defvar org-org-menu)
1751 (defvar org-tbl-menu)
1752
1753 ;; We use a before-change function to check if a table might need
1754 ;; an update.
1755 (defvar org-table-may-need-update t
1756 "Indicates of a table might need an update.
1757 This variable is set by `org-before-change-function'. `org-table-align'
1758 sets it back to nil.")
1759 (defvar org-mode-hook nil)
1760 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1761
1762
1763 ;;;###autoload
1764 (define-derived-mode org-mode outline-mode "Org"
1765 "Outline-based notes management and organizer, alias
1766 \"Carstens outline-mode for keeping track of everything.\"
1767
1768 Org-mode develops organizational tasks around a NOTES file which
1769 contains information about projects as plain text. Org-mode is
1770 implemented on top of outline-mode, which is ideal to keep the content
1771 of large files well structured. It supports ToDo items, deadlines and
1772 time stamps, which magically appear in the diary listing of the Emacs
1773 calendar. Tables are easily created with a built-in table editor.
1774 Plain text URL-like links connect to websites, emails (VM), Usenet
1775 messages (Gnus), BBDB entries, and any files related to the project.
1776 For printing and sharing of notes, an Org-mode file (or a part of it)
1777 can be exported as a structured ASCII or HTML file.
1778
1779 The following commands are available:
1780
1781 \\{org-mode-map}"
1782 (easy-menu-add org-org-menu)
1783 (easy-menu-add org-tbl-menu)
1784 (org-install-agenda-files-menu)
1785 (setq outline-regexp "\\*+")
1786 (if org-startup-truncated (setq truncate-lines t))
1787 (org-set-regexps-and-options)
1788 (set (make-local-variable 'font-lock-unfontify-region-function)
1789 'org-unfontify-region)
1790 ;; Activate before-change-function
1791 (set (make-local-variable 'org-table-may-need-update) t)
1792 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1793 (add-hook 'before-change-functions 'org-before-change-function nil
1794 'local)
1795 ;; Paragraph regular expressions
1796 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1797 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1798 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1799 (set (make-local-variable 'auto-fill-inhibit-regexp)
1800 (concat "\\*\\|#"
1801 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1802 (concat
1803 "\\|[ \t]*["
1804 (if org-enable-table-editor "|" "")
1805 (if org-enable-fixed-width-editor ":" "")
1806 "]"))))
1807 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1808 ;; Settings for Calc embedded mode
1809 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1810 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1811 (if (and org-insert-mode-line-in-empty-file
1812 (interactive-p)
1813 (= (point-min) (point-max)))
1814 (insert " -*- mode: org -*-\n\n"))
1815
1816 ;; Get rid of Outline menus, they are not needed
1817 ;; Need to do this here because define-derived-mode sets up
1818 ;; the keymap so late.
1819 (if org-xemacs-p
1820 (progn
1821 (delete-menu-item '("Headings"))
1822 (delete-menu-item '("Show"))
1823 (delete-menu-item '("Hide"))
1824 (set-menubar-dirty-flag))
1825 (define-key org-mode-map [menu-bar headings] 'undefined)
1826 (define-key org-mode-map [menu-bar hide] 'undefined)
1827 (define-key org-mode-map [menu-bar show] 'undefined))
1828
1829 (unless org-inhibit-startup
1830 (if org-startup-with-deadline-check
1831 (call-interactively 'org-check-deadlines)
1832 (cond
1833 ((eq org-startup-folded t)
1834 (org-cycle '(4)))
1835 ((eq org-startup-folded 'content)
1836 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1837 (org-cycle '(4)) (org-cycle '(4))))))))
1838
1839 (defun org-fill-paragraph (&optional justify)
1840 "Re-align a table, pass through to fill-paragraph if no table."
1841 (save-excursion
1842 (beginning-of-line 1)
1843 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1844
1845 (defsubst org-current-line (&optional pos)
1846 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1847
1848 ;;; Font-Lock stuff
1849
1850 (defvar org-mouse-map (make-sparse-keymap))
1851 (define-key org-mouse-map
1852 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1853 (define-key org-mouse-map
1854 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1855
1856 (require 'font-lock)
1857
1858 (defconst org-non-link-chars "\t\n\r|<>\000")
1859 (defconst org-link-regexp
1860 (if org-allow-space-in-links
1861 (concat
1862 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1863 (concat
1864 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1865 )
1866 "Regular expression for matching links.")
1867 (defconst org-link-maybe-angles-regexp
1868 (concat "<?\\(" org-link-regexp "\\)>?")
1869 "Matches a link and optionally surrounding angle brackets.")
1870 (defconst org-protected-link-regexp
1871 (concat "\000" org-link-regexp "\000")
1872 "Matches a link and optionally surrounding angle brackets.")
1873
1874 (defconst org-ts-lengths
1875 (cons (length (format-time-string (car org-time-stamp-formats)))
1876 (length (format-time-string (cdr org-time-stamp-formats))))
1877 "This holds the lengths of the two different time formats.")
1878 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1879 "Regular expression for fast time stamp matching.")
1880 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1881 "Regular expression matching time strings for analysis.")
1882 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1883 "Regular expression matching time stamps, with groups.")
1884 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1885 "Regular expression matching a time stamp range.")
1886 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1887 org-ts-regexp "\\)?")
1888 "Regular expression matching a time stamp or time stamp range.")
1889
1890 (defun org-activate-links (limit)
1891 "Run through the buffer and add overlays to links."
1892 (if (re-search-forward org-link-regexp limit t)
1893 (progn
1894 (add-text-properties (match-beginning 0) (match-end 0)
1895 (list 'mouse-face 'highlight
1896 'keymap org-mouse-map))
1897 t)))
1898
1899 (defun org-activate-dates (limit)
1900 "Run through the buffer and add overlays to dates."
1901 (if (re-search-forward org-tsr-regexp limit t)
1902 (progn
1903 (add-text-properties (match-beginning 0) (match-end 0)
1904 (list 'mouse-face 'highlight
1905 'keymap org-mouse-map))
1906 t)))
1907
1908 (defun org-font-lock-level ()
1909 (save-excursion
1910 (org-back-to-heading t)
1911 (- (match-end 0) (match-beginning 0))))
1912
1913 (defvar org-font-lock-keywords nil)
1914
1915 (defun org-set-font-lock-defaults ()
1916 (let ((org-font-lock-extra-keywords
1917 (list
1918 '(org-activate-links (0 'org-link))
1919 '(org-activate-dates (0 'org-link))
1920 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1921 '(1 'org-warning t))
1922 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning t))
1923 (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1924 (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1925 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1926 ;; (3 'bold))
1927 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1928 ;; (3 'italic))
1929 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1930 ;; (3 'underline))
1931 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1932 '(1 'org-warning t))
1933 '("^#.*" (0 'font-lock-comment-face t))
1934 (if org-fontify-done-headline
1935 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1936 '(1 'org-done t) '(2 'org-headline-done t))
1937 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1938 '(1 'org-done t)))
1939 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1940 (1 'org-table t))
1941 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1942 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
1943 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
1944 )))
1945 (set (make-local-variable 'org-font-lock-keywords)
1946 (append
1947 (if org-noutline-p ; FIXME: I am not sure if eval will work
1948 ; on XEmacs if noutline is ever ported
1949 '((eval . (list "^\\(\\*+\\).*"
1950 0 '(nth
1951 (% (- (match-end 1) (match-beginning 1) 1)
1952 org-n-levels)
1953 org-level-faces)
1954 nil t)))
1955 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1956 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1957 org-n-levels)
1958 org-level-faces)
1959 nil t))))
1960 org-font-lock-extra-keywords))
1961 (set (make-local-variable 'font-lock-defaults)
1962 '(org-font-lock-keywords t nil nil backward-paragraph))
1963 (kill-local-variable 'font-lock-keywords) nil))
1964
1965 (defun org-unfontify-region (beg end &optional maybe_loudly)
1966 "Remove fontification and activation overlays from links."
1967 (font-lock-default-unfontify-region beg end)
1968 (let* ((buffer-undo-list t)
1969 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1970 (inhibit-modification-hooks t)
1971 deactivate-mark buffer-file-name buffer-file-truename)
1972 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1973
1974 ;;; Visibility cycling
1975
1976 (defvar org-cycle-global-status nil)
1977 (defvar org-cycle-subtree-status nil)
1978 (defun org-cycle (&optional arg)
1979 "Visibility cycling for Org-mode.
1980
1981 - When this function is called with a prefix argument, rotate the entire
1982 buffer through 3 states (global cycling)
1983 1. OVERVIEW: Show only top-level headlines.
1984 2. CONTENTS: Show all headlines of all levels, but no body text.
1985 3. SHOW ALL: Show everything.
1986
1987 - When point is at the beginning of a headline, rotate the subtree started
1988 by this line through 3 different states (local cycling)
1989 1. FOLDED: Only the main headline is shown.
1990 2. CHILDREN: The main headline and the direct children are shown. From
1991 this state, you can move to one of the children and
1992 zoom in further.
1993 3. SUBTREE: Show the entire subtree, including body text.
1994
1995 - When there is a numeric prefix, go up to a heading with level ARG, do
1996 a `show-subtree' and return to the previous cursor position. If ARG
1997 is negative, go up that many levels.
1998
1999 - When point is not at the beginning of a headline, execute
2000 `indent-relative', like TAB normally does. See the option
2001 `org-cycle-emulate-tab' for details.
2002
2003 - Special case: if point is the the beginning of the buffer and there is
2004 no headline in line 1, this function will act as if called with prefix arg."
2005 (interactive "P")
2006
2007 (if (or (and (bobp) (not (looking-at outline-regexp)))
2008 (equal arg '(4)))
2009 ;; special case: use global cycling
2010 (setq arg t))
2011
2012 (cond
2013
2014 ((org-at-table-p 'any)
2015 ;; Enter the table or move to the next field in the table
2016 (or (org-table-recognize-table.el)
2017 (progn
2018 (org-table-justify-field-maybe)
2019 (org-table-next-field))))
2020
2021 ((eq arg t) ;; Global cycling
2022
2023 (cond
2024 ((and (eq last-command this-command)
2025 (eq org-cycle-global-status 'overview))
2026 ;; We just created the overview - now do table of contents
2027 ;; This can be slow in very large buffers, so indicate action
2028 (message "CONTENTS...")
2029 (save-excursion
2030 ;; Visit all headings and show their offspring
2031 (goto-char (point-max))
2032 (catch 'exit
2033 (while (and (progn (condition-case nil
2034 (outline-previous-visible-heading 1)
2035 (error (goto-char (point-min))))
2036 t)
2037 (looking-at outline-regexp))
2038 (show-branches)
2039 (if (bobp) (throw 'exit nil))))
2040 (message "CONTENTS...done"))
2041 (setq org-cycle-global-status 'contents)
2042 (run-hook-with-args 'org-cycle-hook 'contents))
2043
2044 ((and (eq last-command this-command)
2045 (eq org-cycle-global-status 'contents))
2046 ;; We just showed the table of contents - now show everything
2047 (show-all)
2048 (message "SHOW ALL")
2049 (setq org-cycle-global-status 'all)
2050 (run-hook-with-args 'org-cycle-hook 'all))
2051
2052 (t
2053 ;; Default action: go to overview
2054 (hide-sublevels 1)
2055 (message "OVERVIEW")
2056 (setq org-cycle-global-status 'overview)
2057 (run-hook-with-args 'org-cycle-hook 'overview))))
2058
2059 ((integerp arg)
2060 ;; Show-subtree, ARG levels up from here.
2061 (save-excursion
2062 (org-back-to-heading)
2063 (outline-up-heading (if (< arg 0) (- arg)
2064 (- (outline-level) arg)))
2065 (org-show-subtree)))
2066
2067 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2068 ;; At a heading: rotate between three different views
2069 (org-back-to-heading)
2070 (let ((goal-column 0) eoh eol eos)
2071 ;; First, some boundaries
2072 (save-excursion
2073 (org-back-to-heading)
2074 (save-excursion
2075 (beginning-of-line 2)
2076 (while (and (not (eobp)) ;; this is like `next-line'
2077 (get-char-property (1- (point)) 'invisible))
2078 (beginning-of-line 2)) (setq eol (point)))
2079 (outline-end-of-heading) (setq eoh (point))
2080 (outline-end-of-subtree) (setq eos (point))
2081 (outline-next-heading))
2082 ;; Find out what to do next and set `this-command'
2083 (cond
2084 ((= eos eoh)
2085 ;; Nothing is hidden behind this heading
2086 (message "EMPTY ENTRY")
2087 (setq org-cycle-subtree-status nil))
2088 ((>= eol eos)
2089 ;; Entire subtree is hidden in one line: open it
2090 (org-show-entry)
2091 (show-children)
2092 (message "CHILDREN")
2093 (setq org-cycle-subtree-status 'children)
2094 (run-hook-with-args 'org-cycle-hook 'children))
2095 ((and (eq last-command this-command)
2096 (eq org-cycle-subtree-status 'children))
2097 ;; We just showed the children, now show everything.
2098 (org-show-subtree)
2099 (message "SUBTREE")
2100 (setq org-cycle-subtree-status 'subtree)
2101 (run-hook-with-args 'org-cycle-hook 'subtree))
2102 (t
2103 ;; Default action: hide the subtree.
2104 (hide-subtree)
2105 (message "FOLDED")
2106 (setq org-cycle-subtree-status 'folded)
2107 (run-hook-with-args 'org-cycle-hook 'folded)))))
2108
2109 ;; TAB emulation
2110 (buffer-read-only (org-back-to-heading))
2111 ((if (and (eq org-cycle-emulate-tab 'white)
2112 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2113 t
2114 (eq org-cycle-emulate-tab t))
2115 (if (and (looking-at "[ \n\r\t]")
2116 (string-match "^[ \t]*$" (buffer-substring
2117 (point-at-bol) (point))))
2118 (progn
2119 (beginning-of-line 1)
2120 (and (looking-at "[ \t]+") (replace-match ""))))
2121 (indent-relative))
2122
2123 (t (save-excursion
2124 (org-back-to-heading)
2125 (org-cycle)))))
2126
2127 (defun org-optimize-window-after-visibility-change (state)
2128 "Adjust the window after a change in outline visibility.
2129 This function is the default value of the hook `org-cycle-hook'."
2130 (cond
2131 ((eq state 'overview) (org-first-headline-recenter 1))
2132 ((eq state 'content) nil)
2133 ((eq state 'all) nil)
2134 ((eq state 'folded) nil)
2135 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2136 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2137
2138 (defun org-subtree-end-visible-p ()
2139 "Is the end of the current subtree visible?"
2140 (pos-visible-in-window-p
2141 (save-excursion (outline-end-of-subtree) (point))))
2142
2143 (defun org-first-headline-recenter (&optional N)
2144 "Move cursor to the first headline and recenter the headline.
2145 Optional argument N means, put the headline into the Nth line of the window."
2146 (goto-char (point-min))
2147 (when (re-search-forward (concat "^" outline-regexp) nil t)
2148 (beginning-of-line)
2149 (recenter (prefix-numeric-value N))))
2150
2151 (defvar org-goto-window-configuration nil)
2152 (defvar org-goto-marker nil)
2153 (defvar org-goto-map (make-sparse-keymap))
2154 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2155 (while (setq cmd (pop cmds))
2156 (substitute-key-definition cmd cmd org-goto-map global-map)))
2157 (define-key org-goto-map "\C-m" 'org-goto-ret)
2158 (define-key org-goto-map [(left)] 'org-goto-left)
2159 (define-key org-goto-map [(right)] 'org-goto-right)
2160 (define-key org-goto-map [(?q)] 'org-goto-quit)
2161 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2162 (define-key org-goto-map "\C-i" 'org-cycle)
2163 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2164 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2165 (define-key org-goto-map "n" 'outline-next-visible-heading)
2166 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2167 (define-key org-goto-map "f" 'outline-forward-same-level)
2168 (define-key org-goto-map "b" 'outline-backward-same-level)
2169 (define-key org-goto-map "u" 'outline-up-heading)
2170 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2171 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2172 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2173 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2174 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2175 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2176 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2177
2178 (defconst org-goto-help
2179 "Select a location to jump to, press RET
2180 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2181
2182 (defun org-goto ()
2183 "Go to a different location of the document, keeping current visibility.
2184
2185 When you want to go to a different location in a document, the fastest way
2186 is often to fold the entire buffer and then dive into the tree. This
2187 method has the disadvantage, that the previous location will be folded,
2188 which may not be what you want.
2189
2190 This command works around this by showing a copy of the current buffer in
2191 overview mode. You can dive into the tree in that copy, to find the
2192 location you want to reach. When pressing RET, the command returns to the
2193 original buffer in which the visibility is still unchanged. It then jumps
2194 to the new location, making it and the headline hierarchy above it visible."
2195 (interactive)
2196 (let* ((org-goto-start-pos (point))
2197 (selected-point
2198 (org-get-location (current-buffer) org-goto-help)))
2199 (if selected-point
2200 (progn
2201 (goto-char selected-point)
2202 (if (org-invisible-p) (org-show-hierarchy-above)))
2203 (error "Quit"))))
2204
2205 (defun org-get-location (buf help)
2206 "Let the user select a location in the Org-mode buffer BUF.
2207 This function uses a recursive edit. It returns the selected position
2208 or nil."
2209 (let (org-selected-point)
2210 (save-excursion
2211 (save-window-excursion
2212 (delete-other-windows)
2213 (switch-to-buffer (get-buffer-create "*org-goto*"))
2214 (with-output-to-temp-buffer "*Help*"
2215 (princ help))
2216 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2217 (setq buffer-read-only nil)
2218 (erase-buffer)
2219 (insert-buffer buf)
2220 (let ((org-startup-truncated t)
2221 (org-startup-folded t)
2222 (org-startup-with-deadline-check nil))
2223 (org-mode))
2224 (setq buffer-read-only t)
2225 (if (boundp 'org-goto-start-pos)
2226 (goto-char org-goto-start-pos)
2227 (goto-char (point-min)))
2228 (org-beginning-of-line)
2229 (message "Select location and press RET")
2230 ;; now we make sure that during selection, ony very few keys work
2231 ;; and that it is impossible to switch to another window.
2232 (let ((gm (current-global-map))
2233 (overriding-local-map org-goto-map))
2234 (unwind-protect
2235 (progn
2236 (use-global-map org-goto-map)
2237 (recursive-edit))
2238 (use-global-map gm)))))
2239 (kill-buffer "*org-goto*")
2240 org-selected-point))
2241
2242 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2243 (defun org-goto-ret (&optional arg)
2244 "Finish org-goto by going to the new location."
2245 (interactive "P")
2246 (setq org-selected-point (point)
2247 current-prefix-arg arg)
2248 (throw 'exit nil))
2249
2250 (defun org-goto-left ()
2251 "Finish org-goto by going to the new location."
2252 (interactive)
2253 (if (org-on-heading-p)
2254 (progn
2255 (beginning-of-line 1)
2256 (setq org-selected-point (point)
2257 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2258 (throw 'exit nil))
2259 (error "Not on a heading")))
2260
2261 (defun org-goto-right ()
2262 "Finish org-goto by going to the new location."
2263 (interactive)
2264 (if (org-on-heading-p)
2265 (progn
2266 (outline-end-of-subtree)
2267 (or (eobp) (forward-char 1))
2268 (setq org-selected-point (point)
2269 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2270 (throw 'exit nil))
2271 (error "Not on a heading")))
2272
2273 (defun org-goto-quit ()
2274 "Finish org-goto without cursor motion."
2275 (interactive)
2276 (setq org-selected-point nil)
2277 (throw 'exit nil))
2278
2279 ;;; Promotion, Demotion, Inserting new headlines
2280
2281 (defvar org-ignore-region nil
2282 "To temporarily disable the active region.")
2283
2284 (defun org-insert-heading ()
2285 "Insert a new heading with same depth at point."
2286 (interactive)
2287 (let* ((head (save-excursion
2288 (condition-case nil
2289 (org-back-to-heading)
2290 (error (outline-next-heading)))
2291 (prog1 (match-string 0)
2292 (funcall outline-level)))))
2293 (unless (bolp) (newline))
2294 (insert head)
2295 (unless (eolp)
2296 (save-excursion (newline-and-indent)))
2297 (unless (equal (char-before) ?\ )
2298 (insert " "))
2299 (run-hooks 'org-insert-heading-hook)))
2300
2301 (defun org-insert-todo-heading (arg)
2302 "Insert a new heading with the same level and TODO state as current heading.
2303 If the heading has no TODO state, or if the state is DONE, use the first
2304 state (TODO by default). Also with prefix arg, force first state."
2305 (interactive "P")
2306 (org-insert-heading)
2307 (save-excursion
2308 (org-back-to-heading)
2309 (outline-previous-heading)
2310 (looking-at org-todo-line-regexp))
2311 (if (or arg
2312 (not (match-beginning 2))
2313 (equal (match-string 2) org-done-string))
2314 (insert (car org-todo-keywords) " ")
2315 (insert (match-string 2) " ")))
2316
2317 (defun org-promote-subtree ()
2318 "Promote the entire subtree.
2319 See also `org-promote'."
2320 (interactive)
2321 (save-excursion
2322 (org-map-tree 'org-promote)))
2323
2324 (defun org-demote-subtree ()
2325 "Demote the entire subtree. See `org-demote'.
2326 See also `org-promote'."
2327 (interactive)
2328 (save-excursion
2329 (org-map-tree 'org-demote)))
2330
2331 (defun org-do-promote ()
2332 "Promote the current heading higher up the tree.
2333 If the region is active in `transient-mark-mode', promote all headings
2334 in the region."
2335 (interactive)
2336 (save-excursion
2337 (if (org-region-active-p)
2338 (org-map-region 'org-promote (region-beginning) (region-end))
2339 (org-promote)))
2340 (org-fix-position-after-promote))
2341
2342 (defun org-do-demote ()
2343 "Demote the current heading lower down the tree.
2344 If the region is active in `transient-mark-mode', demote all headings
2345 in the region."
2346 (interactive)
2347 (save-excursion
2348 (if (org-region-active-p)
2349 (org-map-region 'org-demote (region-beginning) (region-end))
2350 (org-demote)))
2351 (org-fix-position-after-promote))
2352
2353 (defun org-fix-position-after-promote ()
2354 "Make sure that after pro/demotion cursor position is right."
2355 (and (equal (char-after) ?\ )
2356 (equal (char-before) ?*)
2357 (forward-char 1)))
2358
2359 (defun org-promote ()
2360 "Promote the current heading higher up the tree.
2361 If the region is active in `transient-mark-mode', promote all headings
2362 in the region."
2363 (org-back-to-heading t)
2364 (let* ((level (save-match-data (funcall outline-level)))
2365 (up-head (make-string (1- level) ?*)))
2366 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2367 (replace-match up-head nil t)
2368 (if org-adapt-indentation
2369 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2370
2371 (defun org-demote ()
2372 "Demote the current heading lower down the tree.
2373 If the region is active in `transient-mark-mode', demote all headings
2374 in the region."
2375 (org-back-to-heading t)
2376 (let* ((level (save-match-data (funcall outline-level)))
2377 (down-head (make-string (1+ level) ?*)))
2378 (replace-match down-head nil t)
2379 (if org-adapt-indentation
2380 (org-fixup-indentation "^ " " " "^\\S-"))))
2381
2382 (defun org-map-tree (fun)
2383 "Call FUN for every heading underneath the current one."
2384 (org-back-to-heading)
2385 (let ((level (outline-level)))
2386 (save-excursion
2387 (funcall fun)
2388 (while (and (progn
2389 (outline-next-heading)
2390 (> (funcall outline-level) level))
2391 (not (eobp)))
2392 (funcall fun)))))
2393
2394 (defun org-map-region (fun beg end)
2395 "Call FUN for every heading between BEG and END."
2396 (let ((org-ignore-region t))
2397 (save-excursion
2398 (setq end (copy-marker end))
2399 (goto-char beg)
2400 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2401 (< (point) end))
2402 (funcall fun))
2403 (while (and (progn
2404 (outline-next-heading)
2405 (< (point) end))
2406 (not (eobp)))
2407 (funcall fun)))))
2408
2409 (defun org-fixup-indentation (from to prohibit)
2410 "Change the indentation in the current entry by re-replacing FROM with TO.
2411 However, if the regexp PROHIBIT matches at all, don't do anything.
2412 This is being used to change indentation along with the length of the
2413 heading marker. But if there are any lines which are not indented, nothing
2414 is changed at all."
2415 (save-excursion
2416 (let ((end (save-excursion (outline-next-heading)
2417 (point-marker))))
2418 (unless (save-excursion (re-search-forward prohibit end t))
2419 (while (re-search-forward from end t)
2420 (replace-match to)
2421 (beginning-of-line 2)))
2422 (move-marker end nil))))
2423
2424 ;;; Vertical tree motion, cutting and pasting of subtrees
2425
2426 (defun org-move-subtree-up (&optional arg)
2427 "Move the current subtree up past ARG headlines of the same level."
2428 (interactive "p")
2429 (org-move-subtree-down (- (prefix-numeric-value arg))))
2430
2431 (defun org-move-subtree-down (&optional arg)
2432 "Move the current subtree down past ARG headlines of the same level."
2433 (interactive "p")
2434 (setq arg (prefix-numeric-value arg))
2435 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2436 'outline-get-last-sibling))
2437 (ins-point (make-marker))
2438 (cnt (abs arg))
2439 beg end txt folded)
2440 ;; Select the tree
2441 (org-back-to-heading)
2442 (setq beg (point))
2443 (save-match-data
2444 (save-excursion (outline-end-of-heading)
2445 (setq folded (org-invisible-p)))
2446 (outline-end-of-subtree))
2447 (outline-next-heading)
2448 (setq end (point))
2449 ;; Find insertion point, with error handling
2450 (goto-char beg)
2451 (while (> cnt 0)
2452 (or (and (funcall movfunc) (looking-at outline-regexp))
2453 (progn (goto-char beg)
2454 (error "Cannot move past superior level or buffer limit")))
2455 (setq cnt (1- cnt)))
2456 (if (> arg 0)
2457 ;; Moving forward - still need to move over subtree
2458 (progn (outline-end-of-subtree)
2459 (outline-next-heading)
2460 (if (not (or (looking-at (concat "^" outline-regexp))
2461 (bolp)))
2462 (newline))))
2463 (move-marker ins-point (point))
2464 (setq txt (buffer-substring beg end))
2465 (delete-region beg end)
2466 (insert txt)
2467 (goto-char ins-point)
2468 (if folded (hide-subtree))
2469 (move-marker ins-point nil)))
2470
2471 (defvar org-subtree-clip ""
2472 "Clipboard for cut and paste of subtrees.
2473 This is actually only a copy of the kill, because we use the normal kill
2474 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2475
2476 (defvar org-subtree-clip-folded nil
2477 "Was the last copied subtree folded?
2478 This is used to fold the tree back after pasting.")
2479
2480 (defun org-cut-subtree ()
2481 "Cut the current subtree into the clipboard.
2482 This is a short-hand for marking the subtree and then cutting it."
2483 (interactive)
2484 (org-copy-subtree 'cut))
2485
2486 (defun org-copy-subtree (&optional cut)
2487 "Cut the current subtree into the clipboard.
2488 This is a short-hand for marking the subtree and then copying it.
2489 If CUT is non nil, actually cut the subtree."
2490 (interactive)
2491 (let (beg end folded)
2492 (org-back-to-heading)
2493 (setq beg (point))
2494 (save-match-data
2495 (save-excursion (outline-end-of-heading)
2496 (setq folded (org-invisible-p)))
2497 (outline-end-of-subtree))
2498 (if (equal (char-after) ?\n) (forward-char 1))
2499 (setq end (point))
2500 (goto-char beg)
2501 (when (> end beg)
2502 (setq org-subtree-clip-folded folded)
2503 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2504 (setq org-subtree-clip (current-kill 0))
2505 (message "%s: Subtree with %d characters"
2506 (if cut "Cut" "Copied")
2507 (length org-subtree-clip)))))
2508
2509 (defun org-paste-subtree (&optional level tree)
2510 "Paste the clipboard as a subtree, with modification of headline level.
2511 The entire subtree is promoted or demoted in order to match a new headline
2512 level. By default, the new level is derived from the visible headings
2513 before and after the insertion point, and taken to be the inferior headline
2514 level of the two. So if the previous visible heading is level 3 and the
2515 next is level 4 (or vice versa), level 4 will be used for insertion.
2516 This makes sure that the subtree remains an independent subtree and does
2517 not swallow low level entries.
2518
2519 You can also force a different level, either by using a numeric prefix
2520 argument, or by inserting the heading marker by hand. For example, if the
2521 cursor is after \"*****\", then the tree will be shifted to level 5.
2522
2523 If you want to insert the tree as is, just use \\[yank].
2524
2525 If optional TREE is given, use this text instead of the kill ring."
2526 (interactive "P")
2527 (unless (org-kill-is-subtree-p tree)
2528 (error
2529 (substitute-command-keys
2530 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2531 (let* ((txt (or tree (current-kill 0)))
2532 (^re (concat "^\\(" outline-regexp "\\)"))
2533 (re (concat "\\(" outline-regexp "\\)"))
2534 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2535
2536 (old-level (if (string-match ^re txt)
2537 (- (match-end 0) (match-beginning 0))
2538 -1))
2539 (force-level (cond (level (prefix-numeric-value level))
2540 ((string-match
2541 ^re_ (buffer-substring (point-at-bol) (point)))
2542 (- (match-end 0) (match-beginning 0)))
2543 (t nil)))
2544 (previous-level (save-excursion
2545 (condition-case nil
2546 (progn
2547 (outline-previous-visible-heading 1)
2548 (if (looking-at re)
2549 (- (match-end 0) (match-beginning 0))
2550 1))
2551 (error 1))))
2552 (next-level (save-excursion
2553 (condition-case nil
2554 (progn
2555 (outline-next-visible-heading 1)
2556 (if (looking-at re)
2557 (- (match-end 0) (match-beginning 0))
2558 1))
2559 (error 1))))
2560 (new-level (or force-level (max previous-level next-level)))
2561 (shift (if (or (= old-level -1)
2562 (= new-level -1)
2563 (= old-level new-level))
2564 0
2565 (- new-level old-level)))
2566 (shift1 shift)
2567 (delta (if (> shift 0) -1 1))
2568 (func (if (> shift 0) 'org-demote 'org-promote))
2569 beg end)
2570 ;; Remove the forces level indicator
2571 (if force-level
2572 (delete-region (point-at-bol) (point)))
2573 ;; Make sure we start at the beginning of an empty line
2574 (if (not (bolp)) (insert "\n"))
2575 (if (not (looking-at "[ \t]*$"))
2576 (progn (insert "\n") (backward-char 1)))
2577 ;; Paste
2578 (setq beg (point))
2579 (insert txt)
2580 (setq end (point))
2581 (goto-char beg)
2582 ;; Shift if necessary
2583 (if (= shift 0)
2584 (message "Pasted at level %d, without shift" new-level)
2585 (save-restriction
2586 (narrow-to-region beg end)
2587 (while (not (= shift 0))
2588 (org-map-region func (point-min) (point-max))
2589 (setq shift (+ delta shift)))
2590 (goto-char (point-min))
2591 (message "Pasted at level %d, with shift by %d levels"
2592 new-level shift1)))
2593 (if (and (eq org-subtree-clip (current-kill 0))
2594 org-subtree-clip-folded)
2595 ;; The tree was folded before it was killed/copied
2596 (hide-subtree))))
2597
2598 (defun org-kill-is-subtree-p (&optional txt)
2599 "Check if the current kill is an outline subtree, or a set of trees.
2600 Returns nil if kill does not start with a headline, or if the first
2601 headline level is not the largest headline level in the tree.
2602 So this will actually accept several entries of equal levels as well,
2603 which is OK for `org-paste-subtree'.
2604 If optional TXT is given, check this string instead of the current kill."
2605 (let* ((kill (or txt (current-kill 0) ""))
2606 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2607 (- (match-end 0) (match-beginning 0))))
2608 (re (concat "^" outline-regexp))
2609 (start 1))
2610 (if (not start-level)
2611 nil ;; does not even start with a heading
2612 (catch 'exit
2613 (while (setq start (string-match re kill (1+ start)))
2614 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2615 (throw 'exit nil)))
2616 t))))
2617
2618 (defun org-archive-subtree ()
2619 "Move the current subtree to the archive.
2620 The archive can be a certain top-level heading in the current file, or in
2621 a different file. The tree will be moved to that location, the subtree
2622 heading be marked DONE, and the current time will be added."
2623 (interactive)
2624 ;; Save all relevant TODO keyword-relatex variables
2625 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2626 (tr-org-todo-keywords org-todo-keywords)
2627 (tr-org-todo-interpretation org-todo-interpretation)
2628 (tr-org-done-string org-done-string)
2629 (tr-org-todo-regexp org-todo-regexp)
2630 (tr-org-todo-line-regexp org-todo-line-regexp)
2631 (this-buffer (current-buffer))
2632 file heading buffer level newfile-p)
2633 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2634 (progn
2635 (setq file (format (match-string 1 org-archive-location)
2636 (file-name-nondirectory (buffer-file-name)))
2637 heading (match-string 2 org-archive-location)))
2638 (error "Invalid `org-archive-location'"))
2639 (if (> (length file) 0)
2640 (setq newfile-p (not (file-exists-p file))
2641 buffer (find-file-noselect file))
2642 (setq buffer (current-buffer)))
2643 (unless buffer
2644 (error "Cannot access file \"%s\"" file))
2645 (if (and (> (length heading) 0)
2646 (string-match "^\\*+" heading))
2647 (setq level (match-end 0))
2648 (setq heading nil level 0))
2649 (save-excursion
2650 ;; We first only copy, in case something goes wrong
2651 ;; we need to protect this-command, to avoid kill-region sets it,
2652 ;; which would lead to duplication of subtrees
2653 (let (this-command) (org-copy-subtree))
2654 (set-buffer buffer)
2655 ;; Enforce org-mode for the archive buffer
2656 (if (not (eq major-mode 'org-mode))
2657 ;; Force the mode for future visits.
2658 (let ((org-insert-mode-line-in-empty-file t))
2659 (call-interactively 'org-mode)))
2660 (when newfile-p
2661 (goto-char (point-max))
2662 (insert (format "\nArchived entries from file %s\n\n"
2663 (buffer-file-name this-buffer))))
2664 ;; Force the TODO keywords of the original buffer
2665 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2666 (org-todo-keywords tr-org-todo-keywords)
2667 (org-todo-interpretation tr-org-todo-interpretation)
2668 (org-done-string tr-org-done-string)
2669 (org-todo-regexp tr-org-todo-regexp)
2670 (org-todo-line-regexp tr-org-todo-line-regexp))
2671 (goto-char (point-min))
2672 (if heading
2673 (progn
2674 (if (re-search-forward
2675 (concat "\\(^\\|\r\\)"
2676 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2677 nil t)
2678 (goto-char (match-end 0))
2679 ;; Heading not found, just insert it at the end
2680 (goto-char (point-max))
2681 (or (bolp) (insert "\n"))
2682 (insert "\n" heading "\n")
2683 (end-of-line 0))
2684 ;; Make the heading visible, and the following as well
2685 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2686 (if (re-search-forward
2687 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2688 nil t)
2689 (progn (goto-char (match-beginning 0)) (insert "\n")
2690 (beginning-of-line 0))
2691 (goto-char (point-max)) (insert "\n")))
2692 (goto-char (point-max)) (insert "\n"))
2693 ;; Paste
2694 (org-paste-subtree (1+ level))
2695 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2696 (if org-archive-mark-done
2697 (org-todo (length org-todo-keywords)))
2698 ;; Move cursor to right after the TODO keyword
2699 (when org-archive-stamp-time
2700 (beginning-of-line 1)
2701 (looking-at org-todo-line-regexp)
2702 (goto-char (or (match-end 2) (match-beginning 3)))
2703 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2704 (current-time))
2705 ")"))
2706 ;; Save the buffer, if it is not the same buffer.
2707 (if (not (eq this-buffer buffer)) (save-buffer))))
2708 ;; Here we are back in the original buffer. Everything seems to have
2709 ;; worked. So now cut the tree and finish up.
2710 (let (this-command) (org-cut-subtree))
2711 (if (looking-at "[ \t]*$") (kill-line))
2712 (message "Subtree archived %s"
2713 (if (eq this-buffer buffer)
2714 (concat "under heading: " heading)
2715 (concat "in file: " (abbreviate-file-name file))))))
2716
2717 ;;; Completion
2718
2719 (defun org-complete (&optional arg)
2720 "Perform completion on word at point.
2721 At the beginning of a headline, this completes TODO keywords as given in
2722 `org-todo-keywords'.
2723 If the current word is preceded by a backslash, completes the TeX symbols
2724 that are supported for HTML support.
2725 If the current word is preceded by \"#+\", completes special words for
2726 setting file options.
2727 At all other locations, this simply calls `ispell-complete-word'."
2728 (interactive "P")
2729 (catch 'exit
2730 (let* ((end (point))
2731 (beg (save-excursion
2732 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2733 (skip-chars-backward "a-zA-Z0-9_:$")
2734 (point)))
2735 (texp (equal (char-before beg) ?\\))
2736 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2737 beg)
2738 "#+"))
2739 (pattern (buffer-substring-no-properties beg end))
2740 (completion-ignore-case opt)
2741 (type nil)
2742 (table (cond
2743 (opt
2744 (setq type :opt)
2745 (mapcar (lambda (x)
2746 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2747 (cons (match-string 2 x) (match-string 1 x)))
2748 (org-split-string (org-get-current-options) "\n")))
2749 (texp
2750 (setq type :tex)
2751 org-html-entities)
2752 ((string-match "\\`\\*+[ \t]*\\'"
2753 (buffer-substring (point-at-bol) beg))
2754 (setq type :todo)
2755 (mapcar 'list org-todo-keywords))
2756 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2757 (completion (try-completion pattern table)))
2758 (cond ((eq completion t)
2759 (if (equal type :opt)
2760 (insert (substring (cdr (assoc (upcase pattern) table))
2761 (length pattern)))))
2762 ((null completion)
2763 (message "Can't find completion for \"%s\"" pattern)
2764 (ding))
2765 ((not (string= pattern completion))
2766 (delete-region beg end)
2767 (if (string-match " +$" completion)
2768 (setq completion (replace-match "" t t completion)))
2769 (insert completion)
2770 (if (get-buffer-window "*Completions*")
2771 (delete-window (get-buffer-window "*Completions*")))
2772 (if (and (eq type :todo)
2773 (assoc completion table))
2774 (insert " "))
2775 (if (and (equal type :opt) (assoc completion table))
2776 (message (substitute-command-keys
2777 "Press \\[org-complete] again to insert example settings"))))
2778 (t
2779 (message "Making completion list...")
2780 (let ((list (sort (all-completions pattern table) 'string<)))
2781 (with-output-to-temp-buffer "*Completions*"
2782 (display-completion-list list)))
2783 (message "Making completion list...%s" "done"))))))
2784
2785 ;;; Comments, TODO and DEADLINE
2786
2787 (defun org-toggle-comment ()
2788 "Change the COMMENT state of an entry."
2789 (interactive)
2790 (save-excursion
2791 (org-back-to-heading)
2792 (if (looking-at (concat outline-regexp
2793 "\\( +\\<" org-comment-string "\\>\\)"))
2794 (replace-match "" t t nil 1)
2795 (if (looking-at outline-regexp)
2796 (progn
2797 (goto-char (match-end 0))
2798 (insert " " org-comment-string))))))
2799
2800 (defvar org-last-todo-state-is-todo nil
2801 "This is non-nil when the last TODO state change led to a TODO state.
2802 If the last change removed the TODO tag or switched to DONE, then
2803 this is nil.")
2804
2805 (defun org-todo (&optional arg)
2806 "Change the TODO state of an item.
2807 The state of an item is given by a keyword at the start of the heading,
2808 like
2809 *** TODO Write paper
2810 *** DONE Call mom
2811
2812 The different keywords are specified in the variable `org-todo-keywords'. By
2813 default the available states are \"TODO\" and \"DONE\".
2814 So for this example: when the item starts with TODO, it is changed to DONE.
2815 When it starts with DONE, the DONE is removed. And when neither TODO nor
2816 DONE are present, add TODO at the beginning of the heading.
2817
2818 With prefix arg, use completion to determined the new state. With numeric
2819 prefix arg, switch to that state."
2820 (interactive "P")
2821 (save-excursion
2822 (org-back-to-heading)
2823 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2824 (or (looking-at (concat " +" org-todo-regexp " *"))
2825 (looking-at " *"))
2826 (let* ((this (match-string 1))
2827 (completion-ignore-case t)
2828 (member (member this org-todo-keywords))
2829 (tail (cdr member))
2830 (state (cond
2831 ((equal arg '(4))
2832 ;; Read a state with completion
2833 (completing-read "State: " (mapcar (lambda(x) (list x))
2834 org-todo-keywords)
2835 nil t))
2836 (arg
2837 ;; user requests a specific state
2838 (nth (1- (prefix-numeric-value arg))
2839 org-todo-keywords))
2840 ((null member) (car org-todo-keywords))
2841 ((null tail) nil) ;; -> first entry
2842 ((eq org-todo-interpretation 'sequence)
2843 (car tail))
2844 ((memq org-todo-interpretation '(type priority))
2845 (if (eq this-command last-command)
2846 (car tail)
2847 (if (> (length tail) 0) org-done-string nil)))
2848 (t nil)))
2849 (next (if state (concat " " state " ") " ")))
2850 (replace-match next t t)
2851 (setq org-last-todo-state-is-todo
2852 (not (equal state org-done-string)))
2853 (run-hooks 'org-after-todo-state-change-hook)))
2854 ;; Fixup cursor location if close to the keyword
2855 (if (and (outline-on-heading-p)
2856 (not (bolp))
2857 (save-excursion (beginning-of-line 1)
2858 (looking-at org-todo-line-regexp))
2859 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2860 (progn
2861 (goto-char (or (match-end 2) (match-end 1)))
2862 (just-one-space))))
2863
2864 (defun org-show-todo-tree (arg)
2865 "Make a compact tree which shows all headlines marked with TODO.
2866 The tree will show the lines where the regexp matches, and all higher
2867 headlines above the match."
2868 (interactive "P")
2869 (let ((case-fold-search nil)
2870 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2871 (message "%d TODO entries found"
2872 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2873
2874 (defun org-deadline ()
2875 "Insert the DEADLINE: string to make a deadline.
2876 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2877 to modify it to the correct date."
2878 (interactive)
2879 (insert
2880 org-deadline-string " "
2881 (format-time-string (car org-time-stamp-formats)
2882 (org-read-date nil 'to-time)))
2883 (message (substitute-command-keys
2884 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2885
2886 (defun org-schedule ()
2887 "Insert the SCHEDULED: string to schedule a TODO item.
2888 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2889 to modify it to the correct date."
2890 (interactive)
2891 (insert
2892 org-scheduled-string " "
2893 (format-time-string (car org-time-stamp-formats)
2894 (org-read-date nil 'to-time)))
2895 (message (substitute-command-keys
2896 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2897
2898
2899 (defun org-occur (regexp &optional callback)
2900 "Make a compact tree which shows all matches of REGEXP.
2901 The tree will show the lines where the regexp matches, and all higher
2902 headlines above the match. It will also show the heading after the match,
2903 to make sure editing the matching entry is easy.
2904 if CALLBACK is non-nil, it is a function which is called to confirm
2905 that the match should indeed be shown."
2906 (interactive "sRegexp: ")
2907 (setq regexp (org-check-occur-regexp regexp))
2908 (let ((cnt 0))
2909 (save-excursion
2910 (goto-char (point-min))
2911 (hide-sublevels 1)
2912 (while (re-search-forward regexp nil t)
2913 (when (or (not callback)
2914 (funcall callback))
2915 (setq cnt (1+ cnt))
2916 (org-show-hierarchy-above))))
2917 (run-hooks 'org-occur-hook)
2918 (if (interactive-p)
2919 (message "%d match(es) for regexp %s" cnt regexp))
2920 cnt))
2921
2922 (defun org-show-hierarchy-above ()
2923 "Make sure point and the headings hierarchy above is visible."
2924 (if (org-on-heading-p t)
2925 (org-flag-heading nil) ; only show the heading
2926 (org-show-hidden-entry)) ; show entire entry
2927 (save-excursion
2928 (and org-show-following-heading
2929 (outline-next-heading)
2930 (org-flag-heading nil))) ; show the next heading
2931 (save-excursion ; show all higher headings
2932 (while (condition-case nil
2933 (progn (org-up-heading-all 1) t)
2934 (error nil))
2935 (org-flag-heading nil))))
2936
2937 ;;; Priorities
2938
2939 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2940 "Regular expression matching the priority indicator.")
2941
2942 (defvar org-remove-priority-next-time nil)
2943
2944 (defun org-priority-up ()
2945 "Increase the priority of the current item."
2946 (interactive)
2947 (org-priority 'up))
2948
2949 (defun org-priority-down ()
2950 "Decrease the priority of the current item."
2951 (interactive)
2952 (org-priority 'down))
2953
2954 (defun org-priority (&optional action)
2955 "Change the priority of an item by ARG.
2956 ACTION can be set, up, or down."
2957 (interactive)
2958 (setq action (or action 'set))
2959 (let (current new news have remove)
2960 (save-excursion
2961 (org-back-to-heading)
2962 (if (looking-at org-priority-regexp)
2963 (setq current (string-to-char (match-string 2))
2964 have t)
2965 (setq current org-default-priority))
2966 (cond
2967 ((eq action 'set)
2968 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2969 (setq new (read-char-exclusive))
2970 (cond ((equal new ?\ ) (setq remove t))
2971 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2972 (error "Priority must be between `%c' and `%c'"
2973 ?A org-lowest-priority))))
2974 ((eq action 'up)
2975 (setq new (1- current)))
2976 ((eq action 'down)
2977 (setq new (1+ current)))
2978 (t (error "Invalid action")))
2979 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2980 (setq news (format "%c" new))
2981 (if have
2982 (if remove
2983 (replace-match "" t t nil 1)
2984 (replace-match news t t nil 2))
2985 (if remove
2986 (error "No priority cookie found in line")
2987 (looking-at org-todo-line-regexp)
2988 (if (match-end 2)
2989 (progn
2990 (goto-char (match-end 2))
2991 (insert " [#" news "]"))
2992 (goto-char (match-beginning 3))
2993 (insert "[#" news "] ")))))
2994 (if remove
2995 (message "Priority removed")
2996 (message "Priority of current item set to %s" news))))
2997
2998
2999 (defun org-get-priority (s)
3000 "Find priority cookie and return priority."
3001 (save-match-data
3002 (if (not (string-match org-priority-regexp s))
3003 (* 1000 (- org-lowest-priority org-default-priority))
3004 (* 1000 (- org-lowest-priority
3005 (string-to-char (match-string 2 s)))))))
3006
3007 ;;; Timestamps
3008
3009 (defvar org-last-changed-timestamp nil)
3010
3011 (defun org-time-stamp (arg)
3012 "Prompt for a date/time and insert a time stamp.
3013 If the user specifies a time like HH:MM, or if this command is called
3014 with a prefix argument, the time stamp will contain date and time.
3015 Otherwise, only the date will be included. All parts of a date not
3016 specified by the user will be filled in from the current date/time.
3017 So if you press just return without typing anything, the time stamp
3018 will represent the current date/time. If there is already a timestamp
3019 at the cursor, it will be modified."
3020 (interactive "P")
3021 (let ((fmt (if arg (cdr org-time-stamp-formats)
3022 (car org-time-stamp-formats)))
3023 (org-time-was-given nil)
3024 time)
3025 (cond
3026 ((and (org-at-timestamp-p)
3027 (eq last-command 'org-time-stamp)
3028 (eq this-command 'org-time-stamp))
3029 (insert "--")
3030 (setq time (let ((this-command this-command))
3031 (org-read-date arg 'totime)))
3032 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3033 (insert (format-time-string fmt time)))
3034 ((org-at-timestamp-p)
3035 (setq time (let ((this-command this-command))
3036 (org-read-date arg 'totime)))
3037 (and (org-at-timestamp-p) (replace-match
3038 (setq org-last-changed-timestamp
3039 (format-time-string fmt time))
3040 t t))
3041 (message "Timestamp updated"))
3042 (t
3043 (setq time (let ((this-command this-command))
3044 (org-read-date arg 'totime)))
3045 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3046 (insert (format-time-string fmt time))))))
3047
3048 ;;; FIXME: Make the function take "Fri" as "next friday"
3049 (defun org-read-date (&optional with-time to-time)
3050 "Read a date and make things smooth for the user.
3051 The prompt will suggest to enter an ISO date, but you can also enter anything
3052 which will at least partially be understood by `parse-time-string'.
3053 Unrecognized parts of the date will default to the current day, month ,year,
3054 hour and minute. For example,
3055 3-2-5 --> 2003-02-05
3056 feb 15 --> currentyear-02-15
3057 sep 12 9 --> 2009-09-12
3058 12:45 --> today 12:45
3059 22 sept 0:34 --> currentyear-09-22 0:34
3060 12 --> currentyear-currentmonth-12
3061 etc.
3062 The function understands only English month and weekday abbreviations,
3063 but this can be configured with the variables `parse-time-months' and
3064 `parse-time-weekdays'.
3065
3066 While prompting, a calendar is popped up - you can also select the
3067 date with the mouse (button 1). The calendar shows a period of three
3068 month. To scroll it to other months, use the keys `>' and `<'.
3069 If you don't like the calendar, turn it off with
3070 \(setq org-popup-calendar-for-date-prompt nil).
3071
3072 With optional argument TO-TIME, the date will immediately be converted
3073 to an internal time.
3074 With an optional argument WITH-TIME, the prompt will suggest to also
3075 insert a time. Note that when WITH-TIME is not set, you can still
3076 enter a time, and this function will inform the calling routine about
3077 this change. The calling routine may then choose to change the format
3078 used to insert the time stamp into the buffer to include the time."
3079 (let* ((default-time
3080 ;; Default time is either today, or, when entering a range,
3081 ;; the range start.
3082 (if (save-excursion
3083 (re-search-backward
3084 (concat org-ts-regexp "--\\=")
3085 (- (point) 20) t))
3086 (apply
3087 'encode-time
3088 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3089 (parse-time-string (match-string 1))))
3090 (current-time)))
3091 (timestr (format-time-string
3092 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3093 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3094 ans ans1 ans2
3095 second minute hour day month year tl)
3096
3097 (if org-popup-calendar-for-date-prompt
3098 ;; Also show a calendar for date selection
3099 ;; Copied (with modifications) from planner.el by John Wiegley
3100 (save-excursion
3101 (save-window-excursion
3102 (calendar)
3103 (calendar-forward-day (- (time-to-days default-time)
3104 (calendar-absolute-from-gregorian
3105 (calendar-current-date))))
3106 (let* ((old-map (current-local-map))
3107 (map (copy-keymap calendar-mode-map))
3108 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3109 (define-key map (kbd "RET") 'org-calendar-select)
3110 (define-key map (if org-xemacs-p [button1] [mouse-1])
3111 'org-calendar-select)
3112 (define-key minibuffer-local-map [(meta shift left)]
3113 (lambda () (interactive)
3114 (org-eval-in-calendar '(calendar-backward-month 1))))
3115 (define-key minibuffer-local-map [(meta shift right)]
3116 (lambda () (interactive)
3117 (org-eval-in-calendar '(calendar-forward-month 1))))
3118 (define-key minibuffer-local-map [(shift up)]
3119 (lambda () (interactive)
3120 (org-eval-in-calendar '(calendar-backward-week 1))))
3121 (define-key minibuffer-local-map [(shift down)]
3122 (lambda () (interactive)
3123 (org-eval-in-calendar '(calendar-forward-week 1))))
3124 (define-key minibuffer-local-map [(shift left)]
3125 (lambda () (interactive)
3126 (org-eval-in-calendar '(calendar-backward-day 1))))
3127 (define-key minibuffer-local-map [(shift right)]
3128 (lambda () (interactive)
3129 (org-eval-in-calendar '(calendar-forward-day 1))))
3130 (define-key minibuffer-local-map ">"
3131 (lambda () (interactive)
3132 (org-eval-in-calendar '(scroll-calendar-left 1))))
3133 (define-key minibuffer-local-map "<"
3134 (lambda () (interactive)
3135 (org-eval-in-calendar '(scroll-calendar-right 1))))
3136 (unwind-protect
3137 (progn
3138 (use-local-map map)
3139 (setq ans (read-string prompt "" nil nil))
3140 (setq ans (or ans1 ans2 ans)))
3141 (use-local-map old-map)))))
3142 ;; Naked prompt only
3143 (setq ans (read-string prompt "" nil timestr)))
3144
3145 (if (string-match
3146 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3147 (progn
3148 (setq year (if (match-end 2)
3149 (string-to-number (match-string 2 ans))
3150 (string-to-number (format-time-string "%Y")))
3151 month (string-to-number (match-string 3 ans))
3152 day (string-to-number (match-string 4 ans)))
3153 (if (< year 100) (setq year (+ 2000 year)))
3154 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3155 t t ans))))
3156 (setq tl (parse-time-string ans)
3157 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3158 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3159 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3160 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3161 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3162 second (or (nth 0 tl) 0))
3163 (if (and (boundp 'org-time-was-given)
3164 (nth 2 tl))
3165 (setq org-time-was-given t))
3166 (if (< year 100) (setq year (+ 2000 year)))
3167 (if to-time
3168 (encode-time second minute hour day month year)
3169 (if (or (nth 1 tl) (nth 2 tl))
3170 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3171 (format "%04d-%02d-%02d" year month day)))))
3172
3173 (defun org-eval-in-calendar (form)
3174 "Eval FORM in the calendar window and return to current window.
3175 Also, store the cursor date in variable ans2."
3176 (let ((sw (selected-window)))
3177 (select-window (get-buffer-window "*Calendar*"))
3178 (eval form)
3179 (when (calendar-cursor-to-date)
3180 (let* ((date (calendar-cursor-to-date))
3181 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3182 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3183 (select-window sw)))
3184
3185 (defun org-calendar-select ()
3186 "Return to `org-read-date' with the date currently selected.
3187 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3188 (interactive)
3189 (when (calendar-cursor-to-date)
3190 (let* ((date (calendar-cursor-to-date))
3191 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3192 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3193 (if (active-minibuffer-window) (exit-minibuffer))))
3194
3195 (defun org-check-deadlines (ndays)
3196 "Check if there are any deadlines due or past due.
3197 A deadline is considered due if it happens within `org-deadline-warning-days'
3198 days from today's date. If the deadline appears in an entry marked DONE,
3199 it is not shown. The prefix arg NDAYS can be used to test that many
3200 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3201 (interactive "P")
3202 (let* ((org-warn-days
3203 (cond
3204 ((equal ndays '(4)) 100000)
3205 (ndays (prefix-numeric-value ndays))
3206 (t org-deadline-warning-days)))
3207 (case-fold-search nil)
3208 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3209 (callback
3210 (lambda ()
3211 (and (let ((d1 (time-to-days (current-time)))
3212 (d2 (time-to-days
3213 (org-time-string-to-time (match-string 1)))))
3214 (< (- d2 d1) org-warn-days))
3215 (not (org-entry-is-done-p))))))
3216 (message "%d deadlines past-due or due within %d days"
3217 (org-occur regexp callback)
3218 org-warn-days)))
3219
3220 (defun org-evaluate-time-range (&optional to-buffer)
3221 "Evaluate a time range by computing the difference between start and end.
3222 Normally the result is just printed in the echo area, but with prefix arg
3223 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3224 If the time range is actually in a table, the result is inserted into the
3225 next column.
3226 For time difference computation, a year is assumed to be exactly 365
3227 days in order to avoid rounding problems."
3228 (interactive "P")
3229 (save-excursion
3230 (unless (org-at-date-range-p)
3231 (goto-char (point-at-bol))
3232 (re-search-forward org-tr-regexp (point-at-eol) t))
3233 (if (not (org-at-date-range-p))
3234 (error "Not at a time-stamp range, and none found in current line")))
3235 (let* ((ts1 (match-string 1))
3236 (ts2 (match-string 2))
3237 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3238 (match-end (match-end 0))
3239 (time1 (org-time-string-to-time ts1))
3240 (time2 (org-time-string-to-time ts2))
3241 (t1 (time-to-seconds time1))
3242 (t2 (time-to-seconds time2))
3243 (diff (abs (- t2 t1)))
3244 (negative (< (- t2 t1) 0))
3245 ;; (ys (floor (* 365 24 60 60)))
3246 (ds (* 24 60 60))
3247 (hs (* 60 60))
3248 (fy "%dy %dd %02d:%02d")
3249 (fy1 "%dy %dd")
3250 (fd "%dd %02d:%02d")
3251 (fd1 "%dd")
3252 (fh "%02d:%02d")
3253 y d h m align)
3254 ;; FIXME: Should I re-introduce years, make year refer to same date?
3255 ;; This would be the only useful way to have years, actually.
3256 (if havetime
3257 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3258 y 0
3259 d (floor (/ diff ds)) diff (mod diff ds)
3260 h (floor (/ diff hs)) diff (mod diff hs)
3261 m (floor (/ diff 60)))
3262 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3263 y 0
3264 d (floor (+ (/ diff ds) 0.5))
3265 h 0 m 0))
3266 (if (not to-buffer)
3267 (message (org-make-tdiff-string y d h m))
3268 (when (org-at-table-p)
3269 (goto-char match-end)
3270 (setq align t)
3271 (and (looking-at " *|") (goto-char (match-end 0))))
3272 (if (looking-at
3273 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3274 (replace-match ""))
3275 (if negative (insert " -"))
3276 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3277 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3278 (insert " " (format fh h m))))
3279 (if align (org-table-align))
3280 (message "Time difference inserted"))))
3281
3282 (defun org-make-tdiff-string (y d h m)
3283 (let ((fmt "")
3284 (l nil))
3285 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3286 l (push y l)))
3287 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3288 l (push d l)))
3289 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3290 l (push h l)))
3291 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3292 l (push m l)))
3293 (apply 'format fmt (nreverse l))))
3294
3295 (defun org-time-string-to-time (s)
3296 (apply 'encode-time (org-parse-time-string s)))
3297
3298 (defun org-parse-time-string (s &optional nodefault)
3299 "Parse the standard Org-mode time string.
3300 This should be a lot faster than the normal `parse-time-string'.
3301 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3302 hour and minute fields will be nil if not given."
3303 (if (string-match org-ts-regexp1 s)
3304 (list 0
3305 (if (or (match-beginning 8) (not nodefault))
3306 (string-to-number (or (match-string 8 s) "0")))
3307 (if (or (match-beginning 7) (not nodefault))
3308 (string-to-number (or (match-string 7 s) "0")))
3309 (string-to-number (match-string 4 s))
3310 (string-to-number (match-string 3 s))
3311 (string-to-number (match-string 2 s))
3312 nil nil nil)
3313 (make-list 9 0)))
3314
3315 (defun org-timestamp-up (&optional arg)
3316 "Increase the date item at the cursor by one.
3317 If the cursor is on the year, change the year. If it is on the month or
3318 the day, change that.
3319 With prefix ARG, change by that many units."
3320 (interactive "p")
3321 (org-timestamp-change (prefix-numeric-value arg)))
3322
3323 (defun org-timestamp-down (&optional arg)
3324 "Decrease the date item at the cursor by one.
3325 If the cursor is on the year, change the year. If it is on the month or
3326 the day, change that.
3327 With prefix ARG, change by that many units."
3328 (interactive "p")
3329 (org-timestamp-change (- (prefix-numeric-value arg))))
3330
3331 (defun org-timestamp-up-day (&optional arg)
3332 "Increase the date in the time stamp by one day.
3333 With prefix ARG, change that many days."
3334 (interactive "p")
3335 (org-timestamp-change (prefix-numeric-value arg) 'day))
3336
3337 (defun org-timestamp-down-day (&optional arg)
3338 "Decrease the date in the time stamp by one day.
3339 With prefix ARG, change that many days."
3340 (interactive "p")
3341 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3342
3343 (defsubst org-pos-in-match-range (pos n)
3344 (and (match-beginning n)
3345 (<= (match-beginning n) pos)
3346 (>= (match-end n) pos)))
3347
3348 (defun org-at-timestamp-p ()
3349 "Determine if the cursor is or at a timestamp."
3350 (interactive)
3351 (let* ((tsr org-ts-regexp2)
3352 (pos (point))
3353 (ans (or (looking-at tsr)
3354 (save-excursion
3355 (skip-chars-backward "^<\n\r\t")
3356 (if (> (point) 1) (backward-char 1))
3357 (and (looking-at tsr)
3358 (> (- (match-end 0) pos) -1))))))
3359 (and (boundp 'org-ts-what)
3360 (setq org-ts-what
3361 (cond
3362 ((org-pos-in-match-range pos 2) 'year)
3363 ((org-pos-in-match-range pos 3) 'month)
3364 ((org-pos-in-match-range pos 7) 'hour)
3365 ((org-pos-in-match-range pos 8) 'minute)
3366 ((or (org-pos-in-match-range pos 4)
3367 (org-pos-in-match-range pos 5)) 'day)
3368 (t 'day))))
3369 ans))
3370
3371 (defun org-timestamp-change (n &optional what)
3372 "Change the date in the time stamp at point.
3373 The date will be changed by N times WHAT. WHAT can be `day', `month',
3374 `year', `minute', `second'. If WHAT is not given, the cursor position
3375 in the timestamp determines what will be changed."
3376 (let ((fmt (car org-time-stamp-formats))
3377 org-ts-what
3378 (pos (point))
3379 ts time time0)
3380 (if (not (org-at-timestamp-p))
3381 (error "Not at a timestamp"))
3382 (setq org-ts-what (or what org-ts-what))
3383 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3384 (- (match-end 0) (match-beginning 0))))
3385 1)
3386 (cdr org-time-stamp-formats)
3387 (car org-time-stamp-formats)))
3388 (setq ts (match-string 0))
3389 (replace-match "")
3390 (setq time0 (org-parse-time-string ts))
3391 (setq time
3392 (apply 'encode-time
3393 (append
3394 (list (or (car time0) 0))
3395 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3396 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3397 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3398 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3399 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3400 (nthcdr 6 time0))))
3401 (if (eq what 'calendar)
3402 (let ((cal-date
3403 (save-excursion
3404 (save-match-data
3405 (set-buffer "*Calendar*")
3406 (calendar-cursor-to-date)))))
3407 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3408 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3409 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3410 (setcar time0 (or (car time0) 0))
3411 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3412 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3413 (setq time (apply 'encode-time time0))))
3414 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3415 (goto-char pos)
3416 ;; Try to recenter the calendar window, if any
3417 (if (and org-calendar-follow-timestamp-change
3418 (get-buffer-window "*Calendar*" t)
3419 (memq org-ts-what '(day month year)))
3420 (org-recenter-calendar (time-to-days time)))))
3421
3422 (defun org-recenter-calendar (date)
3423 "If the calendar is visible, recenter it to DATE."
3424 (let* ((win (selected-window))
3425 (cwin (get-buffer-window "*Calendar*" t)))
3426 (when cwin
3427 (select-window cwin)
3428 (calendar-goto-date (if (listp date) date
3429 (calendar-gregorian-from-absolute date)))
3430 (select-window win))))
3431
3432 (defun org-goto-calendar (&optional arg)
3433 "Go to the Emacs calendar at the current date.
3434 If there is a time stamp in the current line, go to that date.
3435 A prefix ARG can be used force the current date."
3436 (interactive "P")
3437 (let ((tsr org-ts-regexp) diff)
3438 (if (or (org-at-timestamp-p)
3439 (save-excursion
3440 (beginning-of-line 1)
3441 (looking-at (concat ".*" tsr))))
3442 (let ((d1 (time-to-days (current-time)))
3443 (d2 (time-to-days
3444 (org-time-string-to-time (match-string 1)))))
3445 (setq diff (- d2 d1))))
3446 (calendar)
3447 (calendar-goto-today)
3448 (if (and diff (not arg)) (calendar-forward-day diff))))
3449
3450 (defun org-date-from-calendar ()
3451 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3452 If there is already a time stamp at the cursor position, update it."
3453 (interactive)
3454 (org-timestamp-change 0 'calendar))
3455
3456 ;;; Agenda, and Diary Integration
3457
3458 ;;; Define the mode
3459
3460 (defvar org-agenda-mode-map (make-sparse-keymap)
3461 "Keymap for `org-agenda-mode'.")
3462
3463 (defvar org-agenda-menu)
3464 (defvar org-agenda-follow-mode nil)
3465 (defvar org-agenda-buffer-name "*Org Agenda*")
3466 (defvar org-agenda-redo-command nil)
3467 (defvar org-agenda-mode-hook nil)
3468
3469 ;;;###autoload
3470 (defun org-agenda-mode ()
3471 "Mode for time-sorted view on action items in Org-mode files.
3472
3473 The following commands are available:
3474
3475 \\{org-agenda-mode-map}"
3476 (interactive)
3477 (kill-all-local-variables)
3478 (setq major-mode 'org-agenda-mode)
3479 (setq mode-name "Org-Agenda")
3480 (use-local-map org-agenda-mode-map)
3481 (easy-menu-add org-agenda-menu)
3482 (if org-startup-truncated (setq truncate-lines t))
3483 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3484 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3485 (setq org-agenda-follow-mode nil)
3486 (easy-menu-change
3487 '("Agenda") "Agenda Files"
3488 (append
3489 (list
3490 ["Edit File List" (customize-variable 'org-agenda-files) t]
3491 "--")
3492 (mapcar 'org-file-menu-entry org-agenda-files)))
3493 (org-agenda-set-mode-name)
3494 (apply
3495 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3496 org-agenda-mode-hook))
3497
3498 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3499 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3500 (define-key org-agenda-mode-map " " 'org-agenda-show)
3501 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3502 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3503 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3504 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3505 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3506 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3507 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3508 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3509 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3510
3511 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3512 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3513 (while l (define-key org-agenda-mode-map
3514 (int-to-string (pop l)) 'digit-argument)))
3515
3516 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3517 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3518 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3519 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3520 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3521 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3522 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3523 (define-key org-agenda-mode-map "n" 'next-line)
3524 (define-key org-agenda-mode-map "p" 'previous-line)
3525 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3526 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3527 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3528 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3529 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3530 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3531 (eval-after-load "calendar"
3532 '(define-key calendar-mode-map org-calendar-to-agenda-key
3533 'org-calendar-goto-agenda))
3534 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3535 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3536 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3537 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3538 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3539 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3540 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3541 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3542 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3543 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3544 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3545 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3546 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3547
3548 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3549 "Local keymap for agenda entries from Org-mode.")
3550
3551 (define-key org-agenda-keymap
3552 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3553 (define-key org-agenda-keymap
3554 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3555
3556 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3557 '("Agenda"
3558 ("Agenda Files")
3559 "--"
3560 ["Show" org-agenda-show t]
3561 ["Go To (other window)" org-agenda-goto t]
3562 ["Go To (one window)" org-agenda-switch-to t]
3563 ["Follow Mode" org-agenda-follow-mode
3564 :style toggle :selected org-agenda-follow-mode :active t]
3565 "--"
3566 ["Cycle TODO" org-agenda-todo t]
3567 ("Reschedule"
3568 ["Reschedule +1 day" org-agenda-date-later t]
3569 ["Reschedule -1 day" org-agenda-date-earlier t]
3570 "--"
3571 ["Reschedule to ..." org-agenda-date-prompt t])
3572 ("Priority"
3573 ["Set Priority" org-agenda-priority t]
3574 ["Increase Priority" org-agenda-priority-up t]
3575 ["Decrease Priority" org-agenda-priority-down t]
3576 ["Show Priority" org-agenda-show-priority t])
3577 "--"
3578 ["Rebuild buffer" org-agenda-redo t]
3579 ["Goto Today" org-agenda-goto-today t]
3580 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3581 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3582 "--"
3583 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3584 :style radio :selected (equal org-agenda-ndays 1)]
3585 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3586 :style radio :selected (equal org-agenda-ndays 7)]
3587 "--"
3588 ["Include Diary" org-agenda-toggle-diary
3589 :style toggle :selected org-agenda-include-diary :active t]
3590 ["Use Time Grid" org-agenda-toggle-time-grid
3591 :style toggle :selected org-agenda-use-time-grid :active t]
3592 "--"
3593 ["New Diary Entry" org-agenda-diary-entry t]
3594 ("Calendar Commands"
3595 ["Goto Calendar" org-agenda-goto-calendar t]
3596 ["Phases of the Moon" org-agenda-phases-of-moon t]
3597 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3598 ["Holidays" org-agenda-holidays t]
3599 ["Convert" org-agenda-convert-date t])
3600 "--"
3601 ["Quit" org-agenda-quit t]
3602 ["Exit and Release Buffers" org-agenda-exit t]
3603 ))
3604
3605 (defvar org-agenda-markers nil
3606 "List of all currently active markers created by `org-agenda'.")
3607 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3608 "Creation time of the last agenda marker.")
3609
3610 (defun org-agenda-new-marker (&optional pos)
3611 "Return a new agenda marker.
3612 Org-mode keeps a list of these markers and resets them when they are
3613 no longer in use."
3614 (let ((m (copy-marker (or pos (point)))))
3615 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3616 (push m org-agenda-markers)
3617 m))
3618
3619 (defun org-agenda-maybe-reset-markers (&optional force)
3620 "Reset markers created by `org-agenda'. But only if they are old enough."
3621 (if (or force
3622 (> (- (time-to-seconds (current-time))
3623 org-agenda-last-marker-time)
3624 5))
3625 (while org-agenda-markers
3626 (move-marker (pop org-agenda-markers) nil))))
3627
3628 (defvar org-agenda-new-buffers nil
3629 "Buffers created to visit agenda files.")
3630
3631 (defun org-get-agenda-file-buffer (file)
3632 "Get a buffer visiting FILE. If the buffer needs to be created, add
3633 it to the list of buffers which might be released later."
3634 (let ((buf (find-buffer-visiting file)))
3635 (if buf
3636 buf ; just return it
3637 ;; Make a new buffer and remember it
3638 (setq buf (find-file-noselect file))
3639 (if buf (push buf org-agenda-new-buffers))
3640 buf)))
3641
3642 (defun org-release-buffers (blist)
3643 "Release all buffers in list, asking the user for confirmation when needed.
3644 When a buffer is unmodified, it is just killed. When modified, it is saved
3645 \(if the user agrees) and then killed."
3646 (let (buf file)
3647 (while (setq buf (pop blist))
3648 (setq file (buffer-file-name buf))
3649 (when (and (buffer-modified-p buf)
3650 file
3651 (y-or-n-p (format "Save file %s? " file)))
3652 (with-current-buffer buf (save-buffer)))
3653 (kill-buffer buf))))
3654
3655 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3656
3657 (defun org-timeline (&optional include-all)
3658 "Show a time-sorted view of the entries in the current org file.
3659 Only entries with a time stamp of today or later will be listed. With
3660 one \\[universal-argument] prefix argument, past entries will also be listed.
3661 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3662 under the current date.
3663 If the buffer contains an active region, only check the region for
3664 dates."
3665 (interactive "P")
3666 (require 'calendar)
3667 (org-agenda-maybe-reset-markers 'force)
3668 (org-compile-prefix-format org-timeline-prefix-format)
3669 (let* ((dopast include-all)
3670 (dotodo (equal include-all '(16)))
3671 (entry (buffer-file-name))
3672 (org-agenda-files (list (buffer-file-name)))
3673 (date (calendar-current-date))
3674 (win (selected-window))
3675 (pos1 (point))
3676 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3677 (end (if (org-region-active-p) (region-end) (point-max)))
3678 (day-numbers (org-get-all-dates beg end 'no-ranges
3679 t)) ; always include today
3680 (today (time-to-days (current-time)))
3681 (org-respect-restriction t)
3682 (past t)
3683 s e rtn d)
3684 (setq org-agenda-redo-command
3685 (list 'progn
3686 (list 'switch-to-buffer-other-window (current-buffer))
3687 (list 'org-timeline (list 'quote include-all))))
3688 (if (not dopast)
3689 ;; Remove past dates from the list of dates.
3690 (setq day-numbers (delq nil (mapcar (lambda(x)
3691 (if (>= x today) x nil))
3692 day-numbers))))
3693 (switch-to-buffer-other-window
3694 (get-buffer-create org-agenda-buffer-name))
3695 (setq buffer-read-only nil)
3696 (erase-buffer)
3697 (org-agenda-mode) (setq buffer-read-only nil)
3698 (while (setq d (pop day-numbers))
3699 (if (and (>= d today)
3700 dopast
3701 past)
3702 (progn
3703 (setq past nil)
3704 (insert (make-string 79 ?-) "\n")))
3705 (setq date (calendar-gregorian-from-absolute d))
3706 (setq s (point))
3707 (if dotodo
3708 (setq rtn (org-agenda-get-day-entries
3709 entry date :todo :timestamp))
3710 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3711 (if (or rtn (equal d today))
3712 (progn
3713 (insert (calendar-day-name date) " "
3714 (number-to-string (extract-calendar-day date)) " "
3715 (calendar-month-name (extract-calendar-month date)) " "
3716 (number-to-string (extract-calendar-year date)) "\n")
3717 (put-text-property s (1- (point)) 'face
3718 'org-link)
3719 (if (equal d today)
3720 (put-text-property s (1- (point)) 'org-today t))
3721 (insert (org-finalize-agenda-entries rtn) "\n")
3722 (put-text-property s (1- (point)) 'day d))))
3723 (goto-char (point-min))
3724 (setq buffer-read-only t)
3725 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3726 (point-min)))
3727 (when (not org-select-timeline-window)
3728 (select-window win)
3729 (goto-char pos1))))
3730
3731 ;;;###autoload
3732 (defun org-agenda (&optional include-all start-day ndays)
3733 "Produce a weekly view from all files in variable `org-agenda-files'.
3734 The view will be for the current week, but from the overview buffer you
3735 will be able to go to other weeks.
3736 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3737 also be shown, under the current date.
3738 START-DAY defaults to TODAY, or to the most recent match for the weekday
3739 given in `org-agenda-start-on-weekday'.
3740 NDAYS defaults to `org-agenda-ndays'."
3741 (interactive "P")
3742 (org-agenda-maybe-reset-markers 'force)
3743 (org-compile-prefix-format org-agenda-prefix-format)
3744 (require 'calendar)
3745 (let* ((org-agenda-start-on-weekday
3746 (if (or (equal ndays 1)
3747 (and (null ndays) (equal 1 org-agenda-ndays)))
3748 nil org-agenda-start-on-weekday))
3749 (files (copy-sequence org-agenda-files))
3750 (win (selected-window))
3751 (today (time-to-days (current-time)))
3752 (sd (or start-day today))
3753 (start (if (or (null org-agenda-start-on-weekday)
3754 (< org-agenda-ndays 7))
3755 sd
3756 (let* ((nt (calendar-day-of-week
3757 (calendar-gregorian-from-absolute sd)))
3758 (n1 org-agenda-start-on-weekday)
3759 (d (- nt n1)))
3760 (- sd (+ (if (< d 0) 7 0) d)))))
3761 (day-numbers (list start))
3762 (inhibit-redisplay t)
3763 s e rtn rtnall file date d start-pos end-pos todayp nd)
3764 (setq org-agenda-redo-command
3765 (list 'org-agenda (list 'quote include-all) start-day ndays))
3766 ;; Make the list of days
3767 (setq ndays (or ndays org-agenda-ndays)
3768 nd ndays)
3769 (while (> ndays 1)
3770 (push (1+ (car day-numbers)) day-numbers)
3771 (setq ndays (1- ndays)))
3772 (setq day-numbers (nreverse day-numbers))
3773 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3774 (progn
3775 (delete-other-windows)
3776 (switch-to-buffer-other-window
3777 (get-buffer-create org-agenda-buffer-name))))
3778 (setq buffer-read-only nil)
3779 (erase-buffer)
3780 (org-agenda-mode) (setq buffer-read-only nil)
3781 (set (make-local-variable 'starting-day) (car day-numbers))
3782 (set (make-local-variable 'include-all-loc) include-all)
3783 (when (and (or include-all org-agenda-include-all-todo)
3784 (member today day-numbers))
3785 (setq files org-agenda-files
3786 rtnall nil)
3787 (while (setq file (pop files))
3788 (catch 'nextfile
3789 (org-check-agenda-file file)
3790 (setq date (calendar-gregorian-from-absolute today)
3791 rtn (org-agenda-get-day-entries
3792 file date :todo))
3793 (setq rtnall (append rtnall rtn))))
3794 (when rtnall
3795 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3796 (add-text-properties (point-min) (1- (point))
3797 (list 'face 'org-link))
3798 (insert (org-finalize-agenda-entries rtnall) "\n")))
3799 (while (setq d (pop day-numbers))
3800 (setq date (calendar-gregorian-from-absolute d)
3801 s (point))
3802 (if (or (setq todayp (= d today))
3803 (and (not start-pos) (= d sd)))
3804 (setq start-pos (point))
3805 (if (and start-pos (not end-pos))
3806 (setq end-pos (point))))
3807 (setq files org-agenda-files
3808 rtnall nil)
3809 (while (setq file (pop files))
3810 (catch 'nextfile
3811 (org-check-agenda-file file)
3812 (setq rtn (org-agenda-get-day-entries file date))
3813 (setq rtnall (append rtnall rtn))))
3814 (if org-agenda-include-diary
3815 (progn
3816 (require 'diary-lib)
3817 (setq rtn (org-get-entries-from-diary date))
3818 (setq rtnall (append rtnall rtn))))
3819 (if (or rtnall org-agenda-show-all-dates)
3820 (progn
3821 (insert (format "%-9s %2d %s %4d\n"
3822 (calendar-day-name date)
3823 (extract-calendar-day date)
3824 (calendar-month-name (extract-calendar-month date))
3825 (extract-calendar-year date)))
3826 (put-text-property s (1- (point)) 'face
3827 'org-link)
3828 (if rtnall (insert
3829 (org-finalize-agenda-entries ;; FIXME: condition needed
3830 (org-agenda-add-time-grid-maybe
3831 rtnall nd todayp))
3832 "\n"))
3833 (put-text-property s (1- (point)) 'day d))))
3834 (goto-char (point-min))
3835 (setq buffer-read-only t)
3836 (if org-fit-agenda-window
3837 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3838 (/ (frame-height) 2)))
3839 (unless (and (pos-visible-in-window-p (point-min))
3840 (pos-visible-in-window-p (point-max)))
3841 (goto-char (1- (point-max)))
3842 (recenter -1)
3843 (if (not (pos-visible-in-window-p (or start-pos 1)))
3844 (progn
3845 (goto-char (or start-pos 1))
3846 (recenter 1))))
3847 (goto-char (or start-pos 1))
3848 (if (not org-select-agenda-window) (select-window win))
3849 (message "")))
3850
3851 (defun org-check-agenda-file (file)
3852 "Make sure FILE exists. If not, ask user what to do."
3853 ;; FIXME: this does not correctly change the menus
3854 ;; Could probably be fixed by explicitly going to the buffer.
3855 (when (not (file-exists-p file))
3856 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3857 file)
3858 (let ((r (downcase (read-char-exclusive))))
3859 (cond
3860 ((equal r ?r)
3861 (org-remove-file file)
3862 (throw 'nextfile t))
3863 (t (error "Abort"))))))
3864
3865 (defun org-agenda-quit ()
3866 "Exit agenda by removing the window or the buffer."
3867 (interactive)
3868 (let ((buf (current-buffer)))
3869 (if (not (one-window-p)) (delete-window))
3870 (kill-buffer buf)
3871 (org-agenda-maybe-reset-markers 'force)))
3872
3873 (defun org-agenda-exit ()
3874 "Exit agenda by removing the window or the buffer.
3875 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3876 Org-mode buffers visited directly by the user will not be touched."
3877 (interactive)
3878 (org-release-buffers org-agenda-new-buffers)
3879 (setq org-agenda-new-buffers nil)
3880 (org-agenda-quit))
3881
3882 (defun org-agenda-redo ()
3883 "Rebuild Agenda."
3884 (interactive)
3885 (eval org-agenda-redo-command))
3886
3887 (defun org-agenda-goto-today ()
3888 "Go to today."
3889 (interactive)
3890 (if (boundp 'starting-day)
3891 (let ((cmd (car org-agenda-redo-command))
3892 (iall (nth 1 org-agenda-redo-command))
3893 (nday (nth 3 org-agenda-redo-command)))
3894 (eval (list cmd iall nil nday)))
3895 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3896 (point-min)))))
3897
3898 (defun org-agenda-later (arg)
3899 "Go forward in time by `org-agenda-ndays' days.
3900 With prefix ARG, go forward that many times `org-agenda-ndays'."
3901 (interactive "p")
3902 (unless (boundp 'starting-day)
3903 (error "Not allowed"))
3904 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3905 (+ starting-day (* arg org-agenda-ndays))))
3906
3907 (defun org-agenda-earlier (arg)
3908 "Go back in time by `org-agenda-ndays' days.
3909 With prefix ARG, go back that many times `org-agenda-ndays'."
3910 (interactive "p")
3911 (unless (boundp 'starting-day)
3912 (error "Not allowed"))
3913 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3914 (- starting-day (* arg org-agenda-ndays))))
3915
3916 (defun org-agenda-week-view ()
3917 "Switch to weekly view for agenda."
3918 (interactive)
3919 (unless (boundp 'starting-day)
3920 (error "Not allowed"))
3921 (setq org-agenda-ndays 7)
3922 (org-agenda include-all-loc
3923 (or (get-text-property (point) 'day)
3924 starting-day))
3925 (org-agenda-set-mode-name)
3926 (message "Switched to week view"))
3927
3928 (defun org-agenda-day-view ()
3929 "Switch to weekly view for agenda."
3930 (interactive)
3931 (unless (boundp 'starting-day)
3932 (error "Not allowed"))
3933 (setq org-agenda-ndays 1)
3934 (org-agenda include-all-loc
3935 (or (get-text-property (point) 'day)
3936 starting-day))
3937 (org-agenda-set-mode-name)
3938 (message "Switched to day view"))
3939
3940 (defun org-agenda-next-date-line (&optional arg)
3941 "Jump to the next line indicating a date in agenda buffer."
3942 (interactive "p")
3943 (beginning-of-line 1)
3944 (if (looking-at "^\\S-") (forward-char 1))
3945 (if (not (re-search-forward "^\\S-" nil t arg))
3946 (progn
3947 (backward-char 1)
3948 (error "No next date after this line in this buffer")))
3949 (goto-char (match-beginning 0)))
3950
3951 (defun org-agenda-previous-date-line (&optional arg)
3952 "Jump to the next line indicating a date in agenda buffer."
3953 (interactive "p")
3954 (beginning-of-line 1)
3955 (if (not (re-search-backward "^\\S-" nil t arg))
3956 (error "No previous date before this line in this buffer")))
3957
3958 ;; Initialize the highlight
3959 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3960 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3961 'face 'highlight)
3962
3963 (defun org-highlight (begin end &optional buffer)
3964 "Highlight a region with overlay."
3965 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3966 org-hl begin end (or buffer (current-buffer))))
3967
3968 (defun org-unhighlight ()
3969 "Detach overlay INDEX."
3970 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3971
3972
3973 (defun org-agenda-follow-mode ()
3974 "Toggle follow mode in an agenda buffer."
3975 (interactive)
3976 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3977 (org-agenda-set-mode-name)
3978 (message "Follow mode is %s"
3979 (if org-agenda-follow-mode "on" "off")))
3980
3981 (defun org-agenda-toggle-diary ()
3982 "Toggle follow mode in an agenda buffer."
3983 (interactive)
3984 (setq org-agenda-include-diary (not org-agenda-include-diary))
3985 (org-agenda-redo)
3986 (org-agenda-set-mode-name)
3987 (message "Diary inclusion turned %s"
3988 (if org-agenda-include-diary "on" "off")))
3989
3990 (defun org-agenda-toggle-time-grid ()
3991 "Toggle follow mode in an agenda buffer."
3992 (interactive)
3993 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3994 (org-agenda-redo)
3995 (org-agenda-set-mode-name)
3996 (message "Time-grid turned %s"
3997 (if org-agenda-use-time-grid "on" "off")))
3998
3999 (defun org-agenda-set-mode-name ()
4000 "Set the mode name to indicate all the small mode settings."
4001 (setq mode-name
4002 (concat "Org-Agenda"
4003 (if (equal org-agenda-ndays 1) " Day" "")
4004 (if (equal org-agenda-ndays 7) " Week" "")
4005 (if org-agenda-follow-mode " Follow" "")
4006 (if org-agenda-include-diary " Diary" "")
4007 (if org-agenda-use-time-grid " Grid" "")))
4008 (force-mode-line-update))
4009
4010 (defun org-agenda-post-command-hook ()
4011 (and (eolp) (not (bolp)) (backward-char 1))
4012 (if (and org-agenda-follow-mode
4013 (get-text-property (point) 'org-marker))
4014 (org-agenda-show)))
4015
4016 (defvar org-disable-diary nil) ;Dynamically-scoped param.
4017
4018 (defun org-get-entries-from-diary (date)
4019 "Get the (Emacs Calendar) diary entries for DATE."
4020 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4021 (diary-display-hook '(fancy-diary-display))
4022 (list-diary-entries-hook
4023 (cons 'org-diary-default-entry list-diary-entries-hook))
4024 entries
4025 (org-disable-diary t))
4026 (save-excursion
4027 (save-window-excursion
4028 (list-diary-entries date 1)))
4029 (if (not (get-buffer fancy-diary-buffer))
4030 (setq entries nil)
4031 (with-current-buffer fancy-diary-buffer
4032 (setq buffer-read-only nil)
4033 (if (= (point-max) 1)
4034 ;; No entries
4035 (setq entries nil)
4036 ;; Omit the date and other unnecessary stuff
4037 (org-agenda-cleanup-fancy-diary)
4038 ;; Add prefix to each line and extend the text properties
4039 (if (= (point-max) 1)
4040 (setq entries nil)
4041 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4042 (set-buffer-modified-p nil)
4043 (kill-buffer fancy-diary-buffer)))
4044 (when entries
4045 (setq entries (org-split-string entries "\n"))
4046 (setq entries
4047 (mapcar
4048 (lambda (x)
4049 (setq x (org-format-agenda-item "" x "Diary" 'time))
4050 ;; Extend the text properties to the beginning of the line
4051 (add-text-properties
4052 0 (length x)
4053 (text-properties-at (1- (length x)) x)
4054 x)
4055 x)
4056 entries)))))
4057
4058 (defun org-agenda-cleanup-fancy-diary ()
4059 "Remove unwanted stuff in buffer created by fancy-diary-display.
4060 This gets rid of the date, the underline under the date, and
4061 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4062 date. Itt also removes lines that contain only whitespace."
4063 (goto-char (point-min))
4064 (if (looking-at ".*?:[ \t]*")
4065 (progn
4066 (replace-match "")
4067 (re-search-forward "\n=+$" nil t)
4068 (replace-match "")
4069 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4070 (re-search-forward "\n=+$" nil t)
4071 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4072 (goto-char (point-min))
4073 (while (re-search-forward "^ +\n" nil t)
4074 (replace-match ""))
4075 (goto-char (point-min))
4076 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4077 (replace-match "")))
4078
4079 ;; Advise the add-to-diary-list function to allow org to jump to
4080 ;; diary entries. Wrapped into eval-after-load to avoid loading
4081 ;; advice unnecessarily
4082 (eval-after-load "diary-lib"
4083 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
4084 "Make the position visible."
4085 (if (and org-disable-diary ;; called from org-agenda
4086 (stringp string)
4087 (buffer-file-name))
4088 (add-text-properties
4089 0 (length string)
4090 (list 'mouse-face 'highlight
4091 'keymap org-agenda-keymap
4092 'help-echo
4093 (format
4094 "mouse-2 or RET jump to diary file %s"
4095 (abbreviate-file-name (buffer-file-name)))
4096 'org-agenda-diary-link t
4097 'org-marker (org-agenda-new-marker (point-at-bol)))
4098 string))))
4099
4100 (defun org-diary-default-entry ()
4101 "Add a dummy entry to the diary.
4102 Needed to avoid empty dates which mess up holiday display."
4103 ;; Catch the error if dealing with the new add-to-diary-alist
4104 (condition-case nil
4105 (add-to-diary-list original-date "Org-mode dummy" "")
4106 (error
4107 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
4108
4109 (defun org-add-file (&optional file)
4110 "Add current file to the list of files in variable `org-agenda-files'.
4111 These are the files which are being checked for agenda entries.
4112 Optional argument FILE means, use this file instead of the current.
4113 It is possible (but not recommended) to add this function to the
4114 `org-mode-hook'."
4115 (interactive)
4116 (catch 'exit
4117 (let* ((file (or file (buffer-file-name)
4118 (if (interactive-p)
4119 (error "Buffer is not visiting a file")
4120 (throw 'exit nil))))
4121 (true-file (file-truename file))
4122 (afile (abbreviate-file-name file))
4123 (present (delq nil (mapcar
4124 (lambda (x)
4125 (equal true-file (file-truename x)))
4126 org-agenda-files))))
4127 (if (not present)
4128 (progn
4129 (setq org-agenda-files
4130 (cons afile org-agenda-files))
4131 ;; Make sure custom.el does not end up with Org-mode
4132 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4133 (customize-save-variable 'org-agenda-files org-agenda-files))
4134 (org-install-agenda-files-menu)
4135 (message "Added file: %s" afile))
4136 (message "File was already in list: %s" afile)))))
4137
4138 (defun org-remove-file (&optional file)
4139 "Remove current file from the list of files in variable `org-agenda-files'.
4140 These are the files which are being checked for agenda entries.
4141 Optional argument FILE means, use this file instead of the current."
4142 (interactive)
4143 (let* ((file (or file (buffer-file-name)))
4144 (true-file (file-truename file))
4145 (afile (abbreviate-file-name file))
4146 (files (delq nil (mapcar
4147 (lambda (x)
4148 (if (equal true-file
4149 (file-truename x))
4150 nil x))
4151 org-agenda-files))))
4152 (if (not (= (length files) (length org-agenda-files)))
4153 (progn
4154 (setq org-agenda-files files)
4155 (customize-save-variable 'org-agenda-files org-agenda-files)
4156 (org-install-agenda-files-menu)
4157 (message "Removed file: %s" afile))
4158 (message "File was not in list: %s" afile))))
4159
4160 (defun org-file-menu-entry (file)
4161 (vector file (list 'find-file file) t))
4162
4163 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4164 "Return a list of all relevant day numbers from BEG to END buffer positions.
4165 If NO-RANGES is non-nil, include only the start and end dates of a range,
4166 not every single day in the range. If FORCE-TODAY is non-nil, make
4167 sure that TODAY is included in the list."
4168 (let (dates date day day1 day2 ts1 ts2)
4169 (if force-today
4170 (setq dates (list (time-to-days (current-time)))))
4171 (save-excursion
4172 (goto-char beg)
4173 (while (re-search-forward org-ts-regexp end t)
4174 (setq day (time-to-days (org-time-string-to-time
4175 (substring (match-string 1) 0 10))))
4176 (or (memq day dates) (push day dates)))
4177 (unless no-ranges
4178 (goto-char beg)
4179 (while (re-search-forward org-tr-regexp end t)
4180 (setq ts1 (substring (match-string 1) 0 10)
4181 ts2 (substring (match-string 2) 0 10)
4182 day1 (time-to-days (org-time-string-to-time ts1))
4183 day2 (time-to-days (org-time-string-to-time ts2)))
4184 (while (< (setq day1 (1+ day1)) day2)
4185 (or (memq day1 dates) (push day1 dates)))))
4186 (sort dates '<))))
4187
4188 ;;;###autoload
4189 (defun org-diary (&rest args)
4190 "Return diary information from org-files.
4191 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4192 It accesses org files and extracts information from those files to be
4193 listed in the diary. The function accepts arguments specifying what
4194 items should be listed. The following arguments are allowed:
4195
4196 :timestamp List the headlines of items containing a date stamp or
4197 date range matching the selected date. Deadlines will
4198 also be listed, on the expiration day.
4199
4200 :deadline List any deadlines past due, or due within
4201 `org-deadline-warning-days'. The listing occurs only
4202 in the diary for *today*, not at any other date. If
4203 an entry is marked DONE, it is no longer listed.
4204
4205 :scheduled List all items which are scheduled for the given date.
4206 The diary for *today* also contains items which were
4207 scheduled earlier and are not yet marked DONE.
4208
4209 :todo List all TODO items from the org-file. This may be a
4210 long list - so this is not turned on by default.
4211 Like deadlines, these entries only show up in the
4212 diary for *today*, not at any other date.
4213
4214 The call in the diary file should look like this:
4215
4216 &%%(org-diary) ~/path/to/some/orgfile.org
4217
4218 Use a separate line for each org file to check. Or, if you omit the file name,
4219 all files listed in `org-agenda-files' will be checked automatically:
4220
4221 &%%(org-diary)
4222
4223 If you don't give any arguments (as in the example above), the default
4224 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4225 also be written as
4226
4227 &%%(org-diary :deadline :timestamp :scheduled)
4228
4229 The function expects the lisp variables `entry' and `date' to be provided
4230 by the caller, because this is how the calendar works. Don't use this
4231 function from a program - use `org-agenda-get-day-entries' instead."
4232 (org-agenda-maybe-reset-markers)
4233 (org-compile-prefix-format org-agenda-prefix-format)
4234 (setq args (or args '(:deadline :scheduled :timestamp)))
4235 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4236 (list entry)
4237 org-agenda-files))
4238 file rtn results)
4239 ;; If this is called during org-agenda, don't return any entries to
4240 ;; the calendar. Org Agenda will list these entries itself.
4241 (if org-disable-diary (setq files nil))
4242 (while (setq file (pop files))
4243 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4244 (setq results (append results rtn)))
4245 (concat (org-finalize-agenda-entries results) "\n")))
4246
4247 (defun org-agenda-get-day-entries (file date &rest args)
4248 "Does the work for `org-diary' and `org-agenda'.
4249 FILE is the path to a file to be checked for entries. DATE is date like
4250 the one returned by `calendar-current-date'. ARGS are symbols indicating
4251 which kind of entries should be extracted. For details about these, see
4252 the documentation of `org-diary'."
4253 (setq args (or args '(:deadline :scheduled :timestamp)))
4254 (let* ((org-startup-with-deadline-check nil)
4255 (org-startup-folded nil)
4256 (buffer (if (file-exists-p file)
4257 (org-get-agenda-file-buffer file)
4258 (error "No such file %s" file)))
4259 arg results rtn)
4260 (if (not buffer)
4261 ;; If file does not exist, make sure an error message ends up in diary
4262 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4263 (with-current-buffer buffer
4264 (unless (eq major-mode 'org-mode)
4265 (error "Agenda file %s is not in `org-mode'" file))
4266 (let ((case-fold-search nil))
4267 (save-excursion
4268 (save-restriction
4269 (if org-respect-restriction
4270 (if (org-region-active-p)
4271 ;; Respect a region to restrict search
4272 (narrow-to-region (region-beginning) (region-end)))
4273 ;; If we work for the calendar or many files,
4274 ;; get rid of any restriction
4275 (widen))
4276 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4277 (while (setq arg (pop args))
4278 (cond
4279 ((and (eq arg :todo)
4280 (equal date (calendar-current-date)))
4281 (setq rtn (org-agenda-get-todos))
4282 (setq results (append results rtn)))
4283 ((eq arg :timestamp)
4284 (setq rtn (org-agenda-get-blocks))
4285 (setq results (append results rtn))
4286 (setq rtn (org-agenda-get-timestamps))
4287 (setq results (append results rtn)))
4288 ((eq arg :scheduled)
4289 (setq rtn (org-agenda-get-scheduled))
4290 (setq results (append results rtn)))
4291 ((and (eq arg :deadline)
4292 (equal date (calendar-current-date)))
4293 (setq rtn (org-agenda-get-deadlines))
4294 (setq results (append results rtn))))))))
4295 results))))
4296
4297 (defun org-entry-is-done-p ()
4298 "Is the current entry marked DONE?"
4299 (save-excursion
4300 (and (re-search-backward "[\r\n]\\*" nil t)
4301 (looking-at org-nl-done-regexp))))
4302
4303 (defun org-at-date-range-p ()
4304 "Is the cursor inside a date range?"
4305 (interactive)
4306 (save-excursion
4307 (catch 'exit
4308 (let ((pos (point)))
4309 (skip-chars-backward "^<\r\n")
4310 (skip-chars-backward "<")
4311 (and (looking-at org-tr-regexp)
4312 (>= (match-end 0) pos)
4313 (throw 'exit t))
4314 (skip-chars-backward "^<\r\n")
4315 (skip-chars-backward "<")
4316 (and (looking-at org-tr-regexp)
4317 (>= (match-end 0) pos)
4318 (throw 'exit t)))
4319 nil)))
4320
4321 (defun org-agenda-get-todos ()
4322 "Return the TODO information for agenda display."
4323 (let* ((props (list 'face nil
4324 'done-face 'org-done
4325 'mouse-face 'highlight
4326 'keymap org-agenda-keymap
4327 'help-echo
4328 (format "mouse-2 or RET jump to org file %s"
4329 (abbreviate-file-name (buffer-file-name)))))
4330 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4331 "[^\n\r]*\\)"))
4332 marker priority
4333 ee txt)
4334 (goto-char (point-min))
4335 (while (re-search-forward regexp nil t)
4336 (goto-char (match-beginning 1))
4337 (setq marker (org-agenda-new-marker (point-at-bol))
4338 txt (org-format-agenda-item "" (match-string 1))
4339 priority
4340 (+ (org-get-priority txt)
4341 (if org-todo-kwd-priority-p
4342 (- org-todo-kwd-max-priority -2
4343 (length
4344 (member (match-string 2) org-todo-keywords)))
4345 1)))
4346 (add-text-properties
4347 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4348 'priority priority)
4349 props)
4350 txt)
4351 (push txt ee)
4352 (goto-char (match-end 1)))
4353 (nreverse ee)))
4354
4355 (defconst org-agenda-no-heading-message
4356 "No heading for this item in buffer or region")
4357
4358 (defun org-agenda-get-timestamps ()
4359 "Return the date stamp information for agenda display."
4360 (let* ((props (list 'face nil
4361 'mouse-face 'highlight
4362 'keymap org-agenda-keymap
4363 'help-echo
4364 (format "mouse-2 or RET jump to org file %s"
4365 (abbreviate-file-name (buffer-file-name)))))
4366 (regexp (regexp-quote
4367 (substring
4368 (format-time-string
4369 (car org-time-stamp-formats)
4370 (apply 'encode-time ; DATE bound by calendar
4371 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4372 0 11)))
4373 marker hdmarker deadlinep scheduledp donep tmp priority
4374 ee txt timestr)
4375 (goto-char (point-min))
4376 (while (re-search-forward regexp nil t)
4377 (if (not (save-match-data (org-at-date-range-p)))
4378 (progn
4379 (setq marker (org-agenda-new-marker (match-beginning 0))
4380 tmp (buffer-substring (max (point-min)
4381 (- (match-beginning 0)
4382 org-ds-keyword-length))
4383 (match-beginning 0))
4384 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4385 deadlinep (string-match org-deadline-regexp tmp)
4386 scheduledp (string-match org-scheduled-regexp tmp)
4387 donep (org-entry-is-done-p))
4388 (if (string-match ">" timestr)
4389 ;; substring should only run to end of time stamp
4390 (setq timestr (substring timestr 0 (match-end 0))))
4391 (save-excursion
4392 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4393 (progn
4394 (goto-char (match-end 1))
4395 (setq hdmarker (org-agenda-new-marker))
4396 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4397 (setq txt (org-format-agenda-item
4398 (format "%s%s"
4399 (if deadlinep "Deadline: " "")
4400 (if scheduledp "Scheduled: " ""))
4401 (match-string 1) nil timestr)))
4402 (setq txt org-agenda-no-heading-message))
4403 (setq priority (org-get-priority txt))
4404 (add-text-properties
4405 0 (length txt) (append (list 'org-marker marker
4406 'org-hd-marker hdmarker) props)
4407 txt)
4408 (if deadlinep
4409 (add-text-properties
4410 0 (length txt)
4411 (list 'face
4412 (if donep 'org-done 'org-warning)
4413 'undone-face 'org-warning
4414 'done-face 'org-done
4415 'priority (+ 100 priority))
4416 txt)
4417 (if scheduledp
4418 (add-text-properties
4419 0 (length txt)
4420 (list 'face 'org-scheduled-today
4421 'undone-face 'org-scheduled-today
4422 'done-face 'org-done
4423 priority (+ 99 priority))
4424 txt)
4425 (add-text-properties
4426 0 (length txt)
4427 (list 'priority priority) txt)))
4428 (push txt ee))
4429 (outline-next-heading))))
4430 (nreverse ee)))
4431
4432 (defun org-agenda-get-deadlines ()
4433 "Return the deadline information for agenda display."
4434 (let* ((wdays org-deadline-warning-days)
4435 (props (list 'mouse-face 'highlight
4436 'keymap org-agenda-keymap
4437 'help-echo
4438 (format "mouse-2 or RET jump to org file %s"
4439 (abbreviate-file-name (buffer-file-name)))))
4440 (regexp org-deadline-time-regexp)
4441 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4442 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4443 d2 diff pos pos1
4444 ee txt head)
4445 (goto-char (point-min))
4446 (while (re-search-forward regexp nil t)
4447 (setq pos (1- (match-beginning 1))
4448 d2 (time-to-days
4449 (org-time-string-to-time (match-string 1)))
4450 diff (- d2 d1))
4451 ;; When to show a deadline in the calendar:
4452 ;; If the expiration is within wdays warning time.
4453 ;; Past-due deadlines are only shown on the current date
4454 (if (and (< diff wdays) todayp (not (= diff 0)))
4455 (save-excursion
4456 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4457 (progn
4458 (goto-char (match-end 0))
4459 (setq pos1 (match-end 1))
4460 (setq head (buffer-substring-no-properties
4461 (point)
4462 (progn (skip-chars-forward "^\r\n")
4463 (point))))
4464 (if (string-match org-looking-at-done-regexp head)
4465 (setq txt nil)
4466 (setq txt (org-format-agenda-item
4467 (format "In %3d d.: " diff) head))))
4468 (setq txt org-agenda-no-heading-message))
4469 (when txt
4470 (add-text-properties
4471 0 (length txt)
4472 (append
4473 (list 'org-marker (org-agenda-new-marker pos)
4474 'org-hd-marker (org-agenda-new-marker pos1)
4475 'priority (+ (- 10 diff) (org-get-priority txt))
4476 'face (cond ((<= diff 0) 'org-warning)
4477 ((<= diff 5) 'org-scheduled-previously)
4478 (t nil))
4479 'undone-face (cond
4480 ((<= diff 0) 'org-warning)
4481 ((<= diff 5) 'org-scheduled-previously)
4482 (t nil))
4483 'done-face 'org-done)
4484 props)
4485 txt)
4486 (push txt ee)))))
4487 ee))
4488
4489 (defun org-agenda-get-scheduled ()
4490 "Return the scheduled information for agenda display."
4491 (let* ((props (list 'face 'org-scheduled-previously
4492 'undone-face 'org-scheduled-previously
4493 'done-face 'org-done
4494 'mouse-face 'highlight
4495 'keymap org-agenda-keymap
4496 'help-echo
4497 (format "mouse-2 or RET jump to org file %s"
4498 (abbreviate-file-name (buffer-file-name)))))
4499 (regexp org-scheduled-time-regexp)
4500 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4501 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4502 d2 diff pos pos1
4503 ee txt head)
4504 (goto-char (point-min))
4505 (while (re-search-forward regexp nil t)
4506 (setq pos (1- (match-beginning 1))
4507 d2 (time-to-days
4508 (org-time-string-to-time (match-string 1)))
4509 diff (- d2 d1))
4510 ;; When to show a scheduled item in the calendar:
4511 ;; If it is on or past the date.
4512 (if (and (< diff 0) todayp)
4513 (save-excursion
4514 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4515 (progn
4516 (goto-char (match-end 0))
4517 (setq pos1 (match-end 1))
4518 (setq head (buffer-substring-no-properties
4519 (point)
4520 (progn (skip-chars-forward "^\r\n") (point))))
4521 (if (string-match org-looking-at-done-regexp head)
4522 (setq txt nil)
4523 (setq txt (org-format-agenda-item
4524 (format "Sched.%2dx: " (- 1 diff)) head))))
4525 (setq txt org-agenda-no-heading-message))
4526 (when txt
4527 (add-text-properties
4528 0 (length txt)
4529 (append (list 'org-marker (org-agenda-new-marker pos)
4530 'org-hd-marker (org-agenda-new-marker pos1)
4531 'priority (+ (- 5 diff) (org-get-priority txt)))
4532 props) txt)
4533 (push txt ee)))))
4534 ee))
4535
4536 (defun org-agenda-get-blocks ()
4537 "Return the date-range information for agenda display."
4538 (let* ((props (list 'face nil
4539 'mouse-face 'highlight
4540 'keymap org-agenda-keymap
4541 'help-echo
4542 (format "mouse-2 or RET jump to org file %s"
4543 (abbreviate-file-name (buffer-file-name)))))
4544 (regexp org-tr-regexp)
4545 (d0 (calendar-absolute-from-gregorian date))
4546 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4547 (goto-char (point-min))
4548 (while (re-search-forward regexp nil t)
4549 (setq timestr (match-string 0)
4550 s1 (match-string 1)
4551 s2 (match-string 2)
4552 d1 (time-to-days (org-time-string-to-time s1))
4553 d2 (time-to-days (org-time-string-to-time s2)))
4554 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4555 ;; Only allow days between the limits, because the normal
4556 ;; date stamps will catch the limits.
4557 (save-excursion
4558 (setq marker (org-agenda-new-marker (point)))
4559 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4560 (progn
4561 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4562 (goto-char (match-end 1))
4563 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4564 (setq txt (org-format-agenda-item
4565 (format (if (= d1 d2) "" "(%d/%d): ")
4566 (1+ (- d0 d1)) (1+ (- d2 d1)))
4567 (match-string 1) nil (if (= d0 d1) timestr))))
4568 (setq txt org-agenda-no-heading-message))
4569 (add-text-properties
4570 0 (length txt) (append (list 'org-marker marker
4571 'org-hd-marker hdmarker
4572 'priority (org-get-priority txt))
4573 props)
4574 txt)
4575 (push txt ee)))
4576 (outline-next-heading))
4577 ;; Sort the entries by expiration date.
4578 (nreverse ee)))
4579
4580
4581
4582 (defconst org-plain-time-of-day-regexp
4583 (concat
4584 "\\(\\<[012]?[0-9]"
4585 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4586 "\\(--?"
4587 "\\(\\<[012]?[0-9]"
4588 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4589 "\\)?")
4590 "Regular expression to match a plain time or time range.
4591 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4592 groups carry important information:
4593 0 the full match
4594 1 the first time, range or not
4595 8 the second time, if it is a range.")
4596
4597 (defconst org-stamp-time-of-day-regexp
4598 (concat
4599 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4600 "\\([012][0-9]:[0-5][0-9]\\)>"
4601 "\\(--?"
4602 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4603 "Regular expression to match a timestamp time or time range.
4604 After a match, the following groups carry important information:
4605 0 the full match
4606 1 date plus weekday, for backreferencing to make sure both times on same day
4607 2 the first time, range or not
4608 4 the second time, if it is a range.")
4609
4610 (defvar org-prefix-has-time nil
4611 "A flag, set by `org-compile-prefix-format'.
4612 The flag is set if the currently compiled format contains a `%t'.")
4613
4614 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4615 "Format TXT to be inserted into the agenda buffer.
4616 In particular, it adds the prefix and corresponding text properties. EXTRA
4617 must be a string and replaces the `%s' specifier in the prefix format.
4618 CATEGORY (string, symbol or nil) may be used to overule the default
4619 category taken from local variable or file name. It will replace the `%c'
4620 specifier in the format. DOTIME, when non-nil, indicates that a
4621 time-of-day should be extracted from TXT for sorting of this entry, and for
4622 the `%t' specifier in the format. When DOTIME is a string, this string is
4623 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4624 only the correctly processes TXT should be returned - this is used by
4625 `org-agenda-change-all-lines'."
4626 (save-match-data
4627 ;; Diary entries sometimes have extra whitespace at the beginning
4628 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4629 (let* ((category (or category
4630 org-category
4631 (if (buffer-file-name)
4632 (file-name-sans-extension
4633 (file-name-nondirectory (buffer-file-name)))
4634 "")))
4635 time ;; needed for the eval of the prefix format
4636 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4637 (time-of-day (and dotime (org-get-time-of-day ts)))
4638 stamp plain s0 s1 s2 rtn)
4639 (when (and dotime time-of-day org-prefix-has-time)
4640 ;; Extract starting and ending time and move them to prefix
4641 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4642 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4643 (setq s0 (match-string 0 ts)
4644 s1 (match-string (if plain 1 2) ts)
4645 s2 (match-string (if plain 8 4) ts))
4646
4647 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4648 ;; them, we might want to remove them there to avoid duplication.
4649 ;; The user can turn this off with a variable.
4650 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4651 (string-match (concat (regexp-quote s0) " *") txt)
4652 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4653 (= (match-beginning 0) 0)
4654 t))
4655 (setq txt (replace-match "" nil nil txt))))
4656 ;; Normalize the time(s) to 24 hour
4657 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4658 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4659
4660 ;; Create the final string
4661 (if noprefix
4662 (setq rtn txt)
4663 ;; Prepare the variables needed in the eval of the compiled format
4664 (setq time (cond (s2 (concat s1 "-" s2))
4665 (s1 (concat s1 "......"))
4666 (t ""))
4667 extra (or extra "")
4668 category (if (symbolp category) (symbol-name category) category))
4669 ;; Evaluate the compiled format
4670 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4671
4672 ;; And finally add the text properties
4673 (add-text-properties
4674 0 (length rtn) (list 'category (downcase category)
4675 'prefix-length (- (length rtn) (length txt))
4676 'time-of-day time-of-day
4677 'dotime dotime)
4678 rtn)
4679 rtn)))
4680
4681 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4682 (catch 'exit
4683 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4684 ((and todayp (member 'today (car org-agenda-time-grid))))
4685 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4686 ((member 'weekly (car org-agenda-time-grid)))
4687 (t (throw 'exit list)))
4688 (let* ((have (delq nil (mapcar
4689 (lambda (x) (get-text-property 1 'time-of-day x))
4690 list)))
4691 (string (nth 1 org-agenda-time-grid))
4692 (gridtimes (nth 2 org-agenda-time-grid))
4693 (req (car org-agenda-time-grid))
4694 (remove (member 'remove-match req))
4695 new time)
4696 (if (and (member 'require-timed req) (not have))
4697 ;; don't show empty grid
4698 (throw 'exit list))
4699 (while (setq time (pop gridtimes))
4700 (unless (and remove (member time have))
4701 (setq time (int-to-string time))
4702 (push (org-format-agenda-item
4703 nil string "" ;; FIXME: put a category?
4704 (concat (substring time 0 -2) ":" (substring time -2)))
4705 new)
4706 (put-text-property
4707 1 (length (car new)) 'face 'org-time-grid (car new))))
4708 (if (member 'time-up org-agenda-sorting-strategy)
4709 (append new list)
4710 (append list new)))))
4711
4712 (defun org-compile-prefix-format (format)
4713 "Compile the prefix format into a Lisp form that can be evaluated.
4714 The resulting form is returned and stored in the variable
4715 `org-prefix-format-compiled'."
4716 (setq org-prefix-has-time nil)
4717 (let ((start 0) varform vars var (s format) c f opt)
4718 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4719 s start)
4720 (setq var (cdr (assoc (match-string 4 s)
4721 '(("c" . category) ("t" . time) ("s" . extra))))
4722 c (or (match-string 3 s) "")
4723 opt (match-beginning 1)
4724 start (1+ (match-beginning 0)))
4725 (if (equal var 'time) (setq org-prefix-has-time t))
4726 (setq f (concat "%" (match-string 2 s) "s"))
4727 (if opt
4728 (setq varform
4729 `(if (equal "" ,var)
4730 ""
4731 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4732 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4733 (setq s (replace-match "%s" t nil s))
4734 (push varform vars))
4735 (setq vars (nreverse vars))
4736 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4737
4738 (defun org-get-time-of-day (s &optional string)
4739 "Check string S for a time of day.
4740 If found, return it as a military time number between 0 and 2400.
4741 If not found, return nil.
4742 The optional STRING argument forces conversion into a 5 character wide string
4743 HH:MM."
4744 (save-match-data
4745 (when
4746 (or
4747 (string-match
4748 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4749 (string-match
4750 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4751 (let* ((t0 (+ (* 100
4752 (+ (string-to-number (match-string 1 s))
4753 (if (and (match-beginning 4)
4754 (equal (downcase (match-string 4 s)) "pm"))
4755 12 0)))
4756 (if (match-beginning 3)
4757 (string-to-number (match-string 3 s))
4758 0)))
4759 (t1 (concat " " (int-to-string t0))))
4760 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4761
4762 (defun org-finalize-agenda-entries (list)
4763 "Sort and concatenate the agenda items."
4764 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4765
4766 (defsubst org-cmp-priority (a b)
4767 "Compare the priorities of string a and b."
4768 (let ((pa (or (get-text-property 1 'priority a) 0))
4769 (pb (or (get-text-property 1 'priority b) 0)))
4770 (cond ((> pa pb) +1)
4771 ((< pa pb) -1)
4772 (t nil))))
4773
4774 (defsubst org-cmp-category (a b)
4775 "Compare the string values of categories of strings a and b."
4776 (let ((ca (or (get-text-property 1 'category a) ""))
4777 (cb (or (get-text-property 1 'category b) "")))
4778 (cond ((string-lessp ca cb) -1)
4779 ((string-lessp cb ca) +1)
4780 (t nil))))
4781
4782 (defsubst org-cmp-time (a b)
4783 "Compare the time-of-day values of strings a and b."
4784 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4785 (ta (or (get-text-property 1 'time-of-day a) def))
4786 (tb (or (get-text-property 1 'time-of-day b) def)))
4787 (cond ((< ta tb) -1)
4788 ((< tb ta) +1)
4789 (t nil))))
4790
4791 (defun org-entries-lessp (a b)
4792 "Predicate for sorting agenda entries."
4793 ;; The following variables will be used when the form is evaluated.
4794 (let* ((time-up (org-cmp-time a b))
4795 (time-down (if time-up (- time-up) nil))
4796 (priority-up (org-cmp-priority a b))
4797 (priority-down (if priority-up (- priority-up) nil))
4798 (category-up (org-cmp-category a b))
4799 (category-down (if category-up (- category-up) nil))
4800 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4801 (cdr (assoc
4802 (eval (cons 'or org-agenda-sorting-strategy))
4803 '((-1 . t) (1 . nil) (nil . nil))))))
4804
4805 (defun org-agenda-show-priority ()
4806 "Show the priority of the current item.
4807 This priority is composed of the main priority given with the [#A] cookies,
4808 and by additional input from the age of a schedules or deadline entry."
4809 (interactive)
4810 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4811 (message "Priority is %d" (if pri pri -1000))))
4812
4813 (defun org-agenda-goto (&optional highlight)
4814 "Go to the Org-mode file which contains the item at point."
4815 (interactive)
4816 (let* ((marker (or (get-text-property (point) 'org-marker)
4817 (org-agenda-error)))
4818 (buffer (marker-buffer marker))
4819 (pos (marker-position marker)))
4820 (switch-to-buffer-other-window buffer)
4821 (widen)
4822 (goto-char pos)
4823 (when (eq major-mode 'org-mode)
4824 (org-show-hidden-entry)
4825 (save-excursion
4826 (and (outline-next-heading)
4827 (org-flag-heading nil)))) ; show the next heading
4828 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4829
4830 (defun org-agenda-switch-to ()
4831 "Go to the Org-mode file which contains the item at point."
4832 (interactive)
4833 (let* ((marker (or (get-text-property (point) 'org-marker)
4834 (org-agenda-error)))
4835 (buffer (marker-buffer marker))
4836 (pos (marker-position marker)))
4837 (switch-to-buffer buffer)
4838 (delete-other-windows)
4839 (widen)
4840 (goto-char pos)
4841 (when (eq major-mode 'org-mode)
4842 (org-show-hidden-entry)
4843 (save-excursion
4844 (and (outline-next-heading)
4845 (org-flag-heading nil)))))) ; show the next heading
4846
4847 (defun org-agenda-goto-mouse (ev)
4848 "Go to the Org-mode file which contains the item at the mouse click."
4849 (interactive "e")
4850 (mouse-set-point ev)
4851 (org-agenda-goto))
4852
4853 (defun org-agenda-show ()
4854 "Display the Org-mode file which contains the item at point."
4855 (interactive)
4856 (let ((win (selected-window)))
4857 (org-agenda-goto t)
4858 (select-window win)))
4859
4860 (defun org-agenda-recenter (arg)
4861 "Display the Org-mode file which contains the item at point and recenter."
4862 (interactive "P")
4863 (let ((win (selected-window)))
4864 (org-agenda-goto t)
4865 (recenter arg)
4866 (select-window win)))
4867
4868 (defun org-agenda-show-mouse (ev)
4869 "Display the Org-mode file which contains the item at the mouse click."
4870 (interactive "e")
4871 (mouse-set-point ev)
4872 (org-agenda-show))
4873
4874 (defun org-agenda-check-no-diary ()
4875 "Check if the entry is a diary link and abort if yes."
4876 (if (get-text-property (point) 'org-agenda-diary-link)
4877 (org-agenda-error)))
4878
4879 (defun org-agenda-error ()
4880 (error "Command not allowed in this line"))
4881
4882 (defvar org-last-heading-marker (make-marker)
4883 "Marker pointing to the headline that last changed its TODO state
4884 by a remote command from the agenda.")
4885
4886 (defun org-agenda-todo ()
4887 "Cycle TODO state of line at point, also in Org-mode file.
4888 This changes the line at point, all other lines in the agenda referring to
4889 the same tree node, and the headline of the tree node in the Org-mode file."
4890 (interactive)
4891 (org-agenda-check-no-diary)
4892 (let* ((col (current-column))
4893 (marker (or (get-text-property (point) 'org-marker)
4894 (org-agenda-error)))
4895 (buffer (marker-buffer marker))
4896 (pos (marker-position marker))
4897 (hdmarker (get-text-property (point) 'org-hd-marker))
4898 (buffer-read-only nil)
4899 newhead)
4900 (with-current-buffer buffer
4901 (widen)
4902 (goto-char pos)
4903 (org-show-hidden-entry)
4904 (save-excursion
4905 (and (outline-next-heading)
4906 (org-flag-heading nil))) ; show the next heading
4907 (org-todo)
4908 (forward-char 1)
4909 (setq newhead (org-get-heading))
4910 (save-excursion
4911 (org-back-to-heading)
4912 (move-marker org-last-heading-marker (point))))
4913 (beginning-of-line 1)
4914 (save-excursion
4915 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4916 (move-to-column col)))
4917
4918 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4919 "Change all lines in the agenda buffer which match hdmarker.
4920 The new content of the line will be NEWHEAD (as modified by
4921 `org-format-agenda-item'). HDMARKER is checked with
4922 `equal' against all `org-hd-marker' text properties in the file.
4923 If FIXFACE is non-nil, the face of each item is modified acording to
4924 the new TODO state."
4925 (let* (props m pl undone-face done-face finish new dotime)
4926 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4927 (save-excursion
4928 (goto-char (point-max))
4929 (beginning-of-line 1)
4930 (while (not finish)
4931 (setq finish (bobp))
4932 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4933 (equal m hdmarker))
4934 (setq props (text-properties-at (point))
4935 dotime (get-text-property (point) 'dotime)
4936 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4937 pl (get-text-property (point) 'prefix-length)
4938 undone-face (get-text-property (point) 'undone-face)
4939 done-face (get-text-property (point) 'done-face))
4940 (move-to-column pl)
4941 (if (looking-at ".*")
4942 (progn
4943 (replace-match new t t)
4944 (beginning-of-line 1)
4945 (add-text-properties (point-at-bol) (point-at-eol) props)
4946 (if fixface
4947 (add-text-properties
4948 (point-at-bol) (point-at-eol)
4949 (list 'face
4950 (if org-last-todo-state-is-todo
4951 undone-face done-face))))
4952 (beginning-of-line 1))
4953 (error "Line update did not work")))
4954 (beginning-of-line 0)))))
4955
4956 (defun org-agenda-priority-up ()
4957 "Increase the priority of line at point, also in Org-mode file."
4958 (interactive)
4959 (org-agenda-priority 'up))
4960
4961 (defun org-agenda-priority-down ()
4962 "Decrease the priority of line at point, also in Org-mode file."
4963 (interactive)
4964 (org-agenda-priority 'down))
4965
4966 (defun org-agenda-priority (&optional force-direction)
4967 "Set the priority of line at point, also in Org-mode file.
4968 This changes the line at point, all other lines in the agenda referring to
4969 the same tree node, and the headline of the tree node in the Org-mode file."
4970 (interactive)
4971 (org-agenda-check-no-diary)
4972 (let* ((marker (or (get-text-property (point) 'org-marker)
4973 (org-agenda-error)))
4974 (buffer (marker-buffer marker))
4975 (pos (marker-position marker))
4976 (hdmarker (get-text-property (point) 'org-hd-marker))
4977 (buffer-read-only nil)
4978 newhead)
4979 (with-current-buffer buffer
4980 (widen)
4981 (goto-char pos)
4982 (org-show-hidden-entry)
4983 (save-excursion
4984 (and (outline-next-heading)
4985 (org-flag-heading nil))) ; show the next heading
4986 (funcall 'org-priority force-direction)
4987 (end-of-line 1)
4988 (setq newhead (org-get-heading)))
4989 (org-agenda-change-all-lines newhead hdmarker)
4990 (beginning-of-line 1)))
4991
4992 (defun org-agenda-date-later (arg &optional what)
4993 "Change the date of this item to one day later."
4994 (interactive "p")
4995 (org-agenda-check-no-diary)
4996 (let* ((marker (or (get-text-property (point) 'org-marker)
4997 (org-agenda-error)))
4998 (buffer (marker-buffer marker))
4999 (pos (marker-position marker)))
5000 (with-current-buffer buffer
5001 (widen)
5002 (goto-char pos)
5003 (if (not (org-at-timestamp-p))
5004 (error "Cannot find time stamp"))
5005 (org-timestamp-change arg (or what 'day))
5006 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5007
5008 (defun org-agenda-date-earlier (arg &optional what)
5009 "Change the date of this item to one day earlier."
5010 (interactive "p")
5011 (org-agenda-date-later (- arg) what))
5012
5013 (defun org-agenda-date-prompt (arg)
5014 "Change the date of this item. Date is prompted for, with default today.
5015 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5016 be used to request time specification in the time stamp."
5017 (interactive "P")
5018 (org-agenda-check-no-diary)
5019 (let* ((marker (or (get-text-property (point) 'org-marker)
5020 (org-agenda-error)))
5021 (buffer (marker-buffer marker))
5022 (pos (marker-position marker)))
5023 (with-current-buffer buffer
5024 (widen)
5025 (goto-char pos)
5026 (if (not (org-at-timestamp-p))
5027 (error "Cannot find time stamp"))
5028 (org-time-stamp arg)
5029 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5030
5031 (defun org-get-heading ()
5032 "Return the heading of the current entry, without the stars."
5033 (save-excursion
5034 (if (and (re-search-backward "[\r\n]\\*" nil t)
5035 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5036 (match-string 1)
5037 "")))
5038
5039 (defun org-agenda-diary-entry ()
5040 "Make a diary entry, like the `i' command from the calendar.
5041 All the standard commands work: block, weekly etc"
5042 (interactive)
5043 (require 'diary-lib)
5044 (let* ((char (progn
5045 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5046 (read-char-exclusive)))
5047 (cmd (cdr (assoc char
5048 '((?d . insert-diary-entry)
5049 (?w . insert-weekly-diary-entry)
5050 (?m . insert-monthly-diary-entry)
5051 (?y . insert-yearly-diary-entry)
5052 (?a . insert-anniversary-diary-entry)
5053 (?b . insert-block-diary-entry)
5054 (?c . insert-cyclic-diary-entry)))))
5055 (oldf (symbol-function 'calendar-cursor-to-date))
5056 (point (point))
5057 (mark (or (mark t) (point))))
5058 (unless cmd
5059 (error "No command associated with <%c>" char))
5060 (unless (and (get-text-property point 'day)
5061 (or (not (equal ?b char))
5062 (get-text-property mark 'day)))
5063 (error "Don't know which date to use for diary entry"))
5064 ;; We implement this by hacking the `calendar-cursor-to-date' function
5065 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5066 (let ((calendar-mark-ring
5067 (list (calendar-gregorian-from-absolute
5068 (or (get-text-property mark 'day)
5069 (get-text-property point 'day))))))
5070 (unwind-protect
5071 (progn
5072 (fset 'calendar-cursor-to-date
5073 (lambda (&optional error)
5074 (calendar-gregorian-from-absolute
5075 (get-text-property point 'day))))
5076 (call-interactively cmd))
5077 (fset 'calendar-cursor-to-date oldf)))))
5078
5079
5080 (defun org-agenda-execute-calendar-command (cmd)
5081 "Execute a calendar command from the agenda, with the date associated to
5082 the cursor position."
5083 (require 'diary-lib)
5084 (unless (get-text-property (point) 'day)
5085 (error "Don't know which date to use for calendar command"))
5086 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5087 (point (point))
5088 (date (calendar-gregorian-from-absolute
5089 (get-text-property point 'day)))
5090 (displayed-day (extract-calendar-day date))
5091 (displayed-month (extract-calendar-month date))
5092 (displayed-year (extract-calendar-year date)))
5093 (unwind-protect
5094 (progn
5095 (fset 'calendar-cursor-to-date
5096 (lambda (&optional error)
5097 (calendar-gregorian-from-absolute
5098 (get-text-property point 'day))))
5099 (call-interactively cmd))
5100 (fset 'calendar-cursor-to-date oldf))))
5101
5102 (defun org-agenda-phases-of-moon ()
5103 "Display the phases of the moon for the 3 months around the cursor date."
5104 (interactive)
5105 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5106
5107 (defun org-agenda-holidays ()
5108 "Display the holidays for the 3 months around the cursor date."
5109 (interactive)
5110 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5111
5112 (defun org-agenda-sunrise-sunset (arg)
5113 "Display sunrise and sunset for the cursor date.
5114 Latitude and longitude can be specified with the variables
5115 `calendar-latitude' and `calendar-longitude'. When called with prefix
5116 argument, latitude and longitude will be prompted for."
5117 (interactive "P")
5118 (let ((calendar-longitude (if arg nil calendar-longitude))
5119 (calendar-latitude (if arg nil calendar-latitude))
5120 (calendar-location-name
5121 (if arg "the given coordinates" calendar-location-name)))
5122 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5123
5124 (defun org-agenda-goto-calendar ()
5125 "Open the Emacs calendar with the date at the cursor."
5126 (interactive)
5127 (let* ((day (or (get-text-property (point) 'day)
5128 (error "Don't know which date to open in calendar")))
5129 (date (calendar-gregorian-from-absolute day)))
5130 (calendar)
5131 (calendar-goto-date date)))
5132
5133 (defun org-calendar-goto-agenda ()
5134 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5135 This is a command that has to be installed in `calendar-mode-map'."
5136 (interactive)
5137 (org-agenda nil (calendar-absolute-from-gregorian
5138 (calendar-cursor-to-date))))
5139
5140 (defun org-agenda-convert-date ()
5141 (interactive)
5142 (let ((day (get-text-property (point) 'day))
5143 date s)
5144 (unless day
5145 (error "Don't know which date to convert"))
5146 (setq date (calendar-gregorian-from-absolute day))
5147 (setq s (concat
5148 "Gregorian: " (calendar-date-string date) "\n"
5149 "ISO: " (calendar-iso-date-string date) "\n"
5150 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5151 "Julian: " (calendar-julian-date-string date) "\n"
5152 "Astron. JD: " (calendar-astro-date-string date)
5153 " (Julian date number at noon UTC)\n"
5154 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5155 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5156 "French: " (calendar-french-date-string date) "\n"
5157 "Mayan: " (calendar-mayan-date-string date) "\n"
5158 "Coptic: " (calendar-coptic-date-string date) "\n"
5159 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5160 "Persian: " (calendar-persian-date-string date) "\n"
5161 "Chinese: " (calendar-chinese-date-string date) "\n"))
5162 (with-output-to-temp-buffer "*Dates*"
5163 (princ s))
5164 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5165
5166 ;;; Link Stuff
5167
5168 (defun org-find-file-at-mouse (ev)
5169 "Open file link or URL at mouse."
5170 (interactive "e")
5171 (mouse-set-point ev)
5172 (org-open-at-point 'in-emacs))
5173
5174 (defun org-open-at-mouse (ev)
5175 "Open file link or URL at mouse."
5176 (interactive "e")
5177 (mouse-set-point ev)
5178 (org-open-at-point))
5179
5180 (defun org-open-at-point (&optional in-emacs)
5181 "Open link at or after point.
5182 If there is no link at point, this function will search forward up to
5183 the end of the current subtree.
5184 Normally, files will be opened by an appropriate application. If the
5185 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5186 (interactive "P")
5187 (if (org-at-timestamp-p)
5188 (org-agenda nil (time-to-days (org-time-string-to-time
5189 (substring (match-string 1) 0 10)))
5190 1)
5191 (let (type path line (pos (point)))
5192 (save-excursion
5193 (skip-chars-backward
5194 (concat (if org-allow-space-in-links "^" "^ ")
5195 org-non-link-chars))
5196 (if (re-search-forward
5197 org-link-regexp
5198 (save-excursion
5199 (condition-case nil
5200 (progn (outline-end-of-subtree) (max pos (point)))
5201 (error (end-of-line 1) (point))))
5202 t)
5203 (setq type (match-string 1)
5204 path (match-string 2)))
5205 (unless path
5206 (error "No link found"))
5207 ;; Remove any trailing spaces in path
5208 (if (string-match " +\\'" path)
5209 (setq path (replace-match "" t t path)))
5210
5211 (cond
5212
5213 ((string= type "file")
5214 (if (string-match ":\\([0-9]+\\)\\'" path)
5215 (setq line (string-to-number (match-string 1 path))
5216 path (substring path 0 (match-beginning 0))))
5217 (org-open-file path in-emacs line))
5218
5219 ((string= type "news")
5220 (org-follow-gnus-link path))
5221
5222 ((string= type "bbdb")
5223 (org-follow-bbdb-link path))
5224
5225 ((string= type "gnus")
5226 (let (group article)
5227 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5228 (error "Error in Gnus link"))
5229 (setq group (match-string 1 path)
5230 article (match-string 3 path))
5231 (org-follow-gnus-link group article)))
5232
5233 ((string= type "vm")
5234 (let (folder article)
5235 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5236 (error "Error in VM link"))
5237 (setq folder (match-string 1 path)
5238 article (match-string 3 path))
5239 ;; in-emacs is the prefix arg, will be interpreted as read-only
5240 (org-follow-vm-link folder article in-emacs)))
5241
5242 ((string= type "wl")
5243 (let (folder article)
5244 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5245 (error "Error in Wanderlust link"))
5246 (setq folder (match-string 1 path)
5247 article (match-string 3 path))
5248 (org-follow-wl-link folder article)))
5249
5250 ((string= type "rmail")
5251 (let (folder article)
5252 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5253 (error "Error in RMAIL link"))
5254 (setq folder (match-string 1 path)
5255 article (match-string 3 path))
5256 (org-follow-rmail-link folder article)))
5257
5258 ((string= type "shell")
5259 (let ((cmd path))
5260 (while (string-match "@{" cmd)
5261 (setq cmd (replace-match "<" t t cmd)))
5262 (while (string-match "@}" cmd)
5263 (setq cmd (replace-match ">" t t cmd)))
5264 (if (or (not org-confirm-shell-links)
5265 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5266 (shell-command cmd)
5267 (error "Abort"))))
5268
5269 (t
5270 (browse-url-at-point)))))))
5271
5272 (defun org-follow-bbdb-link (name)
5273 "Follow a BBDB link to NAME."
5274 (require 'bbdb)
5275 (let ((inhibit-redisplay t))
5276 (catch 'exit
5277 ;; Exact match on name
5278 (bbdb-name (concat "\\`" name "\\'") nil)
5279 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5280 ;; Exact match on name
5281 (bbdb-company (concat "\\`" name "\\'") nil)
5282 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5283 ;; Partial match on name
5284 (bbdb-name name nil)
5285 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5286 ;; Partial match on company
5287 (bbdb-company name nil)
5288 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5289 ;; General match including network address and notes
5290 (bbdb name nil)
5291 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5292 (delete-window (get-buffer-window "*BBDB*"))
5293 (error "No matching BBDB record")))))
5294
5295 (defun org-follow-gnus-link (&optional group article)
5296 "Follow a Gnus link to GROUP and ARTICLE."
5297 (require 'gnus)
5298 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5299 (if group (gnus-fetch-group group))
5300 (if article
5301 (or (gnus-summary-goto-article article nil 'force)
5302 (if (fboundp 'gnus-summary-insert-cached-articles)
5303 (progn
5304 (gnus-summary-insert-cached-articles)
5305 (gnus-summary-goto-article article nil 'force))
5306 (message "Message could not be found.")))))
5307
5308 (defun org-follow-vm-link (&optional folder article readonly)
5309 "Follow a VM link to FOLDER and ARTICLE."
5310 (require 'vm)
5311 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5312 ;; ange-ftp or efs or tramp access
5313 (let ((user (or (match-string 1 folder) (user-login-name)))
5314 (host (match-string 2 folder))
5315 (file (match-string 3 folder)))
5316 (cond
5317 ((featurep 'tramp)
5318 ;; use tramp to access the file
5319 (if org-xemacs-p
5320 (setq folder (format "[%s@%s]%s" user host file))
5321 (setq folder (format "/%s@%s:%s" user host file))))
5322 (t
5323 ;; use ange-ftp or efs
5324 (require (if org-xemacs-p 'efs 'ange-ftp))
5325 (setq folder (format "/%s@%s:%s" user host file))))))
5326 (when folder
5327 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5328 (sit-for 0.1)
5329 (when article
5330 (vm-select-folder-buffer)
5331 (widen)
5332 (let ((case-fold-search t))
5333 (goto-char (point-min))
5334 (if (not (re-search-forward
5335 (concat "^" "message-id: *" (regexp-quote article))))
5336 (error "Could not find the specified message in this folder"))
5337 (vm-isearch-update)
5338 (vm-isearch-narrow)
5339 (vm-beginning-of-message)
5340 (vm-summarize)))))
5341
5342 (defun org-follow-wl-link (folder article)
5343 "Follow a Wanderlust link to FOLDER and ARTICLE."
5344 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5345 (if article (wl-summary-jump-to-msg-by-message-id article))
5346 (wl-summary-redisplay))
5347
5348 (defun org-follow-rmail-link (folder article)
5349 "Follow an RMAIL link to FOLDER and ARTICLE."
5350 (let (message-number)
5351 (save-excursion
5352 (save-window-excursion
5353 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5354 (setq message-number
5355 (save-restriction
5356 (widen)
5357 (goto-char (point-max))
5358 (if (re-search-backward
5359 (concat "^Message-ID:\\s-+" (regexp-quote
5360 (or article "")))
5361 nil t)
5362 (rmail-what-message))))))
5363 (if message-number
5364 (progn
5365 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5366 (rmail-show-message message-number)
5367 message-number)
5368 (error "Message not found"))))
5369
5370 (defun org-open-file (path &optional in-emacs line)
5371 "Open the file at PATH.
5372 First, this expands any special file name abbreviations. Then the
5373 configuration variable `org-file-apps' is checked if it contains an
5374 entry for this file type, and if yes, the corresponding command is launched.
5375 If no application is found, Emacs simply visits the file.
5376 With optional argument IN-EMACS, Emacs will visit the file.
5377 If the file does not exist, an error is thrown."
5378 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5379 (dfile (downcase file))
5380 ext cmd apps)
5381 (if (and (not (file-exists-p file))
5382 (not org-open-non-existing-files))
5383 (error "No such file: %s" file))
5384 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5385 (setq ext (match-string 1 dfile))
5386 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5387 (setq ext (match-string 1 dfile))))
5388 (setq apps (append org-file-apps (org-default-apps)))
5389 (if in-emacs
5390 (setq cmd 'emacs)
5391 (setq cmd (or (cdr (assoc ext apps))
5392 (cdr (assoc t apps)))))
5393 (cond
5394 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5395 (setq cmd (format cmd (concat "\"" file "\"")))
5396 (save-window-excursion
5397 (shell-command (concat cmd " & &"))))
5398 ((or (stringp cmd)
5399 (eq cmd 'emacs))
5400 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5401 (if line (goto-line line)))
5402 ((consp cmd)
5403 (eval cmd))
5404 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5405
5406 (defun org-default-apps ()
5407 "Return the default applications for this operating system."
5408 (cond
5409 ((eq system-type 'darwin)
5410 org-file-apps-defaults-macosx)
5411 ((eq system-type 'windows-nt)
5412 org-file-apps-defaults-windowsnt)
5413 (t org-file-apps-defaults-gnu)))
5414
5415 (defun org-expand-file-name (path)
5416 "Replace special path abbreviations and expand the file name."
5417 (expand-file-name path))
5418
5419
5420 (defvar org-insert-link-history nil
5421 "Minibuffer history for links inserted with `org-insert-link'.")
5422
5423 (defvar org-stored-links nil
5424 "Contains the links stored with `org-store-link'.")
5425
5426 ;;;###autoload
5427 (defun org-store-link (arg)
5428 "\\<org-mode-map>Store an org-link to the current location.
5429 This link can later be inserted into an org-buffer with
5430 \\[org-insert-link].
5431 For some link types, a prefix arg is interpreted:
5432 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5433 For file links, arg negates `org-line-numbers-in-file-links'."
5434 (interactive "P")
5435 (let (link cpltxt)
5436 (cond
5437
5438 ((eq major-mode 'bbdb-mode)
5439 (setq cpltxt (concat
5440 "bbdb:"
5441 (or (bbdb-record-name (bbdb-current-record))
5442 (bbdb-record-company (bbdb-current-record))))
5443 link (org-make-link cpltxt)))
5444
5445 ((eq major-mode 'calendar-mode)
5446 (let ((cd (calendar-cursor-to-date)))
5447 (setq link
5448 (format-time-string
5449 (car org-time-stamp-formats)
5450 (apply 'encode-time
5451 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5452 nil nil nil))))))
5453
5454 ((or (eq major-mode 'vm-summary-mode)
5455 (eq major-mode 'vm-presentation-mode))
5456 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5457 (vm-follow-summary-cursor)
5458 (save-excursion
5459 (vm-select-folder-buffer)
5460 (let* ((message (car vm-message-pointer))
5461 (folder (buffer-file-name))
5462 (subject (vm-su-subject message))
5463 (author (vm-su-full-name message))
5464 (message-id (vm-su-message-id message)))
5465 (setq folder (abbreviate-file-name folder))
5466 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5467 folder)
5468 (setq folder (replace-match "" t t folder)))
5469 (setq cpltxt (concat author " on: " subject))
5470 (setq link (concat cpltxt "\n "
5471 (org-make-link
5472 "vm:" folder "#" message-id))))))
5473
5474 ((eq major-mode 'wl-summary-mode)
5475 (let* ((msgnum (wl-summary-message-number))
5476 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5477 msgnum 'message-id))
5478 (wl-message-entity (elmo-msgdb-overview-get-entity
5479 msgnum (wl-summary-buffer-msgdb)))
5480 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5481 (subject "???")) ; FIXME: How to get subject of email?
5482 (setq cpltxt (concat author " on: " subject))
5483 (setq link (concat cpltxt "\n "
5484 (org-make-link
5485 "wl:" wl-summary-buffer-folder-name
5486 "#" message-id)))))
5487
5488 ((eq major-mode 'rmail-mode)
5489 (save-excursion
5490 (save-restriction
5491 (rmail-narrow-to-non-pruned-header)
5492 (let ((folder (buffer-file-name))
5493 (message-id (mail-fetch-field "message-id"))
5494 (author (mail-fetch-field "from"))
5495 (subject (mail-fetch-field "subject")))
5496 (setq cpltxt (concat author " on: " subject))
5497 (setq link (concat cpltxt "\n "
5498 (org-make-link
5499 "rmail:" folder "#" message-id)))))))
5500
5501 ((eq major-mode 'gnus-group-mode)
5502 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5503 (gnus-group-group-name)) ; version
5504 ((fboundp 'gnus-group-name)
5505 (gnus-group-name))
5506 (t "???"))))
5507 (setq cpltxt (concat
5508 (if (org-xor arg org-usenet-links-prefer-google)
5509 "http://groups.google.com/groups?group="
5510 "gnus:")
5511 group)
5512 link (org-make-link cpltxt))))
5513
5514 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5515 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5516 (gnus-summary-beginning-of-article)
5517 (let* ((group (car gnus-article-current))
5518 (article (cdr gnus-article-current))
5519 (header (gnus-summary-article-header article))
5520 (author (mail-header-from header))
5521 (message-id (mail-header-id header))
5522 (date (mail-header-date header))
5523 (subject (gnus-summary-subject-string)))
5524 (setq cpltxt (concat author " on: " subject))
5525 (if (org-xor arg org-usenet-links-prefer-google)
5526 (setq link
5527 (concat
5528 cpltxt "\n "
5529 (format "http://groups.google.com/groups?as_umsgid=%s"
5530 (org-fixup-message-id-for-http message-id))))
5531 (setq link (concat cpltxt "\n"
5532 (org-make-link
5533 "gnus:" group
5534 "#" (number-to-string article)))))))
5535
5536 ((eq major-mode 'w3-mode)
5537 (setq cpltxt (url-view-url t)
5538 link (org-make-link cpltxt)))
5539 ((eq major-mode 'w3m-mode)
5540 (setq cpltxt w3m-current-url
5541 link (org-make-link cpltxt)))
5542
5543 ((buffer-file-name)
5544 ;; Just link to this file here.
5545 (setq cpltxt (concat "file:"
5546 (abbreviate-file-name (buffer-file-name))))
5547 ;; Add the line number?
5548 (if (org-xor org-line-numbers-in-file-links arg)
5549 (setq cpltxt
5550 (concat cpltxt
5551 ":" (int-to-string
5552 (+ (if (bolp) 1 0) (count-lines
5553 (point-min) (point)))))))
5554 (setq link (org-make-link cpltxt)))
5555
5556 ((interactive-p)
5557 (error "Cannot link to a buffer which is not visiting a file"))
5558
5559 (t (setq link nil)))
5560
5561 (if (and (interactive-p) link)
5562 (progn
5563 (setq org-stored-links
5564 (cons (cons (or cpltxt link) link) org-stored-links))
5565 (message "Stored: %s" (or cpltxt link)))
5566 link)))
5567
5568 (defun org-make-link (&rest strings)
5569 "Concatenate STRINGS, format resulting string with `org-link-format'."
5570 (format org-link-format (apply 'concat strings)))
5571
5572 (defun org-xor (a b)
5573 "Exclusive or."
5574 (if a (not b) b))
5575
5576 (defun org-get-header (header)
5577 "Find a header field in the current buffer."
5578 (save-excursion
5579 (goto-char (point-min))
5580 (let ((case-fold-search t) s)
5581 (cond
5582 ((eq header 'from)
5583 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5584 (setq s (match-string 1)))
5585 (while (string-match "\"" s)
5586 (setq s (replace-match "" t t s)))
5587 (if (string-match "[<(].*" s)
5588 (setq s (replace-match "" t t s))))
5589 ((eq header 'message-id)
5590 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5591 (setq s (match-string 1))))
5592 ((eq header 'subject)
5593 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5594 (setq s (match-string 1)))))
5595 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5596 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5597 s)))
5598
5599
5600 (defun org-fixup-message-id-for-http (s)
5601 "Replace special characters in a message id, so it can be used in an http query."
5602 (while (string-match "<" s)
5603 (setq s (replace-match "%3C" t t s)))
5604 (while (string-match ">" s)
5605 (setq s (replace-match "%3E" t t s)))
5606 (while (string-match "@" s)
5607 (setq s (replace-match "%40" t t s)))
5608 s)
5609
5610 (defun org-insert-link (&optional complete-file)
5611 "Insert a link. At the prompt, enter the link.
5612
5613 Completion can be used to select a link previously stored with
5614 `org-store-link'. When the empty string is entered (i.e. if you just
5615 press RET at the prompt), the link defaults to the most recently
5616 stored link. As SPC triggers completion in the minibuffer, you need to
5617 use M-SPC or C-q SPC to force the insertion of a space character.
5618
5619 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5620 selected using completion. The path to the file will be relative to
5621 the current directory if the file is in the current directory or a
5622 subdirectory. Otherwise, the link will be the absolute path as
5623 completed in the minibuffer (i.e. normally ~/path/to/file).
5624
5625 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5626 is in the current directory or below."
5627 (interactive "P")
5628 (let ((link (if complete-file
5629 (read-file-name "File: ")
5630 (completing-read
5631 "Link: " org-stored-links nil nil nil
5632 org-insert-link-history
5633 (or (car (car org-stored-links))))))
5634 linktxt matched)
5635 (if (or (not link) (equal link ""))
5636 (error "No links available"))
5637 (if complete-file
5638 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5639 (cond
5640 ((equal complete-file '(16))
5641 (insert
5642 (org-make-link
5643 "file:" (abbreviate-file-name (expand-file-name link)))))
5644 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5645 (expand-file-name link))
5646 (insert
5647 (org-make-link
5648 "file:" (match-string 1 (expand-file-name link)))))
5649 (t (insert (org-make-link "file:" link)))))
5650 (setq linktxt (cdr (assoc link org-stored-links)))
5651 (if (not org-keep-stored-link-after-insertion)
5652 (setq org-stored-links (delq (assoc link org-stored-links)
5653 org-stored-links)))
5654 (if (not linktxt) (setq link (org-make-link link)))
5655 (let ((lines (org-split-string (or linktxt link) "\n")))
5656 (insert (car lines))
5657 (setq matched (string-match org-link-regexp (car lines)))
5658 (setq lines (cdr lines))
5659 (while lines
5660 (insert "\n")
5661 (if (save-excursion
5662 (beginning-of-line 0)
5663 (looking-at "[ \t]+\\S-"))
5664 (indent-relative))
5665 (setq matched (or matched
5666 (string-match org-link-regexp (car lines))))
5667 (insert (car lines))
5668 (setq lines (cdr lines))))
5669 (unless matched
5670 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5671
5672 ;;; Hooks for remember.el
5673 ;;;###autoload
5674 (defun org-remember-annotation ()
5675 "Return a link to the current location as an annotation for remember.el.
5676 If you are using Org-mode files as target for data storage with
5677 remember.el, then the annotations should include a link compatible with the
5678 conventions in Org-mode. This function returns such a link."
5679 (org-store-link nil))
5680
5681 (defconst org-remember-help
5682 "Select a destination location for the note.
5683 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5684 RET at beg-of-buf -> Append to file as level 2 headline
5685 RET on headline -> Store as sublevel entry to current headline
5686 <left>/<right> -> before/after current headline, same headings level")
5687
5688 ;;;###autoload
5689 (defun org-remember-handler ()
5690 "Store stuff from remember.el into an org file.
5691 First prompts for an org file. If the user just presses return, the value
5692 of `org-default-notes-file' is used.
5693 Then the command offers the headings tree of the selected file in order to
5694 file the text at a specific location.
5695 You can either immediately press RET to get the note appended to the
5696 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5697 find a better place. Then press RET or <left> or <right> in insert the note.
5698
5699 Key Cursor position Note gets inserted
5700 -----------------------------------------------------------------------------
5701 RET buffer-start as level 2 heading at end of file
5702 RET on headline as sublevel of the heading at cursor
5703 RET no heading at cursor position, level taken from context.
5704 Or use prefix arg to specify level manually.
5705 <left> on headline as same level, before current heading
5706 <right> on headline as same level, after current heading
5707
5708 So the fastest way to store the note is to press RET RET to append it to
5709 the default file. This way your current train of thought is not
5710 interrupted, in accordance with the principles of remember.el. But with
5711 little extra effort, you can push it directly to the correct location.
5712
5713 Before being stored away, the function ensures that the text has a
5714 headline, i.e. a first line that starts with a \"*\". If not, a headline
5715 is constructed from the current date and some additional data.
5716
5717 If the variable `org-adapt-indentation' is non-nil, the entire text is
5718 also indented so that it starts in the same column as the headline
5719 \(i.e. after the stars).
5720
5721 See also the variable `org-reverse-note-order'."
5722 (catch 'quit
5723 (let* ((txt (buffer-substring (point-min) (point-max)))
5724 (fastp current-prefix-arg)
5725 (file (if fastp org-default-notes-file (org-get-org-file)))
5726 (visiting (find-buffer-visiting file))
5727 (org-startup-with-deadline-check nil)
5728 (org-startup-folded nil)
5729 spos level indent reversed)
5730 ;; Modify text so that it becomes a nice subtree which can be inserted
5731 ;; into an org tree.
5732 (let* ((lines (split-string txt "\n"))
5733 (first (car lines))
5734 (lines (cdr lines)))
5735 (if (string-match "^\\*+" first)
5736 ;; Is already a headline
5737 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5738 -1) ?\ ))
5739 ;; We need to add a headline: Use time and first buffer line
5740 (setq lines (cons first lines)
5741 first (concat "* " (current-time-string)
5742 " (" (remember-buffer-desc) ")")
5743 indent " "))
5744 (if org-adapt-indentation
5745 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5746 (setq txt (concat first "\n"
5747 (mapconcat 'identity lines "\n"))))
5748 ;; Find the file
5749 (if (not visiting)
5750 (find-file-noselect file))
5751 (with-current-buffer (get-file-buffer file)
5752 (setq reversed (org-notes-order-reversed-p))
5753 (save-excursion
5754 (save-restriction
5755 (widen)
5756 ;; Ask the User for a location
5757 (setq spos (if fastp 1 (org-get-location
5758 (current-buffer)
5759 org-remember-help)))
5760 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5761 ; not handle this note
5762 (goto-char spos)
5763 (cond ((bobp)
5764 ;; Put it at the start or end, as level 2
5765 (save-restriction
5766 (widen)
5767 (goto-char (if reversed (point-min) (point-max)))
5768 (if (not (bolp)) (newline))
5769 (org-paste-subtree (or current-prefix-arg 2) txt)))
5770 ((and (org-on-heading-p nil) (not current-prefix-arg))
5771 ;; Put it below this entry, at the beg/end of the subtree
5772 (org-back-to-heading)
5773 (setq level (outline-level))
5774 (if reversed
5775 (outline-end-of-heading)
5776 (outline-end-of-subtree))
5777 (if (not (bolp)) (newline))
5778 (beginning-of-line 1)
5779 (org-paste-subtree (1+ level) txt))
5780 (t
5781 ;; Put it right there, with automatic level determined by
5782 ;; org-paste-subtree or from prefix arg
5783 (org-paste-subtree current-prefix-arg txt)))
5784 (when remember-save-after-remembering
5785 (save-buffer)
5786 (if (not visiting) (kill-buffer (current-buffer)))))))))
5787 t) ;; return t to indicate that we took care of this note.
5788
5789 (defun org-get-org-file ()
5790 "Read a filename, with default directory `org-directory'."
5791 (let ((default (or org-default-notes-file remember-data-file)))
5792 (read-file-name (format "File name [%s]: " default)
5793 (file-name-as-directory org-directory)
5794 default)))
5795
5796 (defun org-notes-order-reversed-p ()
5797 "Check if the current file should receive notes in reversed order."
5798 (cond
5799 ((not org-reverse-note-order) nil)
5800 ((eq t org-reverse-note-order) t)
5801 ((not (listp org-reverse-note-order)) nil)
5802 (t (catch 'exit
5803 (let ((all org-reverse-note-order)
5804 entry)
5805 (while (setq entry (pop all))
5806 (if (string-match (car entry) (buffer-file-name))
5807 (throw 'exit (cdr entry))))
5808 nil)))))
5809
5810 ;;; Tables
5811
5812 ;; Watch out: Here we are talking about two different kind of tables.
5813 ;; Most of the code is for the tables created with the Org-mode table editor.
5814 ;; Sometimes, we talk about tables created and edited with the table.el
5815 ;; Emacs package. We call the former org-type tables, and the latter
5816 ;; table.el-type tables.
5817
5818
5819 (defun org-before-change-function (beg end)
5820 "Every change indicates that a table might need an update."
5821 (setq org-table-may-need-update t))
5822
5823 (defconst org-table-line-regexp "^[ \t]*|"
5824 "Detects an org-type table line.")
5825 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5826 "Detects an org-type table line.")
5827 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5828 "Detects a table line marked for automatic recalculation.")
5829 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5830 "Detects a table line marked for automatic recalculation.")
5831 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5832 "Detects a table line marked for automatic recalculation.")
5833 (defconst org-table-hline-regexp "^[ \t]*|-"
5834 "Detects an org-type table hline.")
5835 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5836 "Detects a table-type table hline.")
5837 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5838 "Detects an org-type or table-type table.")
5839 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5840 "Searching from within a table (any type) this finds the first line
5841 outside the table.")
5842 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5843 "Searching from within a table (any type) this finds the first line
5844 outside the table.")
5845
5846 (defun org-table-create-with-table.el ()
5847 "Use the table.el package to insert a new table.
5848 If there is already a table at point, convert between Org-mode tables
5849 and table.el tables."
5850 (interactive)
5851 (require 'table)
5852 (cond
5853 ((org-at-table.el-p)
5854 (if (y-or-n-p "Convert table to Org-mode table? ")
5855 (org-table-convert)))
5856 ((org-at-table-p)
5857 (if (y-or-n-p "Convert table to table.el table? ")
5858 (org-table-convert)))
5859 (t (call-interactively 'table-insert))))
5860
5861 (defun org-table-create (&optional size)
5862 "Query for a size and insert a table skeleton.
5863 SIZE is a string Columns x Rows like for example \"3x2\"."
5864 (interactive "P")
5865 (unless size
5866 (setq size (read-string
5867 (concat "Table size Columns x Rows [e.g. "
5868 org-table-default-size "]: ")
5869 "" nil org-table-default-size)))
5870
5871 (let* ((pos (point))
5872 (indent (make-string (current-column) ?\ ))
5873 (split (org-split-string size " *x *"))
5874 (rows (string-to-number (nth 1 split)))
5875 (columns (string-to-number (car split)))
5876 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5877 "\n")))
5878 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5879 (point-at-bol) (point)))
5880 (beginning-of-line 1)
5881 (newline))
5882 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5883 (dotimes (i rows) (insert line))
5884 (goto-char pos)
5885 (if (> rows 1)
5886 ;; Insert a hline after the first row.
5887 (progn
5888 (end-of-line 1)
5889 (insert "\n|-")
5890 (goto-char pos)))
5891 (org-table-align)))
5892
5893 (defun org-table-convert-region (beg0 end0 nspace)
5894 "Convert region to a table.
5895 The region goes from BEG0 to END0, but these borders will be moved
5896 slightly, to make sure a beginning of line in the first line is included.
5897 When NSPACE is non-nil, it indicates the minimum number of spaces that
5898 separate columns (default: just one space)"
5899 (let* ((beg (min beg0 end0))
5900 (end (max beg0 end0))
5901 (tabsep t)
5902 re)
5903 (goto-char beg)
5904 (beginning-of-line 1)
5905 (setq beg (move-marker (make-marker) (point)))
5906 (goto-char end)
5907 (if (bolp) (backward-char 1) (end-of-line 1))
5908 (setq end (move-marker (make-marker) (point)))
5909 ;; Lets see if this is tab-separated material. If every nonempty line
5910 ;; contains a tab, we will assume that it is tab-separated material
5911 (if nspace
5912 (setq tabsep nil)
5913 (goto-char beg)
5914 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5915 (if nspace (setq tabsep nil))
5916 (if tabsep
5917 (setq re "^\\|\t")
5918 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5919 (max 1 (prefix-numeric-value nspace)))))
5920 (goto-char beg)
5921 (while (re-search-forward re end t)
5922 (replace-match "|" t t))
5923 (goto-char beg)
5924 (insert " ")
5925 (org-table-align)))
5926
5927 (defun org-table-import (file arg)
5928 "Import FILE as a table.
5929 The file is assumed to be tab-separated. Such files can be produced by most
5930 spreadsheet and database applications. If no tabs (at least one per line)
5931 are found, lines will be split on whitespace into fields."
5932 (interactive "f\nP")
5933 (or (bolp) (newline))
5934 (let ((beg (point))
5935 (pm (point-max)))
5936 (insert-file-contents file)
5937 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5938
5939 (defun org-table-export ()
5940 "Export table as a tab-separated file.
5941 Such a file can be imported into a spreadsheet program like Excel."
5942 (interactive)
5943 (let* ((beg (org-table-begin))
5944 (end (org-table-end))
5945 (table (buffer-substring beg end))
5946 (file (read-file-name "Export table to: "))
5947 buf)
5948 (unless (or (not (file-exists-p file))
5949 (y-or-n-p (format "Overwrite file %s? " file)))
5950 (error "Abort"))
5951 (with-current-buffer (find-file-noselect file)
5952 (setq buf (current-buffer))
5953 (erase-buffer)
5954 (fundamental-mode)
5955 (insert table)
5956 (goto-char (point-min))
5957 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5958 (replace-match "" t t)
5959 (end-of-line 1))
5960 (goto-char (point-min))
5961 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5962 (replace-match "" t t)
5963 (goto-char (min (1+ (point)) (point-max))))
5964 (goto-char (point-min))
5965 (while (re-search-forward "^-[-+]*$" nil t)
5966 (replace-match "")
5967 (if (looking-at "\n")
5968 (delete-char 1)))
5969 (goto-char (point-min))
5970 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5971 (replace-match "\t" t t))
5972 (save-buffer))
5973 (kill-buffer buf)))
5974
5975 (defvar org-table-aligned-begin-marker (make-marker)
5976 "Marker at the beginning of the table last aligned.
5977 Used to check if cursor still is in that table, to minimize realignment.")
5978 (defvar org-table-aligned-end-marker (make-marker)
5979 "Marker at the end of the table last aligned.
5980 Used to check if cursor still is in that table, to minimize realignment.")
5981 (defvar org-table-last-alignment nil
5982 "List of flags for flushright alignment, from the last re-alignment.
5983 This is being used to correctly align a single field after TAB or RET.")
5984 ;; FIXME: The following is currently not used.
5985 (defvar org-table-last-column-widths nil
5986 "List of max width of fields in each column.
5987 This is being used to correctly align a single field after TAB or RET.")
5988
5989 (defvar org-last-recalc-line nil)
5990
5991 (defun org-table-align ()
5992 "Align the table at point by aligning all vertical bars."
5993 (interactive)
5994 ;; (message "align") (sit-for 2)
5995 (let* (
5996 ;; Limits of table
5997 (beg (org-table-begin))
5998 (end (org-table-end))
5999 ;; Current cursor position
6000 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6001 (colpos (org-table-current-column))
6002 (winstart (window-start))
6003 text lines (new "") lengths l typenums ty fields maxfields i
6004 column
6005 (indent "") cnt frac
6006 rfmt hfmt
6007 (spaces (if (org-in-invisibility-spec-p '(org-table))
6008 org-table-spaces-around-invisible-separators
6009 org-table-spaces-around-separators))
6010 (sp1 (car spaces))
6011 (sp2 (cdr spaces))
6012 (rfmt1 (concat
6013 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6014 (hfmt1 (concat
6015 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6016 emptystrings)
6017 (untabify beg end)
6018 ;; (message "Aligning table...")
6019 ;; Get the rows
6020 (setq lines (org-split-string
6021 (buffer-substring-no-properties beg end) "\n"))
6022 ;; Store the indentation of the first line
6023 (if (string-match "^ *" (car lines))
6024 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6025 ;; Mark the hlines
6026 (setq lines (mapcar (lambda (l)
6027 (if (string-match "^ *|-" l)
6028 nil
6029 (if (string-match "[ \t]+$" l)
6030 (substring l 0 (match-beginning 0))
6031 l)))
6032 lines))
6033 ;; Get the data fields
6034 (setq fields (mapcar
6035 (lambda (l)
6036 (org-split-string l " *| *"))
6037 (delq nil (copy-sequence lines))))
6038 ;; How many fields in the longest line?
6039 (condition-case nil
6040 (setq maxfields (apply 'max (mapcar 'length fields)))
6041 (error
6042 (kill-region beg end)
6043 (org-table-create org-table-default-size)
6044 (error "Empty table - created default table")))
6045 ;; A list of empty string to fill any short rows on output
6046 (setq emptystrings (make-list maxfields ""))
6047 ;; Get the maximum length of a field and the most common datatype
6048 ;; for each column
6049 (setq i -1)
6050 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6051 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6052 ;; maximum length
6053 (push (apply 'max 1 (mapcar 'length column)) lengths)
6054 ;; compute the fraction stepwise, ignoring empty fields
6055 (setq cnt 0 frac 0.0)
6056 (mapcar
6057 (lambda (x)
6058 (if (equal x "")
6059 nil
6060 (setq frac ( / (+ (* frac cnt)
6061 (if (string-match org-table-number-regexp x) 1 0))
6062 (setq cnt (1+ cnt))))))
6063 column)
6064 (push (>= frac org-table-number-fraction) typenums))
6065 (setq lengths (nreverse lengths)
6066 typenums (nreverse typenums))
6067 (setq org-table-last-alignment typenums
6068 org-table-last-column-widths lengths)
6069 ;; Compute the formats needed for output of the table
6070 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6071 (while (setq l (pop lengths))
6072 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6073 (setq rfmt (concat rfmt (format rfmt1 ty l))
6074 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6075 (setq rfmt (concat rfmt "\n")
6076 hfmt (concat (substring hfmt 0 -1) "|\n"))
6077 ;; Produce the new table
6078 ;;(while lines
6079 ;; (setq l (pop lines))
6080 ;; (if l
6081 ;; (setq new (concat new (apply 'format rfmt
6082 ;; (append (pop fields) emptystrings))))
6083 ;; (setq new (concat new hfmt))))
6084 (setq new (mapconcat
6085 (lambda (l)
6086 (if l (apply 'format rfmt
6087 (append (pop fields) emptystrings))
6088 hfmt))
6089 lines ""))
6090 ;; Replace the old one
6091 (delete-region beg end)
6092 (move-marker end nil)
6093 (move-marker org-table-aligned-begin-marker (point))
6094 (insert new)
6095 (move-marker org-table-aligned-end-marker (point))
6096 ;; Try to move to the old location (approximately)
6097 (goto-line linepos)
6098 (set-window-start (selected-window) winstart 'noforce)
6099 (org-table-goto-column colpos)
6100 (setq org-table-may-need-update nil)
6101 (if (org-in-invisibility-spec-p '(org-table))
6102 (org-table-add-invisible-to-vertical-lines))
6103 ))
6104
6105 (defun org-table-begin (&optional table-type)
6106 "Find the beginning of the table and return its position.
6107 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6108 (save-excursion
6109 (if (not (re-search-backward
6110 (if table-type org-table-any-border-regexp
6111 org-table-border-regexp)
6112 nil t))
6113 (error "Can't find beginning of table")
6114 (goto-char (match-beginning 0))
6115 (beginning-of-line 2)
6116 (point))))
6117
6118 (defun org-table-end (&optional table-type)
6119 "Find the end of the table and return its position.
6120 With argument TABLE-TYPE, go to the end of a table.el-type table."
6121 (save-excursion
6122 (if (not (re-search-forward
6123 (if table-type org-table-any-border-regexp
6124 org-table-border-regexp)
6125 nil t))
6126 (goto-char (point-max))
6127 (goto-char (match-beginning 0)))
6128 (point-marker)))
6129
6130 (defun org-table-justify-field-maybe (&optional new)
6131 "Justify the current field, text to left, number to right.
6132 Optional argument NEW may specify text to replace the current field content."
6133 (cond
6134 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6135 ((org-at-table-hline-p)
6136 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6137 ;; (setq org-table-may-need-update t)
6138 )
6139 ((and (not new)
6140 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6141 (current-buffer)))
6142 (< (point) org-table-aligned-begin-marker)
6143 (>= (point) org-table-aligned-end-marker)))
6144 ;; This is not the same table, force a full re-align
6145 (setq org-table-may-need-update t))
6146 (t ;; realign the current field, based on previous full realign
6147 (let* ((pos (point)) s
6148 (col (org-table-current-column))
6149 (num (nth (1- col) org-table-last-alignment))
6150 l f n o e)
6151 (when (> col 0)
6152 (skip-chars-backward "^|\n")
6153 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6154 (progn
6155 (setq s (match-string 1)
6156 o (match-string 0)
6157 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6158 e (not (= (match-beginning 2) (match-end 2))))
6159 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6160 l (if e "|" (setq org-table-may-need-update t) ""))
6161 n (format f s t t))
6162 (if new
6163 (if (<= (length new) l)
6164 (setq n (format f new t t)) ;; FIXME: why t t?????
6165 (setq n (concat new "|") org-table-may-need-update t)))
6166 (or (equal n o)
6167 (let (org-table-may-need-update)
6168 (replace-match n))))
6169 (setq org-table-may-need-update t))
6170 (goto-char pos))))))
6171
6172 (defun org-table-next-field ()
6173 "Go to the next field in the current table.
6174 Before doing so, re-align the table if necessary."
6175 (interactive)
6176 (org-table-maybe-eval-formula)
6177 (org-table-maybe-recalculate-line)
6178 (if (and org-table-automatic-realign
6179 org-table-may-need-update)
6180 (org-table-align))
6181 (if (org-at-table-hline-p)
6182 (end-of-line 1))
6183 (condition-case nil
6184 (progn
6185 (re-search-forward "|" (org-table-end))
6186 (if (looking-at "[ \t]*$")
6187 (re-search-forward "|" (org-table-end)))
6188 (if (looking-at "-")
6189 (progn
6190 (beginning-of-line 0)
6191 (org-table-insert-row 'below))
6192 (if (looking-at " ") (forward-char 1))))
6193 (error
6194 (org-table-insert-row 'below))))
6195
6196 (defun org-table-previous-field ()
6197 "Go to the previous field in the table.
6198 Before doing so, re-align the table if necessary."
6199 (interactive)
6200 (org-table-justify-field-maybe)
6201 (org-table-maybe-recalculate-line)
6202 (if (and org-table-automatic-realign
6203 org-table-may-need-update)
6204 (org-table-align))
6205 (if (org-at-table-hline-p)
6206 (end-of-line 1))
6207 (re-search-backward "|" (org-table-begin))
6208 (re-search-backward "|" (org-table-begin))
6209 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6210 (re-search-backward "|" (org-table-begin)))
6211 (if (looking-at "| ?")
6212 (goto-char (match-end 0))))
6213
6214 (defun org-table-next-row ()
6215 "Go to the next row (same column) in the current table.
6216 Before doing so, re-align the table if necessary."
6217 (interactive)
6218 (org-table-maybe-eval-formula)
6219 (org-table-maybe-recalculate-line)
6220 (if (or (looking-at "[ \t]*$")
6221 (save-excursion (skip-chars-backward " \t") (bolp)))
6222 (newline)
6223 (if (and org-table-automatic-realign
6224 org-table-may-need-update)
6225 (org-table-align))
6226 (let ((col (org-table-current-column)))
6227 (beginning-of-line 2)
6228 (if (or (not (org-at-table-p))
6229 (org-at-table-hline-p))
6230 (progn
6231 (beginning-of-line 0)
6232 (org-table-insert-row 'below)))
6233 (org-table-goto-column col)
6234 (skip-chars-backward "^|\n\r")
6235 (if (looking-at " ") (forward-char 1)))))
6236
6237 (defun org-table-copy-down (n)
6238 "Copy a field down in the current column.
6239 If the field at the cursor is empty, copy into it the content of the nearest
6240 non-empty field above. With argument N, use the Nth non-empty field.
6241 If the current field is not empty, it is copied down to the next row, and
6242 the cursor is moved with it. Therefore, repeating this command causes the
6243 column to be filled row-by-row.
6244 If the variable `org-table-copy-increment' is non-nil and the field is an
6245 integer, it will be incremented while copying."
6246 (interactive "p")
6247 (let* ((colpos (org-table-current-column))
6248 (field (org-table-get-field))
6249 (non-empty (string-match "[^ \t]" field))
6250 (beg (org-table-begin))
6251 txt)
6252 (org-table-check-inside-data-field)
6253 (if non-empty
6254 (progn
6255 (setq txt (org-trim field))
6256 (org-table-next-row)
6257 (org-table-blank-field))
6258 (save-excursion
6259 (setq txt
6260 (catch 'exit
6261 (while (progn (beginning-of-line 1)
6262 (re-search-backward org-table-dataline-regexp
6263 beg t))
6264 (org-table-goto-column colpos t)
6265 (if (and (looking-at
6266 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6267 (= (setq n (1- n)) 0))
6268 (throw 'exit (match-string 1))))))))
6269 (if txt
6270 (progn
6271 (if (and org-table-copy-increment
6272 (string-match "^[0-9]+$" txt))
6273 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6274 (insert txt)
6275 (org-table-maybe-recalculate-line)
6276 (org-table-align))
6277 (error "No non-empty field found"))))
6278
6279 (defun org-table-check-inside-data-field ()
6280 "Is point inside a table data field?
6281 I.e. not on a hline or before the first or after the last column?"
6282 (if (or (not (org-at-table-p))
6283 (= (org-table-current-column) 0)
6284 (org-at-table-hline-p)
6285 (looking-at "[ \t]*$"))
6286 (error "Not in table data field")))
6287
6288 (defvar org-table-clip nil
6289 "Clipboard for table regions.")
6290
6291 (defun org-table-blank-field ()
6292 "Blank the current table field or active region."
6293 (interactive)
6294 (org-table-check-inside-data-field)
6295 (if (and (interactive-p) (org-region-active-p))
6296 (let (org-table-clip)
6297 (org-table-cut-region (region-beginning) (region-end)))
6298 (skip-chars-backward "^|")
6299 (backward-char 1)
6300 (if (looking-at "|[^|\n]+")
6301 (let* ((pos (match-beginning 0))
6302 (match (match-string 0))
6303 (len (length match)))
6304 (replace-match (concat "|" (make-string (1- len) ?\ )))
6305 (goto-char (+ 2 pos))
6306 (substring match 1)))))
6307
6308 (defun org-table-get-field (&optional n replace)
6309 "Return the value of the field in column N of current row.
6310 N defaults to current field.
6311 If REPLACE is a string, replace field with this value. The return value
6312 is always the old value."
6313 (and n (org-table-goto-column n))
6314 (skip-chars-backward "^|\n")
6315 (backward-char 1)
6316 (if (looking-at "|[^|\r\n]*")
6317 (let* ((pos (match-beginning 0))
6318 (val (buffer-substring (1+ pos) (match-end 0))))
6319 (if replace
6320 (replace-match (concat "|" replace)))
6321 (goto-char (min (point-at-eol) (+ 2 pos)))
6322 val)
6323 (forward-char 1) ""))
6324
6325 (defun org-table-current-column ()
6326 "Find out which column we are in.
6327 When called interactively, column is also displayed in echo area."
6328 (interactive)
6329 (if (interactive-p) (org-table-check-inside-data-field))
6330 (save-excursion
6331 (let ((cnt 0) (pos (point)))
6332 (beginning-of-line 1)
6333 (while (search-forward "|" pos t)
6334 (setq cnt (1+ cnt)))
6335 (if (interactive-p) (message "This is table column %d" cnt))
6336 cnt)))
6337
6338 (defun org-table-goto-column (n &optional on-delim force)
6339 "Move the cursor to the Nth column in the current table line.
6340 With optional argument ON-DELIM, stop with point before the left delimiter
6341 of the field.
6342 If there are less than N fields, just go to after the last delimiter.
6343 However, when FORCE is non-nil, create new columns if necessary."
6344 (let ((pos (point-at-eol)))
6345 (beginning-of-line 1)
6346 (when (> n 0)
6347 (while (and (> (setq n (1- n)) -1)
6348 (or (search-forward "|" pos t)
6349 (and force
6350 (progn (end-of-line 1)
6351 (skip-chars-backward "^|")
6352 (insert " | "))))))
6353 ; (backward-char 2) t)))))
6354 (when (and force (not (looking-at ".*|")))
6355 (save-excursion (end-of-line 1) (insert " | ")))
6356 (if on-delim
6357 (backward-char 1)
6358 (if (looking-at " ") (forward-char 1))))))
6359
6360 (defun org-at-table-p (&optional table-type)
6361 "Return t if the cursor is inside an org-type table.
6362 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6363 (if org-enable-table-editor
6364 (save-excursion
6365 (beginning-of-line 1)
6366 (looking-at (if table-type org-table-any-line-regexp
6367 org-table-line-regexp)))
6368 nil))
6369
6370 (defun org-table-recognize-table.el ()
6371 "If there is a table.el table nearby, recognize it and move into it."
6372 (if org-table-tab-recognizes-table.el
6373 (if (org-at-table.el-p)
6374 (progn
6375 (beginning-of-line 1)
6376 (if (looking-at org-table-dataline-regexp)
6377 nil
6378 (if (looking-at org-table1-hline-regexp)
6379 (progn
6380 (beginning-of-line 2)
6381 (if (looking-at org-table-any-border-regexp)
6382 (beginning-of-line -1)))))
6383 (if (re-search-forward "|" (org-table-end t) t)
6384 (progn
6385 (require 'table)
6386 (if (table--at-cell-p (point))
6387 t
6388 (message "recognizing table.el table...")
6389 (table-recognize-table)
6390 (message "recognizing table.el table...done")))
6391 (error "This should not happen..."))
6392 t)
6393 nil)
6394 nil))
6395
6396 (defun org-at-table.el-p ()
6397 "Return t if the cursor is inside a table.el-type table."
6398 (save-excursion
6399 (if (org-at-table-p 'any)
6400 (progn
6401 (goto-char (org-table-begin 'any))
6402 (looking-at org-table1-hline-regexp))
6403 nil)))
6404
6405 (defun org-at-table-hline-p ()
6406 "Return t if the cursor is inside a hline in a table."
6407 (if org-enable-table-editor
6408 (save-excursion
6409 (beginning-of-line 1)
6410 (looking-at org-table-hline-regexp))
6411 nil))
6412
6413 (defun org-table-insert-column ()
6414 "Insert a new column into the table."
6415 (interactive)
6416 (if (not (org-at-table-p))
6417 (error "Not at a table"))
6418 (org-table-find-dataline)
6419 (let* ((col (max 1 (org-table-current-column)))
6420 (beg (org-table-begin))
6421 (end (org-table-end))
6422 ;; Current cursor position
6423 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6424 (colpos col))
6425 (goto-char beg)
6426 (while (< (point) end)
6427 (if (org-at-table-hline-p)
6428 nil
6429 (org-table-goto-column col t)
6430 (insert "| "))
6431 (beginning-of-line 2))
6432 (move-marker end nil)
6433 (goto-line linepos)
6434 (org-table-goto-column colpos)
6435 (org-table-align)
6436 (org-table-modify-formulas 'insert col)))
6437
6438 (defun org-table-find-dataline ()
6439 "Find a dataline in the current table, which is needed for column commands."
6440 (if (and (org-at-table-p)
6441 (not (org-at-table-hline-p)))
6442 t
6443 (let ((col (current-column))
6444 (end (org-table-end)))
6445 (move-to-column col)
6446 (while (and (< (point) end)
6447 (or (not (= (current-column) col))
6448 (org-at-table-hline-p)))
6449 (beginning-of-line 2)
6450 (move-to-column col))
6451 (if (and (org-at-table-p)
6452 (not (org-at-table-hline-p)))
6453 t
6454 (error
6455 "Please position cursor in a data line for column operations")))))
6456
6457 (defun org-table-delete-column ()
6458 "Delete a column into the table."
6459 (interactive)
6460 (if (not (org-at-table-p))
6461 (error "Not at a table"))
6462 (org-table-find-dataline)
6463 (org-table-check-inside-data-field)
6464 (let* ((col (org-table-current-column))
6465 (beg (org-table-begin))
6466 (end (org-table-end))
6467 ;; Current cursor position
6468 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6469 (colpos col))
6470 (goto-char beg)
6471 (while (< (point) end)
6472 (if (org-at-table-hline-p)
6473 nil
6474 (org-table-goto-column col t)
6475 (and (looking-at "|[^|\n]+|")
6476 (replace-match "|")))
6477 (beginning-of-line 2))
6478 (move-marker end nil)
6479 (goto-line linepos)
6480 (org-table-goto-column colpos)
6481 (org-table-align)
6482 (org-table-modify-formulas 'remove col)))
6483
6484 (defun org-table-move-column-right ()
6485 "Move column to the right."
6486 (interactive)
6487 (org-table-move-column nil))
6488 (defun org-table-move-column-left ()
6489 "Move column to the left."
6490 (interactive)
6491 (org-table-move-column 'left))
6492
6493 (defun org-table-move-column (&optional left)
6494 "Move the current column to the right. With arg LEFT, move to the left."
6495 (interactive "P")
6496 (if (not (org-at-table-p))
6497 (error "Not at a table"))
6498 (org-table-find-dataline)
6499 (org-table-check-inside-data-field)
6500 (let* ((col (org-table-current-column))
6501 (col1 (if left (1- col) col))
6502 (beg (org-table-begin))
6503 (end (org-table-end))
6504 ;; Current cursor position
6505 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6506 (colpos (if left (1- col) (1+ col))))
6507 (if (and left (= col 1))
6508 (error "Cannot move column further left"))
6509 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6510 (error "Cannot move column further right"))
6511 (goto-char beg)
6512 (while (< (point) end)
6513 (if (org-at-table-hline-p)
6514 nil
6515 (org-table-goto-column col1 t)
6516 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6517 (replace-match "|\\2|\\1|")))
6518 (beginning-of-line 2))
6519 (move-marker end nil)
6520 (goto-line linepos)
6521 (org-table-goto-column colpos)
6522 (org-table-align)
6523 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6524
6525 (defun org-table-move-row-down ()
6526 "move table row down."
6527 (interactive)
6528 (org-table-move-row nil))
6529 (defun org-table-move-row-up ()
6530 "move table row up."
6531 (interactive)
6532 (org-table-move-row 'up))
6533
6534 (defun org-table-move-row (&optional up)
6535 "Move the current table line down. With arg UP, move it up."
6536 (interactive "P")
6537 (let ((col (current-column))
6538 (pos (point))
6539 (tonew (if up 0 2))
6540 txt)
6541 (beginning-of-line tonew)
6542 (if (not (org-at-table-p))
6543 (progn
6544 (goto-char pos)
6545 (error "Cannot move row further")))
6546 (goto-char pos)
6547 (beginning-of-line 1)
6548 (setq pos (point))
6549 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6550 (delete-region (point) (1+ (point-at-eol)))
6551 (beginning-of-line tonew)
6552 (insert txt)
6553 (beginning-of-line 0)
6554 (move-to-column col)))
6555
6556 (defun org-table-insert-row (&optional arg)
6557 "Insert a new row above the current line into the table.
6558 With prefix ARG, insert below the current line."
6559 (interactive "P")
6560 (if (not (org-at-table-p))
6561 (error "Not at a table"))
6562 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6563 new)
6564 (if (string-match "^[ \t]*|-" line)
6565 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6566 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6567 ;; Fix the first field if necessary
6568 (setq new (concat new))
6569 (if (string-match "^[ \t]*| *[#$] *|" line)
6570 (setq new (replace-match (match-string 0 line) t t new)))
6571 (beginning-of-line (if arg 2 1))
6572 (let (org-table-may-need-update)
6573 (insert-before-markers new)
6574 (insert-before-markers "\n"))
6575 (beginning-of-line 0)
6576 (re-search-forward "| ?" (point-at-eol) t)
6577 (and org-table-may-need-update (org-table-align))))
6578
6579 (defun org-table-insert-hline (&optional arg)
6580 "Insert a horizontal-line below the current line into the table.
6581 With prefix ARG, insert above the current line."
6582 (interactive "P")
6583 (if (not (org-at-table-p))
6584 (error "Not at a table"))
6585 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6586 (col (current-column))
6587 start)
6588 (if (string-match "^[ \t]*|-" line)
6589 (setq line
6590 (mapcar (lambda (x) (if (member x '(?| ?+))
6591 (prog1 (if start ?+ ?|) (setq start t))
6592 (if start ?- ?\ )))
6593 line))
6594 (setq line
6595 (mapcar (lambda (x) (if (equal x ?|)
6596 (prog1 (if start ?+ ?|) (setq start t))
6597 (if start ?- ?\ )))
6598 line)))
6599 (beginning-of-line (if arg 1 2))
6600 (apply 'insert line)
6601 (if (equal (char-before (point)) ?+)
6602 (progn (backward-delete-char 1) (insert "|")))
6603 (insert "\n")
6604 (beginning-of-line 0)
6605 (move-to-column col)))
6606
6607 (defun org-table-kill-row ()
6608 "Delete the current row or horizontal line from the table."
6609 (interactive)
6610 (if (not (org-at-table-p))
6611 (error "Not at a table"))
6612 (let ((col (current-column)))
6613 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6614 (if (not (org-at-table-p)) (beginning-of-line 0))
6615 (move-to-column col)))
6616
6617
6618 (defun org-table-cut-region (beg end)
6619 "Copy region in table to the clipboard and blank all relevant fields."
6620 (interactive "r")
6621 (org-table-copy-region beg end 'cut))
6622
6623 (defun org-table-copy-region (beg end &optional cut)
6624 "Copy rectangular region in table to clipboard.
6625 A special clipboard is used which can only be accessed
6626 with `org-table-paste-rectangle'"
6627 (interactive "rP")
6628 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6629 region cols
6630 (rpl (if cut " " nil)))
6631 (goto-char beg)
6632 (org-table-check-inside-data-field)
6633 (setq l01 (count-lines (point-min) (point))
6634 c01 (org-table-current-column))
6635 (goto-char end)
6636 (org-table-check-inside-data-field)
6637 (setq l02 (count-lines (point-min) (point))
6638 c02 (org-table-current-column))
6639 (setq l1 (min l01 l02) l2 (max l01 l02)
6640 c1 (min c01 c02) c2 (max c01 c02))
6641 (catch 'exit
6642 (while t
6643 (catch 'nextline
6644 (if (> l1 l2) (throw 'exit t))
6645 (goto-line l1)
6646 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6647 (setq cols nil ic1 c1 ic2 c2)
6648 (while (< ic1 (1+ ic2))
6649 (push (org-table-get-field ic1 rpl) cols)
6650 (setq ic1 (1+ ic1)))
6651 (push (nreverse cols) region)
6652 (setq l1 (1+ l1)))))
6653 (setq org-table-clip (nreverse region))
6654 (if cut (org-table-align))
6655 org-table-clip))
6656
6657 (defun org-table-paste-rectangle ()
6658 "Paste a rectangular region into a table.
6659 The upper right corner ends up in the current field. All involved fields
6660 will be overwritten. If the rectangle does not fit into the present table,
6661 the table is enlarged as needed. The process ignores horizontal separator
6662 lines."
6663 (interactive)
6664 (unless (and org-table-clip (listp org-table-clip))
6665 (error "First cut/copy a region to paste!"))
6666 (org-table-check-inside-data-field)
6667 (let* ((clip org-table-clip)
6668 (line (count-lines (point-min) (point)))
6669 (col (org-table-current-column))
6670 (org-enable-table-editor t)
6671 (org-table-automatic-realign nil)
6672 c cols field)
6673 (while (setq cols (pop clip))
6674 (while (org-at-table-hline-p) (beginning-of-line 2))
6675 (if (not (org-at-table-p))
6676 (progn (end-of-line 0) (org-table-next-field)))
6677 (setq c col)
6678 (while (setq field (pop cols))
6679 (org-table-goto-column c nil 'force)
6680 (org-table-get-field nil field)
6681 (setq c (1+ c)))
6682 (beginning-of-line 2))
6683 (goto-line line)
6684 (org-table-goto-column col)
6685 (org-table-align)))
6686
6687 (defun org-table-convert ()
6688 "Convert from `org-mode' table to table.el and back.
6689 Obviously, this only works within limits. When an Org-mode table is
6690 converted to table.el, all horizontal separator lines get lost, because
6691 table.el uses these as cell boundaries and has no notion of horizontal lines.
6692 A table.el table can be converted to an Org-mode table only if it does not
6693 do row or column spanning. Multiline cells will become multiple cells.
6694 Beware, Org-mode does not test if the table can be successfully converted - it
6695 blindly applies a recipe that works for simple tables."
6696 (interactive)
6697 (require 'table)
6698 (if (org-at-table.el-p)
6699 ;; convert to Org-mode table
6700 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6701 (end (move-marker (make-marker) (org-table-end t))))
6702 (table-unrecognize-region beg end)
6703 (goto-char beg)
6704 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6705 (replace-match ""))
6706 (goto-char beg))
6707 (if (org-at-table-p)
6708 ;; convert to table.el table
6709 (let ((beg (move-marker (make-marker) (org-table-begin)))
6710 (end (move-marker (make-marker) (org-table-end))))
6711 ;; first, get rid of all horizontal lines
6712 (goto-char beg)
6713 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6714 (replace-match ""))
6715 ;; insert a hline before first
6716 (goto-char beg)
6717 (org-table-insert-hline 'above)
6718 ;; insert a hline after each line
6719 (while (progn (beginning-of-line 2) (< (point) end))
6720 (org-table-insert-hline))
6721 (goto-char beg)
6722 (setq end (move-marker end (org-table-end)))
6723 ;; replace "+" at beginning and ending of hlines
6724 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6725 (replace-match "\\1+-"))
6726 (goto-char beg)
6727 (while (re-search-forward "-|[ \t]*$" end t)
6728 (replace-match "-+"))
6729 (goto-char beg)))))
6730
6731 (defun org-table-wrap-region (arg)
6732 "Wrap several fields in a column like a paragraph.
6733 This is useful if you'd like to spread the contents of a field over several
6734 lines, in order to keep the table compact.
6735
6736 If there is an active region, and both point and mark are in the same column,
6737 the text in the column is wrapped to minimum width for the given number of
6738 lines. Generally, this makes the table more compact. A prefix ARG may be
6739 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6740 formats the selected text to two lines. If the region was longer than 2
6741 lines, the remaining lines remain empty. A negative prefix argument reduces
6742 the current number of lines by that amount. The wrapped text is pasted back
6743 into the table. If you formatted it to more lines than it was before, fields
6744 further down in the table get overwritten - so you might need to make space in
6745 the table first.
6746
6747 If there is no region, the current field is split at the cursor position and
6748 the text fragment to the right of the cursor is prepended to the field one
6749 line down.
6750
6751 If there is no region, but you specify a prefix ARG, the current field gets
6752 blank, and the content is appended to the field above."
6753 (interactive "P")
6754 (org-table-check-inside-data-field)
6755 (if (org-region-active-p)
6756 ;; There is a region: fill as a paragraph
6757 (let ((beg (region-beginning))
6758 nlines)
6759 (org-table-cut-region (region-beginning) (region-end))
6760 (if (> (length (car org-table-clip)) 1)
6761 (error "Region must be limited to single column"))
6762 (setq nlines (if arg
6763 (if (< arg 1)
6764 (+ (length org-table-clip) arg)
6765 arg)
6766 (length org-table-clip)))
6767 (setq org-table-clip
6768 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6769 nil nlines)))
6770 (goto-char beg)
6771 (org-table-paste-rectangle))
6772 ;; No region, split the current field at point
6773 (if arg
6774 ;; combine with field above
6775 (let ((s (org-table-blank-field))
6776 (col (org-table-current-column)))
6777 (beginning-of-line 0)
6778 (while (org-at-table-hline-p) (beginning-of-line 0))
6779 (org-table-goto-column col)
6780 (skip-chars-forward "^|")
6781 (skip-chars-backward " ")
6782 (insert " " (org-trim s))
6783 (org-table-align))
6784 ;; split field
6785 (when (looking-at "\\([^|]+\\)+|")
6786 (let ((s (match-string 1)))
6787 (replace-match " |")
6788 (goto-char (match-beginning 0))
6789 (org-table-next-row)
6790 (insert (org-trim s) " ")
6791 (org-table-align))))))
6792
6793 (defun org-trim (s)
6794 "Remove whitespace at beginning and end of string."
6795 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6796 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6797 s)
6798
6799 (defun org-wrap (string &optional width lines)
6800 "Wrap string to either a number of lines, or a width in characters.
6801 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6802 that costs. If there is a word longer than WIDTH, the text is actually
6803 wrapped to the length of that word.
6804 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6805 many lines, whatever width that takes.
6806 The return value is a list of lines, without newlines at the end."
6807 (let* ((words (org-split-string string "[ \t\n]+"))
6808 (maxword (apply 'max (mapcar 'length words)))
6809 w ll)
6810 (cond (width
6811 (org-do-wrap words (max maxword width)))
6812 (lines
6813 (setq w maxword)
6814 (setq ll (org-do-wrap words maxword))
6815 (if (<= (length ll) lines)
6816 ll
6817 (setq ll words)
6818 (while (> (length ll) lines)
6819 (setq w (1+ w))
6820 (setq ll (org-do-wrap words w)))
6821 ll))
6822 (t (error "Cannot wrap this")))))
6823
6824
6825 (defun org-do-wrap (words width)
6826 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6827 (let (lines line)
6828 (while words
6829 (setq line (pop words))
6830 (while (and words (< (+ (length line) (length (car words))) width))
6831 (setq line (concat line " " (pop words))))
6832 (setq lines (push line lines)))
6833 (nreverse lines)))
6834
6835 ;; FIXME: I think I can make this more efficient
6836 (defun org-split-string (string &optional separators)
6837 "Splits STRING into substrings at SEPARATORS.
6838 No empty strings are returned if there are matches at the beginning
6839 and end of string."
6840 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6841 (start 0)
6842 notfirst
6843 (list nil))
6844 (while (and (string-match rexp string
6845 (if (and notfirst
6846 (= start (match-beginning 0))
6847 (< start (length string)))
6848 (1+ start) start))
6849 (< (match-beginning 0) (length string)))
6850 (setq notfirst t)
6851 (or (eq (match-beginning 0) 0)
6852 (and (eq (match-beginning 0) (match-end 0))
6853 (eq (match-beginning 0) start))
6854 (setq list
6855 (cons (substring string start (match-beginning 0))
6856 list)))
6857 (setq start (match-end 0)))
6858 (or (eq start (length string))
6859 (setq list
6860 (cons (substring string start)
6861 list)))
6862 (nreverse list)))
6863
6864 (defun org-table-add-invisible-to-vertical-lines ()
6865 "Add an `invisible' property to vertical lines of current table."
6866 (interactive)
6867 (let* ((beg (org-table-begin))
6868 (end (org-table-end))
6869 (end1))
6870 (save-excursion
6871 (goto-char beg)
6872 (while (< (point) end)
6873 (setq end1 (point-at-eol))
6874 (if (looking-at org-table-dataline-regexp)
6875 (while (re-search-forward "|" end1 t)
6876 (add-text-properties (1- (point)) (point)
6877 '(invisible org-table)))
6878 (while (re-search-forward "[+|]" end1 t)
6879 (add-text-properties (1- (point)) (point)
6880 '(invisible org-table))))
6881 (beginning-of-line 2)))))
6882
6883 (defun org-table-toggle-vline-visibility (&optional arg)
6884 "Toggle the visibility of table vertical lines.
6885 The effect is immediate and on all tables in the file.
6886 With prefix ARG, make lines invisible when ARG is positive, make lines
6887 visible when ARG is not positive"
6888 (interactive "P")
6889 (let ((action (cond
6890 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6891 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6892 (t (if (org-in-invisibility-spec-p '(org-table))
6893 'off
6894 'on)))))
6895 (if (eq action 'off)
6896 (progn
6897 (org-remove-from-invisibility-spec '(org-table))
6898 (org-table-map-tables 'org-table-align)
6899 (message "Vertical table lines visible")
6900 (if (org-at-table-p)
6901 (org-table-align)))
6902 (org-add-to-invisibility-spec '(org-table))
6903 (org-table-map-tables 'org-table-align)
6904 (message "Vertical table lines invisible"))
6905 (redraw-frame (selected-frame))))
6906
6907 (defun org-table-map-tables (function)
6908 "Apply FUNCTION to the start of all tables in the buffer."
6909 (save-excursion
6910 (save-restriction
6911 (widen)
6912 (goto-char (point-min))
6913 (while (re-search-forward org-table-any-line-regexp nil t)
6914 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6915 (beginning-of-line 1)
6916 (if (looking-at org-table-line-regexp)
6917 (save-excursion (funcall function)))
6918 (re-search-forward org-table-any-border-regexp nil 1)))))
6919
6920 (defun org-table-sum (&optional beg end nlast)
6921 "Sum numbers in region of current table column.
6922 The result will be displayed in the echo area, and will be available
6923 as kill to be inserted with \\[yank].
6924
6925 If there is an active region, it is interpreted as a rectangle and all
6926 numbers in that rectangle will be summed. If there is no active
6927 region and point is located in a table column, sum all numbers in that
6928 column.
6929
6930 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6931 numbers are assumed to be times as well (in decimal hours) and the
6932 numbers are added as such.
6933
6934 If NLAST is a number, only the NLAST fields will actually be summed."
6935 (interactive)
6936 (save-excursion
6937 (let (col (timecnt 0) diff h m s org-table-clip)
6938 (cond
6939 ((and beg end)) ; beg and end given explicitly
6940 ((org-region-active-p)
6941 (setq beg (region-beginning) end (region-end)))
6942 (t
6943 (setq col (org-table-current-column))
6944 (goto-char (org-table-begin))
6945 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6946 (error "No table data"))
6947 (org-table-goto-column col)
6948 ;not needed? (skip-chars-backward "^|")
6949 (setq beg (point))
6950 (goto-char (org-table-end))
6951 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6952 (error "No table data"))
6953 (org-table-goto-column col)
6954 ;not needed? (skip-chars-forward "^|")
6955 (setq end (point))))
6956 (let* ((items (apply 'append (org-table-copy-region beg end)))
6957 (items1 (cond ((not nlast) items)
6958 ((>= nlast (length items)) items)
6959 (t (setq items (reverse items))
6960 (setcdr (nthcdr (1- nlast) items) nil)
6961 (nreverse items))))
6962 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6963 items1)))
6964 (res (apply '+ numbers))
6965 (sres (if (= timecnt 0)
6966 (format "%g" res)
6967 (setq diff (* 3600 res)
6968 h (floor (/ diff 3600)) diff (mod diff 3600)
6969 m (floor (/ diff 60)) diff (mod diff 60)
6970 s diff)
6971 (format "%d:%02d:%02d" h m s))))
6972 (kill-new sres)
6973 (if (interactive-p)
6974 (message (substitute-command-keys
6975 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6976 (length numbers) sres))))
6977 sres))))
6978
6979 (defun org-table-get-number-for-summing (s)
6980 (let (n)
6981 (if (string-match "^ *|? *" s)
6982 (setq s (replace-match "" nil nil s)))
6983 (if (string-match " *|? *$" s)
6984 (setq s (replace-match "" nil nil s)))
6985 (setq n (string-to-number s))
6986 (cond
6987 ((and (string-match "0" s)
6988 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6989 ((string-match "\\`[ \t]+\\'" s) nil)
6990 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6991 (let ((h (string-to-number (or (match-string 1 s) "0")))
6992 (m (string-to-number (or (match-string 2 s) "0")))
6993 (s (string-to-number (or (match-string 4 s) "0"))))
6994 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6995 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6996 ((equal n 0) nil)
6997 (t n))))
6998
6999 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7000 "Get a calc vector from a column, according to descriptor DESC.
7001 Optional arguments TBEG and COL can give the beginning of the table
7002 and the current column, to avoid unnecessary parsing."
7003 (save-excursion
7004 (or tbeg (setq tbeg (org-table-begin)))
7005 (or col (setq col (org-table-current-column)))
7006 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7007 (cond
7008 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7009 (setq n1 (- (match-end 1) (match-beginning 1)))
7010 (if (match-beginning 3)
7011 (setq n2 (- (match-end 2) (match-beginning 3))))
7012 (setq n (if n2 (max n1 n2) n1))
7013 (setq n1 (if n2 (min n1 n2)))
7014 (setq nn n)
7015 (while (and (> nn 0)
7016 (re-search-backward org-table-hline-regexp tbeg t))
7017 (push (org-current-line) hline-list)
7018 (setq nn (1- nn)))
7019 (setq hline-list (nreverse hline-list))
7020 (goto-line (nth (1- n) hline-list))
7021 (when (re-search-forward org-table-dataline-regexp)
7022 (org-table-goto-column col)
7023 (setq beg (point)))
7024 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7025 (when (re-search-backward org-table-dataline-regexp)
7026 (org-table-goto-column col)
7027 (setq end (point)))
7028 (setq l (apply 'append (org-table-copy-region beg end)))
7029 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7030 (if (equal x "") "0" x))
7031 l ",") "]"))
7032 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7033 (setq n1 (string-to-number (match-string 1 desc))
7034 n2 (string-to-number (match-string 2 desc)))
7035 (beginning-of-line 1)
7036 (save-excursion
7037 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7038 (org-table-goto-column col)
7039 (setq beg (point))))
7040 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7041 (org-table-goto-column col)
7042 (setq end (point)))
7043 (setq l (apply 'append (org-table-copy-region beg end)))
7044 (concat "[" (mapconcat
7045 (lambda (x) (setq x (org-trim x))
7046 (if (equal x "") "0" x))
7047 l ",") "]"))
7048 ((string-match "\\([0-9]+\\)" desc)
7049 (beginning-of-line 1)
7050 (when (re-search-backward org-table-dataline-regexp tbeg t
7051 (string-to-number (match-string 0 desc)))
7052 (org-table-goto-column col)
7053 (org-trim (org-table-get-field))))))))
7054
7055 (defvar org-table-formula-history nil)
7056
7057 (defvar org-table-column-names nil
7058 "Alist with column names, derived from the `!' line.")
7059 (defvar org-table-column-name-regexp nil
7060 "Regular expression matching the current column names.")
7061 (defvar org-table-local-parameters nil
7062 "Alist with parameter names, derived from the `$' line.")
7063 (defvar org-table-named-field-locations nil
7064 "Alist with locations of named fields.")
7065
7066 (defun org-table-get-formula (&optional equation named)
7067 "Read a formula from the minibuffer, offer stored formula as default."
7068 (let* ((name (car (rassoc (list (org-current-line)
7069 (org-table-current-column))
7070 org-table-named-field-locations)))
7071 (scol (if named
7072 (if name name
7073 (error "Not in a named field"))
7074 (int-to-string (org-table-current-column))))
7075 (dummy (and name (not named)
7076 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7077 (error "Abort")))
7078 (org-table-may-need-update nil)
7079 (stored-list (org-table-get-stored-formulas))
7080 (stored (cdr (assoc scol stored-list)))
7081 (eq (cond
7082 ((and stored equation (string-match "^ *= *$" equation))
7083 stored)
7084 ((stringp equation)
7085 equation)
7086 (t (read-string
7087 (format "%s formula $%s=" (if named "Field" "Column") scol)
7088 (or stored "") 'org-table-formula-history
7089 ;stored
7090 ))))
7091 mustsave)
7092 (when (not (string-match "\\S-" eq))
7093 ;; remove formula
7094 (setq stored-list (delq (assoc scol stored-list) stored-list))
7095 (org-table-store-formulas stored-list)
7096 (error "Formula removed"))
7097 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7098 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7099 (if (and name (not named))
7100 ;; We set the column equation, delete the named one.
7101 (setq stored-list (delq (assoc name stored-list) stored-list)
7102 mustsave t))
7103 (if stored
7104 (setcdr (assoc scol stored-list) eq)
7105 (setq stored-list (cons (cons scol eq) stored-list)))
7106 (if (or mustsave (not (equal stored eq)))
7107 (org-table-store-formulas stored-list))
7108 eq))
7109
7110 (defun org-table-store-formulas (alist)
7111 "Store the list of formulas below the current table."
7112 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7113 (save-excursion
7114 (goto-char (org-table-end))
7115 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7116 (delete-region (point) (match-end 0)))
7117 (insert "#+TBLFM: "
7118 (mapconcat (lambda (x)
7119 (concat "$" (car x) "=" (cdr x)))
7120 alist "::")
7121 "\n")))
7122
7123 (defun org-table-get-stored-formulas ()
7124 "Return an alist with the t=stored formulas directly after current table."
7125 (interactive)
7126 (let (scol eq eq-alist strings string seen)
7127 (save-excursion
7128 (goto-char (org-table-end))
7129 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7130 (setq strings (org-split-string (match-string 2) " *:: *"))
7131 (while (setq string (pop strings))
7132 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7133 (setq scol (match-string 1 string)
7134 eq (match-string 2 string)
7135 eq-alist (cons (cons scol eq) eq-alist))
7136 (if (member scol seen)
7137 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7138 (push scol seen))))))
7139 (nreverse eq-alist)))
7140
7141 (defun org-table-modify-formulas (action &rest columns)
7142 "Modify the formulas stored below the current table.
7143 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7144 expected, for the other action only a single column number is needed."
7145 (let ((list (org-table-get-stored-formulas))
7146 (nmax (length (org-split-string
7147 (buffer-substring (point-at-bol) (point-at-eol))
7148 "|")))
7149 col col1 col2 scol si sc1 sc2)
7150 (cond
7151 ((null list)) ; No action needed if there are no stored formulas
7152 ((eq action 'remove)
7153 (setq col (car columns)
7154 scol (int-to-string col))
7155 (org-table-replace-in-formulas list scol "INVALID")
7156 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7157 (loop for i from (1+ col) upto nmax by 1 do
7158 (setq si (int-to-string i))
7159 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7160 (if (assoc si list) (setcar (assoc si list)
7161 (int-to-string (1- i))))))
7162 ((eq action 'insert)
7163 (setq col (car columns))
7164 (loop for i from nmax downto col by 1 do
7165 (setq si (int-to-string i))
7166 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7167 (if (assoc si list) (setcar (assoc si list)
7168 (int-to-string (1+ i))))))
7169 ((eq action 'swap)
7170 (setq col1 (car columns) col2 (nth 1 columns)
7171 sc1 (int-to-string col1) sc2 (int-to-string col2))
7172 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7173 (org-table-replace-in-formulas list sc1 "ZqZ")
7174 (org-table-replace-in-formulas list sc2 sc1)
7175 (org-table-replace-in-formulas list "ZqZ" sc2)
7176 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7177 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7178 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7179 (t (error "Invalid action in `org-table-modify-formulas'")))
7180 (if list (org-table-store-formulas list))))
7181
7182 (defun org-table-replace-in-formulas (list s1 s2)
7183 (let (elt re s)
7184 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7185 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7186 re (concat (regexp-quote s1) "\\>"))
7187 (while (setq elt (pop list))
7188 (setq s (cdr elt))
7189 (while (string-match re s)
7190 (setq s (replace-match s2 t t s)))
7191 (setcdr elt s))))
7192
7193 (defun org-table-get-specials ()
7194 "Get the column nmaes and local parameters for this table."
7195 (save-excursion
7196 (let ((beg (org-table-begin)) (end (org-table-end))
7197 names name fields fields1 field cnt c v line col)
7198 (setq org-table-column-names nil
7199 org-table-local-parameters nil
7200 org-table-named-field-locations nil)
7201 (goto-char beg)
7202 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7203 (setq names (org-split-string (match-string 1) " *| *")
7204 cnt 1)
7205 (while (setq name (pop names))
7206 (setq cnt (1+ cnt))
7207 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7208 (push (cons name (int-to-string cnt)) org-table-column-names))))
7209 (setq org-table-column-names (nreverse org-table-column-names))
7210 (setq org-table-column-name-regexp
7211 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7212 (goto-char beg)
7213 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7214 (setq fields (org-split-string (match-string 1) " *| *"))
7215 (while (setq field (pop fields))
7216 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7217 (push (cons (match-string 1 field) (match-string 2 field))
7218 org-table-local-parameters))))
7219 (goto-char beg)
7220 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7221 (setq c (match-string 1)
7222 fields (org-split-string (match-string 2) " *| *"))
7223 (save-excursion
7224 (beginning-of-line (if (equal c "_") 2 0))
7225 (setq line (org-current-line) col 1)
7226 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7227 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7228 (while (and fields1 (setq field (pop fields)))
7229 (setq v (pop fields1) col (1+ col))
7230 (when (and (stringp field) (stringp v)
7231 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7232 (push (cons field v) org-table-local-parameters)
7233 (push (list field line col) org-table-named-field-locations)))))))
7234
7235 (defun org-this-word ()
7236 ;; Get the current word
7237 (save-excursion
7238 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7239 (end (progn (skip-chars-forward "^ \t\n") (point))))
7240 (buffer-substring-no-properties beg end))))
7241
7242 (defun org-table-maybe-eval-formula ()
7243 "Check if the current field starts with \"=\" or \":=\".
7244 If yes, store the formula and apply it."
7245 ;; We already know we are in a table. Get field will only return a formula
7246 ;; when appropriate. It might return a separator line, but no problem.
7247 (when org-table-formula-evaluate-inline
7248 (let* ((field (org-trim (or (org-table-get-field) "")))
7249 named eq)
7250 (when (string-match "^:?=\\(.+\\)" field)
7251 (setq named (equal (string-to-char field) ?:)
7252 eq (match-string 1 field))
7253 (if (fboundp 'calc-eval)
7254 (org-table-eval-formula (if named '(4) nil) eq))))))
7255
7256 (defvar org-recalc-commands nil
7257 "List of commands triggering the reccalculation of a line.
7258 Will be filled automatically during use.")
7259
7260 (defvar org-recalc-marks
7261 '((" " . "Unmarked: no special line, no automatic recalculation")
7262 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7263 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7264 ("!" . "Column name definition line. Reference in formula as $name.")
7265 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7266 ("_" . "Names for values in row below this one.")
7267 ("^" . "Names for values in row above this one.")))
7268
7269 (defun org-table-rotate-recalc-marks (&optional newchar)
7270 "Rotate the recalculation mark in the first column.
7271 If in any row, the first field is not consistent with a mark,
7272 insert a new column for the makers.
7273 When there is an active region, change all the lines in the region,
7274 after prompting for the marking character.
7275 After each change, a message will be displayed indication the meaning
7276 of the new mark."
7277 (interactive)
7278 (unless (org-at-table-p) (error "Not at a table"))
7279 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7280 (beg (org-table-begin))
7281 (end (org-table-end))
7282 (l (org-current-line))
7283 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7284 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7285 (have-col
7286 (save-excursion
7287 (goto-char beg)
7288 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7289 (col (org-table-current-column))
7290 (forcenew (car (assoc newchar org-recalc-marks)))
7291 epos new)
7292 (when l1
7293 (message "Change region to what mark? Type # * ! $ or SPC: ")
7294 (setq newchar (char-to-string (read-char-exclusive))
7295 forcenew (car (assoc newchar org-recalc-marks))))
7296 (if (and newchar (not forcenew))
7297 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7298 newchar))
7299 (if l1 (goto-line l1))
7300 (save-excursion
7301 (beginning-of-line 1)
7302 (unless (looking-at org-table-dataline-regexp)
7303 (error "Not at a table data line")))
7304 (unless have-col
7305 (org-table-goto-column 1)
7306 (org-table-insert-column)
7307 (org-table-goto-column (1+ col)))
7308 (setq epos (point-at-eol))
7309 (save-excursion
7310 (beginning-of-line 1)
7311 (org-table-get-field
7312 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7313 (concat " "
7314 (setq new (or forcenew
7315 (cadr (member (match-string 1) marks))))
7316 " ")
7317 " # ")))
7318 (if (and l1 l2)
7319 (progn
7320 (goto-line l1)
7321 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7322 (and (looking-at org-table-dataline-regexp)
7323 (org-table-get-field 1 (concat " " new " "))))
7324 (goto-line l1)))
7325 (if (not (= epos (point-at-eol))) (org-table-align))
7326 (goto-line l)
7327 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7328
7329 (defun org-table-maybe-recalculate-line ()
7330 "Recompute the current line if marked for it, and if we haven't just done it."
7331 (interactive)
7332 (and org-table-allow-automatic-line-recalculation
7333 (not (and (memq last-command org-recalc-commands)
7334 (equal org-last-recalc-line (org-current-line))))
7335 (save-excursion (beginning-of-line 1)
7336 (looking-at org-table-auto-recalculate-regexp))
7337 (fboundp 'calc-eval)
7338 (org-table-recalculate) t))
7339
7340 (defvar org-table-formula-debug nil
7341 "Non-nil means, debug table formulas.
7342 When nil, simply write \"#ERROR\" in corrupted fields.")
7343
7344 (defvar modes)
7345 (defsubst org-set-calc-mode (var &optional value)
7346 (if (stringp var)
7347 (setq var (assoc var '(("D" calc-angle-mode deg)
7348 ("R" calc-angle-mode rad)
7349 ("F" calc-prefer-frac t)
7350 ("S" calc-symbolic-mode t)))
7351 value (nth 2 var) var (nth 1 var)))
7352 (if (memq var modes)
7353 (setcar (cdr (memq var modes)) value)
7354 (cons var (cons value modes)))
7355 modes)
7356
7357 (defun org-table-eval-formula (&optional arg equation
7358 suppress-align suppress-const
7359 suppress-store)
7360 "Replace the table field value at the cursor by the result of a calculation.
7361
7362 This function makes use of Dave Gillespie's calc package, in my view the
7363 most exciting program ever written for GNU Emacs. So you need to have calc
7364 installed in order to use this function.
7365
7366 In a table, this command replaces the value in the current field with the
7367 result of a formula. It also installes the formula as the \"current\" column
7368 formula, by storing it in a special line below the table. When called
7369 with a `C-u' prefix, the current field must ba a named field, and the
7370 formula is installed as valid in only this specific field.
7371
7372 When called, the command first prompts for a formula, which is read in
7373 the minibuffer. Previously entered formulas are available through the
7374 history list, and the last used formula is offered as a default.
7375 These stored formulas are adapted correctly when moving, inserting, or
7376 deleting columns with the corresponding commands.
7377
7378 The formula can be any algebraic expression understood by the calc package.
7379 For details, see the Org-mode manual.
7380
7381 This function can also be called from Lisp programs and offers
7382 additional Arguments: EQUATION can be the formula to apply. If this
7383 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7384 used to speed-up recursive calls by by-passing unnecessary aligns.
7385 SUPPRESS-CONST suppresses the interpretation of constants in the
7386 formula, assuming that this has been done already outside the fuction.
7387 SUPPRESS-STORE means the formula should not be stored, either because
7388 it is already stored, or because it is a modified equation that should
7389 not overwrite the stored one."
7390 (interactive "P")
7391 (require 'calc)
7392 (org-table-check-inside-data-field)
7393 (org-table-get-specials)
7394 (let* (fields
7395 (ndown (if (integerp arg) arg 1))
7396 (org-table-automatic-realign nil)
7397 (case-fold-search nil)
7398 (down (> ndown 1))
7399 (formula (if (and equation suppress-store)
7400 equation
7401 (org-table-get-formula equation (equal arg '(4)))))
7402 (n0 (org-table-current-column))
7403 (modes (copy-sequence org-calc-default-modes))
7404 n form fmt x ev orig c)
7405 ;; Parse the format string. Since we have a lot of modes, this is
7406 ;; a lot of work. However, I think calc still uses most of the time.
7407 (if (string-match ";" formula)
7408 (let ((tmp (org-split-string formula ";")))
7409 (setq formula (car tmp)
7410 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7411 (nth 1 tmp)))
7412 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7413 (setq c (string-to-char (match-string 1 fmt))
7414 n (string-to-number (or (match-string 1 fmt) "")))
7415 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7416 (setq modes (org-set-calc-mode
7417 'calc-float-format
7418 (list (cdr (assoc c '((?n. float) (?f. fix)
7419 (?s. sci) (?e. eng))))
7420 n))))
7421 (setq fmt (replace-match "" t t fmt)))
7422 (while (string-match "[DRFS]" fmt)
7423 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7424 (setq fmt (replace-match "" t t fmt)))
7425 (unless (string-match "\\S-" fmt)
7426 (setq fmt nil))))
7427 (if (and (not suppress-const) org-table-formula-use-constants)
7428 (setq formula (org-table-formula-substitute-names formula)))
7429 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7430 (while (> ndown 0)
7431 (setq fields (org-split-string
7432 (buffer-substring
7433 (point-at-bol) (point-at-eol)) " *| *"))
7434 (if org-table-formula-numbers-only
7435 (setq fields (mapcar
7436 (lambda (x) (number-to-string (string-to-number x)))
7437 fields)))
7438 (setq ndown (1- ndown))
7439 (setq form (copy-sequence formula))
7440 ;; Insert the references to fields in same row
7441 (while (string-match "\\$\\([0-9]+\\)?" form)
7442 (setq n (if (match-beginning 1)
7443 (string-to-int (match-string 1 form))
7444 n0)
7445 x (nth (1- n) fields))
7446 (unless x (error "Invalid field specifier \"%s\""
7447 (match-string 0 form)))
7448 (if (equal x "") (setq x "0"))
7449 (setq form (replace-match (concat "(" x ")") t t form)))
7450 ;; Insert ranges in current column
7451 (while (string-match "\\&[-I0-9]+" form)
7452 (setq form (replace-match
7453 (save-match-data
7454 (org-table-get-vertical-vector (match-string 0 form)
7455 nil n0))
7456 t t form)))
7457 (setq ev (calc-eval (cons form modes)
7458 (if org-table-formula-numbers-only 'num)))
7459
7460 (when org-table-formula-debug
7461 (with-output-to-temp-buffer "*Help*"
7462 (princ (format "Substitution history of formula
7463 Orig: %s
7464 $xyz-> %s
7465 $1-> %s\n" orig formula form))
7466 (if (listp ev)
7467 (princ (format " %s^\nError: %s"
7468 (make-string (car ev) ?\-) (nth 1 ev)))
7469 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7470 ev (or fmt "NONE")
7471 (if fmt (format fmt (string-to-number ev)) ev)))))
7472 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7473 (unless (and (interactive-p) (not ndown))
7474 (unless (let (inhibit-redisplay)
7475 (y-or-n-p "Debugging Formula. Continue to next? "))
7476 (org-table-align)
7477 (error "Abort"))
7478 (delete-window (get-buffer-window "*Help*"))
7479 (message "")))
7480 (if (listp ev) (setq fmt nil ev "#ERROR"))
7481 (org-table-justify-field-maybe
7482 (if fmt (format fmt (string-to-number ev)) ev))
7483 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7484 (call-interactively 'org-return)
7485 (setq ndown 0)))
7486 (and down (org-table-maybe-recalculate-line))
7487 (or suppress-align (and org-table-may-need-update
7488 (org-table-align)))))
7489
7490 (defun org-table-recalculate (&optional all noalign)
7491 "Recalculate the current table line by applying all stored formulas."
7492 (interactive "P")
7493 (or (memq this-command org-recalc-commands)
7494 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7495 (unless (org-at-table-p) (error "Not at a table"))
7496 (org-table-get-specials)
7497 (let* ((eqlist (sort (org-table-get-stored-formulas)
7498 (lambda (a b) (string< (car a) (car b)))))
7499 (inhibit-redisplay t)
7500 (line-re org-table-dataline-regexp)
7501 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7502 (thiscol (org-table-current-column))
7503 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7504 ;; Insert constants in all formulas
7505 (setq eqlist
7506 (mapcar (lambda (x)
7507 (setcdr x (org-table-formula-substitute-names (cdr x)))
7508 x)
7509 eqlist))
7510 ;; Split the equation list
7511 (while (setq eq (pop eqlist))
7512 (if (<= (string-to-char (car eq)) ?9)
7513 (push eq eqlnum)
7514 (push eq eqlname)))
7515 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7516 (if all
7517 (progn
7518 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7519 (goto-char (setq beg (org-table-begin)))
7520 (if (re-search-forward org-table-calculate-mark-regexp end t)
7521 ;; This is a table with marked lines, only compute selected lines
7522 (setq line-re org-table-recalculate-regexp)
7523 ;; Move forward to the first non-header line
7524 (if (and (re-search-forward org-table-dataline-regexp end t)
7525 (re-search-forward org-table-hline-regexp end t)
7526 (re-search-forward org-table-dataline-regexp end t))
7527 (setq beg (match-beginning 0))
7528 nil))) ;; just leave beg where it is
7529 (setq beg (point-at-bol)
7530 end (move-marker (make-marker) (1+ (point-at-eol)))))
7531 (goto-char beg)
7532 (and all (message "Re-applying formulas to full table..."))
7533 (while (re-search-forward line-re end t)
7534 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7535 ;; Unprotected line, recalculate
7536 (and all (message "Re-applying formulas to full table...(line %d)"
7537 (setq cnt (1+ cnt))))
7538 (setq org-last-recalc-line (org-current-line))
7539 (setq eql eqlnum)
7540 (while (setq entry (pop eql))
7541 (goto-line org-last-recalc-line)
7542 (org-table-goto-column (string-to-int (car entry)) nil 'force)
7543 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7544 (goto-line thisline)
7545 (org-table-goto-column thiscol)
7546 (or noalign (and org-table-may-need-update (org-table-align))
7547 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7548 ;; Now do the names fields
7549 (while (setq eq (pop eqlname))
7550 (setq name (car eq)
7551 a (assoc name org-table-named-field-locations))
7552 (when a
7553 (message "Re-applying formula to named field: %s" name)
7554 (goto-line (nth 1 a))
7555 (org-table-goto-column (nth 2 a))
7556 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7557 ;; back to initial position
7558 (goto-line thisline)
7559 (org-table-goto-column thiscol)
7560 (or noalign (and org-table-may-need-update (org-table-align))
7561 (and all (message "Re-applying formulas...done")))))
7562
7563 (defun org-table-formula-substitute-names (f)
7564 "Replace $const with values in string F."
7565 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7566 ;; First, check for column names
7567 (while (setq start (string-match org-table-column-name-regexp f start))
7568 (setq start (1+ start))
7569 (setq a (assoc (match-string 1 f) org-table-column-names))
7570 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7571 ;; Expand ranges to vectors
7572 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7573 (setq n1 (string-to-number (match-string 1 f))
7574 n2 (string-to-number (match-string 2 f))
7575 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7576 s (concat "[($" (number-to-string (1- nn1)) ")"))
7577 (loop for i from nn1 upto nn2 do
7578 (setq s (concat s ",($" (int-to-string i) ")")))
7579 (setq s (concat s "]"))
7580 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7581 (setq f (replace-match s t t f)))
7582 ;; Parameters and constants
7583 (setq start 0)
7584 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7585 (setq start (1+ start))
7586 (if (setq a (save-match-data
7587 (org-table-get-constant (match-string 1 f))))
7588 (setq f (replace-match (concat "(" a ")") t t f))))
7589 (if org-table-formula-debug
7590 (put-text-property 0 (length f) :orig-formula f1 f))
7591 f))
7592
7593 (defun org-table-get-constant (const)
7594 "Find the value for a parameter or constant in a formula.
7595 Parameters get priority."
7596 (or (cdr (assoc const org-table-local-parameters))
7597 (cdr (assoc const org-table-formula-constants))
7598 (and (fboundp 'constants-get) (constants-get const))
7599 "#UNDEFINED_NAME"))
7600
7601 (defvar org-edit-formulas-map (make-sparse-keymap))
7602 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7603 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7604 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7605
7606 (defvar org-pos)
7607 (defvar org-window-configuration)
7608
7609 (defun org-table-edit-formulas ()
7610 "Edit the formulas of the current table in a separate buffer."
7611 (interactive)
7612 (unless (org-at-table-p)
7613 (error "Not at a table"))
7614 (org-table-get-specials)
7615 (let ((eql (org-table-get-stored-formulas))
7616 (pos (move-marker (make-marker) (point)))
7617 (wc (current-window-configuration))
7618 entry loc s)
7619 (switch-to-buffer-other-window "*Edit Formulas*")
7620 (erase-buffer)
7621 (fundamental-mode)
7622 (set (make-local-variable 'org-pos) pos)
7623 (set (make-local-variable 'org-window-configuration) wc)
7624 (use-local-map org-edit-formulas-map)
7625 (setq s "# Edit formulas and finish with `C-c C-c'.
7626 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7627 # Use `C-c ?' to get information about $name at point.
7628 # To cancel editing, press `C-c C-q'.\n")
7629 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7630 (insert s)
7631 (while (setq entry (pop eql))
7632 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7633 (setq s (format "# Named formula, referring to column %d in line %d\n"
7634 (nth 2 loc) (nth 1 loc)))
7635 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7636 (insert s))
7637 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7638 (remove-text-properties 0 (length s) '(face nil) s)
7639 (insert s))
7640 (goto-char (point-min))
7641 (message "Edit formulas and finish with `C-c C-c'.")))
7642
7643 (defun org-show-variable ()
7644 "Show the location/value of the $ expression at point."
7645 (interactive)
7646 (let (var (pos org-pos) (win (selected-window)) e)
7647 (save-excursion
7648 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7649 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7650 (setq var (match-string 1))
7651 (error "No variable at point")))
7652 (cond
7653 ((setq e (assoc var org-table-named-field-locations))
7654 (switch-to-buffer-other-window (marker-buffer pos))
7655 (goto-line (nth 1 e))
7656 (org-table-goto-column (nth 2 e))
7657 (select-window win)
7658 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7659 ((setq e (assoc var org-table-column-names))
7660 (switch-to-buffer-other-window (marker-buffer pos))
7661 (goto-char pos)
7662 (goto-char (org-table-begin))
7663 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7664 (org-table-end) t)
7665 (progn
7666 (goto-char (match-beginning 1))
7667 (message "Named column (column %s)" (cdr e)))
7668 (error "Column name not found"))
7669 (select-window win))
7670 ((string-match "^[0-9]$" var)
7671 ;; column number
7672 (switch-to-buffer-other-window (marker-buffer pos))
7673 (goto-char pos)
7674 (goto-char (org-table-begin))
7675 (recenter 1)
7676 (if (re-search-forward org-table-dataline-regexp
7677 (org-table-end) t)
7678 (progn
7679 (goto-char (match-beginning 0))
7680 (org-table-goto-column (string-to-number var))
7681 (message "Column %s" var))
7682 (error "Column name not found"))
7683 (select-window win))
7684 ((setq e (assoc var org-table-local-parameters))
7685 (switch-to-buffer-other-window (marker-buffer pos))
7686 (goto-char pos)
7687 (goto-char (org-table-begin))
7688 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7689 (progn
7690 (goto-char (match-beginning 1))
7691 (message "Local parameter."))
7692 (error "Parameter not found"))
7693 (select-window win))
7694 (t
7695 (cond
7696 ((setq e (assoc var org-table-formula-constants))
7697 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7698 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7699 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7700 (t (error "Undefined name $%s" var)))))))
7701
7702 (defun org-finish-edit-formulas (&optional arg)
7703 "Parse the buffer for formula definitions and install them.
7704 With prefix ARG, apply the new formulas to the table."
7705 (interactive "P")
7706 (let ((pos org-pos) eql)
7707 (goto-char (point-min))
7708 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7709 (push (cons (match-string 1) (match-string 2)) eql))
7710 (set-window-configuration org-window-configuration)
7711 (select-window (get-buffer-window (marker-buffer pos)))
7712 (goto-char pos)
7713 (unless (org-at-table-p)
7714 (error "Lost table position - cannot install formulae"))
7715 (org-table-store-formulas eql)
7716 (move-marker pos nil)
7717 (kill-buffer "*Edit Formulas*")
7718 (if arg
7719 (org-table-recalculate 'all)
7720 (message "New formulas installed - press C-u C-c C-c to apply."))))
7721
7722 (defun org-abort-edit-formulas ()
7723 "Abort editing formulas, without installing the changes."
7724 (interactive)
7725 (let ((pos org-pos))
7726 (set-window-configuration org-window-configuration)
7727 (select-window (get-buffer-window (marker-buffer pos)))
7728 (goto-char pos)
7729 (message "Formula editing aborted without installing changes")))
7730
7731 ;;; The orgtbl minor mode
7732
7733 ;; Define a minor mode which can be used in other modes in order to
7734 ;; integrate the org-mode table editor.
7735
7736 ;; This is really a hack, because the org-mode table editor uses several
7737 ;; keys which normally belong to the major mode, for example the TAB and
7738 ;; RET keys. Here is how it works: The minor mode defines all the keys
7739 ;; necessary to operate the table editor, but wraps the commands into a
7740 ;; function which tests if the cursor is currently inside a table. If that
7741 ;; is the case, the table editor command is executed. However, when any of
7742 ;; those keys is used outside a table, the function uses `key-binding' to
7743 ;; look up if the key has an associated command in another currently active
7744 ;; keymap (minor modes, major mode, global), and executes that command.
7745 ;; There might be problems if any of the keys used by the table editor is
7746 ;; otherwise used as a prefix key.
7747
7748 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7749 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7750 ;; addresses this by checking explicitly for both bindings.
7751
7752 ;; The optimized version (see variable `orgtbl-optimized') takes over
7753 ;; all keys which are bound to `self-insert-command' in the *global map*.
7754 ;; Some modes bind other commands to simple characters, for example
7755 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7756 ;; active, this binding is ignored inside tables and replaced with a
7757 ;; modified self-insert.
7758
7759 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7760 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7761 In the optimized version, the table editor takes over all simple keys that
7762 normally just insert a character. In tables, the characters are inserted
7763 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7764 for empty fields). Outside tables, the correct binding of the keys is
7765 restored.
7766
7767 The default for this option is t if the optimized version is also used in
7768 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7769 this variable requires a restart of Emacs to become effective."
7770 :group 'org-table
7771 :type 'boolean)
7772
7773 (defvar orgtbl-mode nil
7774 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7775 table editor in arbitrary modes.")
7776 (make-variable-buffer-local 'orgtbl-mode)
7777
7778 (defvar orgtbl-mode-map (make-sparse-keymap)
7779 "Keymap for `orgtbl-mode'.")
7780
7781 ;;;###autoload
7782 (defun turn-on-orgtbl ()
7783 "Unconditionally turn on `orgtbl-mode'."
7784 (orgtbl-mode 1))
7785
7786 ;;;###autoload
7787 (defun orgtbl-mode (&optional arg)
7788 "The `org-mode' table editor as a minor mode for use in other modes."
7789 (interactive)
7790 (if (eq major-mode 'org-mode)
7791 ;; Exit without error, in case some hook functions calls this
7792 ;; by accident in org-mode.
7793 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7794 (setq orgtbl-mode
7795 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7796 (if orgtbl-mode
7797 (progn
7798 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7799 ;; Make sure we are first in minor-mode-map-alist
7800 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7801 (and c (setq minor-mode-map-alist
7802 (cons c (delq c minor-mode-map-alist)))))
7803 (set (make-local-variable (quote org-table-may-need-update)) t)
7804 (make-local-hook (quote before-change-functions))
7805 (add-hook 'before-change-functions 'org-before-change-function
7806 nil 'local)
7807 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7808 auto-fill-inhibit-regexp)
7809 (set (make-local-variable 'auto-fill-inhibit-regexp)
7810 (if auto-fill-inhibit-regexp
7811 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7812 "[ \t]*|"))
7813 (easy-menu-add orgtbl-mode-menu)
7814 (run-hooks 'orgtbl-mode-hook))
7815 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7816 (remove-hook 'before-change-functions 'org-before-change-function t)
7817 (easy-menu-remove orgtbl-mode-menu)
7818 (force-mode-line-update 'all))))
7819
7820 ;; Install it as a minor mode.
7821 (put 'orgtbl-mode :included t)
7822 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7823 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7824
7825 (defun orgtbl-make-binding (fun n &rest keys)
7826 "Create a function for binding in the table minor mode.
7827 FUN is the command to call inside a table. N is used to create a unique
7828 command name. KEYS are keys that should be checked in for a command
7829 to execute outside of tables."
7830 (eval
7831 (list 'defun
7832 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7833 '(arg)
7834 (concat "In tables, run `" (symbol-name fun) "'.\n"
7835 "Outside of tables, run the binding of `"
7836 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7837 "'.")
7838 '(interactive "p")
7839 (list 'if
7840 '(org-at-table-p)
7841 (list 'call-interactively (list 'quote fun))
7842 (list 'let '(orgtbl-mode)
7843 (list 'call-interactively
7844 (append '(or)
7845 (mapcar (lambda (k)
7846 (list 'key-binding k))
7847 keys)
7848 '('orgtbl-error))))))))
7849
7850 (defun orgtbl-error ()
7851 "Error when there is no default binding for a table key."
7852 (interactive)
7853 (error "This key is has no function outside tables"))
7854
7855 (defun orgtbl-setup ()
7856 "Setup orgtbl keymaps."
7857 (let ((nfunc 0)
7858 (bindings
7859 (list
7860 '([(meta shift left)] org-table-delete-column)
7861 '([(meta left)] org-table-move-column-left)
7862 '([(meta right)] org-table-move-column-right)
7863 '([(meta shift right)] org-table-insert-column)
7864 '([(meta shift up)] org-table-kill-row)
7865 '([(meta shift down)] org-table-insert-row)
7866 '([(meta up)] org-table-move-row-up)
7867 '([(meta down)] org-table-move-row-down)
7868 '("\C-c\C-w" org-table-cut-region)
7869 '("\C-c\M-w" org-table-copy-region)
7870 '("\C-c\C-y" org-table-paste-rectangle)
7871 '("\C-c-" org-table-insert-hline)
7872 '([(shift tab)] org-table-previous-field)
7873 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7874 '("\C-m" org-table-next-row)
7875 (list (org-key 'S-return) 'org-table-copy-down)
7876 '([(meta return)] org-table-wrap-region)
7877 '("\C-c\C-q" org-table-wrap-region)
7878 '("\C-c?" org-table-current-column)
7879 '("\C-c " org-table-blank-field)
7880 '("\C-c+" org-table-sum)
7881 '("\C-c|" org-table-toggle-vline-visibility)
7882 '("\C-c=" org-table-eval-formula)
7883 '("\C-c'" org-table-edit-formulas)
7884 '("\C-c*" org-table-recalculate)
7885 '([(control ?#)] org-table-rotate-recalc-marks)))
7886 elt key fun cmd)
7887 (while (setq elt (pop bindings))
7888 (setq nfunc (1+ nfunc))
7889 (setq key (car elt)
7890 fun (nth 1 elt)
7891 cmd (orgtbl-make-binding fun nfunc key))
7892 (define-key orgtbl-mode-map key cmd))
7893 ;; Special treatment needed for TAB and RET
7894 (define-key orgtbl-mode-map [(return)]
7895 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7896 (define-key orgtbl-mode-map "\C-m"
7897 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7898 (define-key orgtbl-mode-map [(tab)]
7899 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7900 (define-key orgtbl-mode-map "\C-i"
7901 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7902 (when orgtbl-optimized
7903 ;; If the user wants maximum table support, we need to hijack
7904 ;; some standard editing functions
7905 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7906 orgtbl-mode-map global-map)
7907 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7908 orgtbl-mode-map global-map)
7909 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7910 orgtbl-mode-map global-map)
7911 (define-key org-mode-map "|" 'self-insert-command))
7912 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7913 '("OrgTbl"
7914 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7915 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7916 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7917 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7918 "--"
7919 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7920 ["Copy Field from Above"
7921 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7922 "--"
7923 ("Column"
7924 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7925 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7926 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7927 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7928 ("Row"
7929 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7930 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7931 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7932 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7933 "--"
7934 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7935 ("Rectangle"
7936 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7937 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7938 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7939 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7940 "--"
7941 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7942 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7943 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
7944 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7945 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7946 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7947 ["Sum Column/Rectangle" org-table-sum
7948 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7949 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7950 ["Debug Formulas"
7951 (setq org-table-formula-debug (not org-table-formula-debug))
7952 :style toggle :selected org-table-formula-debug]
7953 ))
7954 t)
7955
7956 (defun orgtbl-tab ()
7957 "Justification and field motion for `orgtbl-mode'."
7958 (interactive)
7959 (org-table-justify-field-maybe)
7960 (org-table-next-field))
7961
7962 (defun orgtbl-ret ()
7963 "Justification and field motion for `orgtbl-mode'."
7964 (interactive)
7965 (org-table-justify-field-maybe)
7966 (org-table-next-row))
7967
7968 (defun orgtbl-self-insert-command (N)
7969 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7970 If the cursor is in a table looking at whitespace, the whitespace is
7971 overwritten, and the table is not marked as requiring realignment."
7972 (interactive "p")
7973 (if (and (org-at-table-p)
7974 (eq N 1)
7975 (looking-at "[^|\n]* +|"))
7976 (let (org-table-may-need-update)
7977 (goto-char (1- (match-end 0)))
7978 (delete-backward-char 1)
7979 (goto-char (match-beginning 0))
7980 (self-insert-command N))
7981 (setq org-table-may-need-update t)
7982 (let (orgtbl-mode)
7983 (call-interactively (key-binding (vector last-input-event))))))
7984
7985 (defun orgtbl-delete-backward-char (N)
7986 "Like `delete-backward-char', insert whitespace at field end in tables.
7987 When deleting backwards, in tables this function will insert whitespace in
7988 front of the next \"|\" separator, to keep the table aligned. The table will
7989 still be marked for re-alignment, because a narrow field may lead to a
7990 reduced column width."
7991 (interactive "p")
7992 (if (and (org-at-table-p)
7993 (eq N 1)
7994 (string-match "|" (buffer-substring (point-at-bol) (point)))
7995 (looking-at ".*?|"))
7996 (let ((pos (point)))
7997 (backward-delete-char N)
7998 (skip-chars-forward "^|")
7999 (insert " ")
8000 (goto-char (1- pos)))
8001 (delete-backward-char N)))
8002
8003 (defun orgtbl-delete-char (N)
8004 "Like `delete-char', but insert whitespace at field end in tables.
8005 When deleting characters, in tables this function will insert whitespace in
8006 front of the next \"|\" separator, to keep the table aligned. The table
8007 will still be marked for re-alignment, because a narrow field may lead to
8008 a reduced column width."
8009 (interactive "p")
8010 (if (and (org-at-table-p)
8011 (not (bolp))
8012 (not (= (char-after) ?|))
8013 (eq N 1))
8014 (if (looking-at ".*?|")
8015 (let ((pos (point)))
8016 (replace-match (concat
8017 (substring (match-string 0) 1 -1)
8018 " |"))
8019 (goto-char pos)))
8020 (delete-char N)))
8021
8022 ;;; Exporting
8023
8024 (defconst org-level-max 20)
8025
8026 (defun org-export-find-first-heading-line (list)
8027 "Remove all lines from LIST which are before the first headline."
8028 (let ((orig-list list)
8029 (re (concat "^" outline-regexp)))
8030 (while (and list
8031 (not (string-match re (car list))))
8032 (pop list))
8033 (or list orig-list)))
8034
8035 (defun org-skip-comments (lines)
8036 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8037 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8038 (re2 "^\\(\\*+\\)[ \t\n\r]")
8039 rtn line level)
8040 (while (setq line (pop lines))
8041 (cond
8042 ((and (string-match re1 line)
8043 (setq level (- (match-end 1) (match-beginning 1))))
8044 ;; Beginning of a COMMENT subtree. Skip it.
8045 (while (and (setq line (pop lines))
8046 (or (not (string-match re2 line))
8047 (> (- (match-end 1) (match-beginning 1)) level))))
8048 (setq lines (cons line lines)))
8049 ((string-match "^#" line)
8050 ;; an ordinary comment line
8051 )
8052 (t (setq rtn (cons line rtn)))))
8053 (nreverse rtn)))
8054
8055 ;; ASCII
8056
8057 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8058 "Characters for underlining headings in ASCII export.")
8059
8060 (defconst org-html-entities
8061 '(("nbsp")
8062 ("iexcl")
8063 ("cent")
8064 ("pound")
8065 ("curren")
8066 ("yen")
8067 ("brvbar")
8068 ("sect")
8069 ("uml")
8070 ("copy")
8071 ("ordf")
8072 ("laquo")
8073 ("not")
8074 ("shy")
8075 ("reg")
8076 ("macr")
8077 ("deg")
8078 ("plusmn")
8079 ("sup2")
8080 ("sup3")
8081 ("acute")
8082 ("micro")
8083 ("para")
8084 ("middot")
8085 ("odot"."o")
8086 ("star"."*")
8087 ("cedil")
8088 ("sup1")
8089 ("ordm")
8090 ("raquo")
8091 ("frac14")
8092 ("frac12")
8093 ("frac34")
8094 ("iquest")
8095 ("Agrave")
8096 ("Aacute")
8097 ("Acirc")
8098 ("Atilde")
8099 ("Auml")
8100 ("Aring") ("AA"."&Aring;")
8101 ("AElig")
8102 ("Ccedil")
8103 ("Egrave")
8104 ("Eacute")
8105 ("Ecirc")
8106 ("Euml")
8107 ("Igrave")
8108 ("Iacute")
8109 ("Icirc")
8110 ("Iuml")
8111 ("ETH")
8112 ("Ntilde")
8113 ("Ograve")
8114 ("Oacute")
8115 ("Ocirc")
8116 ("Otilde")
8117 ("Ouml")
8118 ("times")
8119 ("Oslash")
8120 ("Ugrave")
8121 ("Uacute")
8122 ("Ucirc")
8123 ("Uuml")
8124 ("Yacute")
8125 ("THORN")
8126 ("szlig")
8127 ("agrave")
8128 ("aacute")
8129 ("acirc")
8130 ("atilde")
8131 ("auml")
8132 ("aring")
8133 ("aelig")
8134 ("ccedil")
8135 ("egrave")
8136 ("eacute")
8137 ("ecirc")
8138 ("euml")
8139 ("igrave")
8140 ("iacute")
8141 ("icirc")
8142 ("iuml")
8143 ("eth")
8144 ("ntilde")
8145 ("ograve")
8146 ("oacute")
8147 ("ocirc")
8148 ("otilde")
8149 ("ouml")
8150 ("divide")
8151 ("oslash")
8152 ("ugrave")
8153 ("uacute")
8154 ("ucirc")
8155 ("uuml")
8156 ("yacute")
8157 ("thorn")
8158 ("yuml")
8159 ("fnof")
8160 ("Alpha")
8161 ("Beta")
8162 ("Gamma")
8163 ("Delta")
8164 ("Epsilon")
8165 ("Zeta")
8166 ("Eta")
8167 ("Theta")
8168 ("Iota")
8169 ("Kappa")
8170 ("Lambda")
8171 ("Mu")
8172 ("Nu")
8173 ("Xi")
8174 ("Omicron")
8175 ("Pi")
8176 ("Rho")
8177 ("Sigma")
8178 ("Tau")
8179 ("Upsilon")
8180 ("Phi")
8181 ("Chi")
8182 ("Psi")
8183 ("Omega")
8184 ("alpha")
8185 ("beta")
8186 ("gamma")
8187 ("delta")
8188 ("epsilon")
8189 ("varepsilon"."&epsilon;")
8190 ("zeta")
8191 ("eta")
8192 ("theta")
8193 ("iota")
8194 ("kappa")
8195 ("lambda")
8196 ("mu")
8197 ("nu")
8198 ("xi")
8199 ("omicron")
8200 ("pi")
8201 ("rho")
8202 ("sigmaf") ("varsigma"."&sigmaf;")
8203 ("sigma")
8204 ("tau")
8205 ("upsilon")
8206 ("phi")
8207 ("chi")
8208 ("psi")
8209 ("omega")
8210 ("thetasym") ("vartheta"."&thetasym;")
8211 ("upsih")
8212 ("piv")
8213 ("bull") ("bullet"."&bull;")
8214 ("hellip") ("dots"."&hellip;")
8215 ("prime")
8216 ("Prime")
8217 ("oline")
8218 ("frasl")
8219 ("weierp")
8220 ("image")
8221 ("real")
8222 ("trade")
8223 ("alefsym")
8224 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8225 ("uarr") ("uparrow"."&uarr;")
8226 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8227 ("darr")("downarrow"."&darr;")
8228 ("harr") ("leftrightarrow"."&harr;")
8229 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8230 ("lArr") ("Leftarrow"."&lArr;")
8231 ("uArr") ("Uparrow"."&uArr;")
8232 ("rArr") ("Rightarrow"."&rArr;")
8233 ("dArr") ("Downarrow"."&dArr;")
8234 ("hArr") ("Leftrightarrow"."&hArr;")
8235 ("forall")
8236 ("part") ("partial"."&part;")
8237 ("exist") ("exists"."&exist;")
8238 ("empty") ("emptyset"."&empty;")
8239 ("nabla")
8240 ("isin") ("in"."&isin;")
8241 ("notin")
8242 ("ni")
8243 ("prod")
8244 ("sum")
8245 ("minus")
8246 ("lowast") ("ast"."&lowast;")
8247 ("radic")
8248 ("prop") ("proptp"."&prop;")
8249 ("infin") ("infty"."&infin;")
8250 ("ang") ("angle"."&ang;")
8251 ("and") ("vee"."&and;")
8252 ("or") ("wedge"."&or;")
8253 ("cap")
8254 ("cup")
8255 ("int")
8256 ("there4")
8257 ("sim")
8258 ("cong") ("simeq"."&cong;")
8259 ("asymp")("approx"."&asymp;")
8260 ("ne") ("neq"."&ne;")
8261 ("equiv")
8262 ("le")
8263 ("ge")
8264 ("sub") ("subset"."&sub;")
8265 ("sup") ("supset"."&sup;")
8266 ("nsub")
8267 ("sube")
8268 ("supe")
8269 ("oplus")
8270 ("otimes")
8271 ("perp")
8272 ("sdot") ("cdot"."&sdot;")
8273 ("lceil")
8274 ("rceil")
8275 ("lfloor")
8276 ("rfloor")
8277 ("lang")
8278 ("rang")
8279 ("loz") ("Diamond"."&loz;")
8280 ("spades") ("spadesuit"."&spades;")
8281 ("clubs") ("clubsuit"."&clubs;")
8282 ("hearts") ("diamondsuit"."&hearts;")
8283 ("diams") ("diamondsuit"."&diams;")
8284 ("quot")
8285 ("amp")
8286 ("lt")
8287 ("gt")
8288 ("OElig")
8289 ("oelig")
8290 ("Scaron")
8291 ("scaron")
8292 ("Yuml")
8293 ("circ")
8294 ("tilde")
8295 ("ensp")
8296 ("emsp")
8297 ("thinsp")
8298 ("zwnj")
8299 ("zwj")
8300 ("lrm")
8301 ("rlm")
8302 ("ndash")
8303 ("mdash")
8304 ("lsquo")
8305 ("rsquo")
8306 ("sbquo")
8307 ("ldquo")
8308 ("rdquo")
8309 ("bdquo")
8310 ("dagger")
8311 ("Dagger")
8312 ("permil")
8313 ("lsaquo")
8314 ("rsaquo")
8315 ("euro")
8316
8317 ("arccos"."arccos")
8318 ("arcsin"."arcsin")
8319 ("arctan"."arctan")
8320 ("arg"."arg")
8321 ("cos"."cos")
8322 ("cosh"."cosh")
8323 ("cot"."cot")
8324 ("coth"."coth")
8325 ("csc"."csc")
8326 ("deg"."deg")
8327 ("det"."det")
8328 ("dim"."dim")
8329 ("exp"."exp")
8330 ("gcd"."gcd")
8331 ("hom"."hom")
8332 ("inf"."inf")
8333 ("ker"."ker")
8334 ("lg"."lg")
8335 ("lim"."lim")
8336 ("liminf"."liminf")
8337 ("limsup"."limsup")
8338 ("ln"."ln")
8339 ("log"."log")
8340 ("max"."max")
8341 ("min"."min")
8342 ("Pr"."Pr")
8343 ("sec"."sec")
8344 ("sin"."sin")
8345 ("sinh"."sinh")
8346 ("sup"."sup")
8347 ("tan"."tan")
8348 ("tanh"."tanh")
8349 )
8350 "Entities for TeX->HTML translation.
8351 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8352 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8353 In that case, \"\\ent\" will be translated to \"&other;\".
8354 The list contains HTML entities for Latin-1, Greek and other symbols.
8355 It is supplemented by a number of commonly used TeX macros with appropriate
8356 translations. There is currently no way for users to extend this.")
8357
8358 (defvar org-last-level nil) ; dynamically scoped variable
8359
8360 (defun org-export-as-ascii (arg)
8361 "Export the outline as a pretty ASCII file.
8362 If there is an active region, export only the region.
8363 The prefix ARG specifies how many levels of the outline should become
8364 underlined headlines. The default is 3."
8365 (interactive "P")
8366 (setq-default org-todo-line-regexp org-todo-line-regexp)
8367 (let* ((region
8368 (buffer-substring
8369 (if (org-region-active-p) (region-beginning) (point-min))
8370 (if (org-region-active-p) (region-end) (point-max))))
8371 (lines (org-export-find-first-heading-line
8372 (org-skip-comments (org-split-string region "[\r\n]"))))
8373 (org-startup-with-deadline-check nil)
8374 (level 0) line txt
8375 (umax nil)
8376 (case-fold-search nil)
8377 (filename (concat (file-name-sans-extension (buffer-file-name))
8378 ".txt"))
8379 (buffer (find-file-noselect filename))
8380 (levels-open (make-vector org-level-max nil))
8381 (date (format-time-string "%Y/%m/%d" (current-time)))
8382 (time (format-time-string "%X" (current-time)))
8383 (author user-full-name)
8384 (title (buffer-name))
8385 (options nil)
8386 (email user-mail-address)
8387 (language org-export-default-language)
8388 (text nil)
8389 (todo nil)
8390 (lang-words nil))
8391
8392 (setq org-last-level 1)
8393 (org-init-section-numbers)
8394
8395 (find-file-noselect filename)
8396
8397 ;; Search for the export key lines
8398 (org-parse-key-lines)
8399
8400 (setq lang-words (or (assoc language org-export-language-setup)
8401 (assoc "en" org-export-language-setup)))
8402 (if org-export-ascii-show-new-buffer
8403 (switch-to-buffer-other-window buffer)
8404 (set-buffer buffer))
8405 (erase-buffer)
8406 (fundamental-mode)
8407 (if options (org-parse-export-options options))
8408 (setq umax (if arg (prefix-numeric-value arg)
8409 org-export-headline-levels))
8410
8411 ;; File header
8412 (if title (org-insert-centered title ?=))
8413 (insert "\n")
8414 (if (or author email)
8415 (insert (concat (nth 1 lang-words) ": " (or author "")
8416 (if email (concat " <" email ">") "")
8417 "\n")))
8418 (if (and date time)
8419 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8420 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8421
8422 (insert "\n\n")
8423
8424 (if org-export-with-toc
8425 (progn
8426 (insert (nth 3 lang-words) "\n"
8427 (make-string (length (nth 3 lang-words)) ?=) "\n")
8428 (mapcar '(lambda (line)
8429 (if (string-match org-todo-line-regexp
8430 line)
8431 ;; This is a headline
8432 (progn
8433 (setq level (- (match-end 1) (match-beginning 1))
8434 txt (match-string 3 line)
8435 todo
8436 (or (and (match-beginning 2)
8437 (not (equal (match-string 2 line)
8438 org-done-string)))
8439 ; TODO, not DONE
8440 (and (= level umax)
8441 (org-search-todo-below
8442 line lines level))))
8443 (setq txt (org-html-expand-for-ascii txt))
8444
8445 (if org-export-with-section-numbers
8446 (setq txt (concat (org-section-number level)
8447 " " txt)))
8448 (if (<= level umax)
8449 (progn
8450 (insert
8451 (make-string (* (1- level) 4) ?\ )
8452 (format (if todo "%s (*)\n" "%s\n") txt))
8453 (setq org-last-level level))
8454 ))))
8455 lines)))
8456
8457 (org-init-section-numbers)
8458 (while (setq line (pop lines))
8459 ;; Remove the quoted HTML tags.
8460 (setq line (org-html-expand-for-ascii line))
8461 (cond
8462 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8463 ;; a Headline
8464 (setq level (- (match-end 1) (match-beginning 1))
8465 txt (match-string 2 line))
8466 (org-ascii-level-start level txt umax))
8467 (t (insert line "\n"))))
8468 (normal-mode)
8469 (save-buffer)
8470 (goto-char (point-min))))
8471
8472 (defun org-search-todo-below (line lines level)
8473 "Search the subtree below LINE for any TODO entries."
8474 (let ((rest (cdr (memq line lines)))
8475 (re org-todo-line-regexp)
8476 line lv todo)
8477 (catch 'exit
8478 (while (setq line (pop rest))
8479 (if (string-match re line)
8480 (progn
8481 (setq lv (- (match-end 1) (match-beginning 1))
8482 todo (and (match-beginning 2)
8483 (not (equal (match-string 2 line)
8484 org-done-string))))
8485 ; TODO, not DONE
8486 (if (<= lv level) (throw 'exit nil))
8487 (if todo (throw 'exit t))))))))
8488
8489 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8490 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8491 (defun org-html-expand-for-ascii (line)
8492 "Handle quoted HTML for ASCII export."
8493 (if org-export-html-expand
8494 (while (string-match "@<[^<>\n]*>" line)
8495 ;; We just remove the tags for now.
8496 (setq line (replace-match "" nil nil line))))
8497 line)
8498
8499 (defun org-insert-centered (s &optional underline)
8500 "Insert the string S centered and underline it with character UNDERLINE."
8501 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8502 (insert (make-string ind ?\ ) s "\n")
8503 (if underline
8504 (insert (make-string ind ?\ )
8505 (make-string (length s) underline)
8506 "\n"))))
8507
8508 (defun org-ascii-level-start (level title umax)
8509 "Insert a new level in ASCII export."
8510 (let (char)
8511 (if (> level umax)
8512 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8513 (if (or (not (equal (char-before) ?\n))
8514 (not (equal (char-before (1- (point))) ?\n)))
8515 (insert "\n"))
8516 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8517 (if org-export-with-section-numbers
8518 (setq title (concat (org-section-number level) " " title)))
8519 (insert title "\n" (make-string (string-width title) char) "\n"))))
8520
8521 (defun org-export-copy-visible ()
8522 "Copy the visible part of the buffer to another buffer, for printing.
8523 Also removes the first line of the buffer if it specifies a mode,
8524 and all options lines."
8525 (interactive)
8526 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8527 ".txt"))
8528 (buffer (find-file-noselect filename))
8529 (ore (concat
8530 (org-make-options-regexp
8531 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8532 "STARTUP" "ARCHIVE"
8533 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8534 (if org-noutline-p "\\(\n\\|$\\)" "")))
8535 s e)
8536 (with-current-buffer buffer
8537 (erase-buffer)
8538 (text-mode))
8539 (save-excursion
8540 (setq s (goto-char (point-min)))
8541 (while (not (= (point) (point-max)))
8542 (goto-char (org-find-invisible))
8543 (append-to-buffer buffer s (point))
8544 (setq s (goto-char (org-find-visible)))))
8545 (switch-to-buffer-other-window buffer)
8546 (newline)
8547 (goto-char (point-min))
8548 (if (looking-at ".*-\\*- mode:.*\n")
8549 (replace-match ""))
8550 (while (re-search-forward ore nil t)
8551 (replace-match ""))
8552 (goto-char (point-min))))
8553
8554 (defun org-find-visible ()
8555 (if (featurep 'noutline)
8556 (let ((s (point)))
8557 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8558 (get-char-property s 'invisible)))
8559 s)
8560 (skip-chars-forward "^\n")
8561 (point)))
8562 (defun org-find-invisible ()
8563 (if (featurep 'noutline)
8564 (let ((s (point)))
8565 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8566 (not (get-char-property s 'invisible))))
8567 s)
8568 (skip-chars-forward "^\r")
8569 (point)))
8570
8571 ;; HTML
8572
8573 (defun org-get-current-options ()
8574 "Return a string with current options as keyword options.
8575 Does include HTML export options as well as TODO and CATEGORY stuff."
8576 (format
8577 "#+TITLE: %s
8578 #+AUTHOR: %s
8579 #+EMAIL: %s
8580 #+LANGUAGE: %s
8581 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8582 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8583 #+CATEGORY: %s
8584 #+SEQ_TODO: %s
8585 #+TYP_TODO: %s
8586 #+STARTUP: %s %s
8587 #+ARCHIVE: %s
8588 "
8589 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8590 org-export-headline-levels
8591 org-export-with-section-numbers
8592 org-export-with-toc
8593 org-export-preserve-breaks
8594 org-export-html-expand
8595 org-export-with-fixed-width
8596 org-export-with-tables
8597 org-export-with-sub-superscripts
8598 org-export-with-emphasize
8599 org-export-with-TeX-macros
8600 (file-name-nondirectory (buffer-file-name))
8601 (if (equal org-todo-interpretation 'sequence)
8602 (mapconcat 'identity org-todo-keywords " ")
8603 "TODO FEEDBACK VERIFY DONE")
8604 (if (equal org-todo-interpretation 'type)
8605 (mapconcat 'identity org-todo-keywords " ")
8606 "Me Jason Marie DONE")
8607 (cdr (assoc org-startup-folded
8608 '((nil . "nofold")(t . "fold")(content . "content"))))
8609 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8610 org-archive-location
8611 ))
8612
8613 (defun org-insert-export-options-template ()
8614 "Insert into the buffer a template with information for exporting."
8615 (interactive)
8616 (if (not (bolp)) (newline))
8617 (let ((s (org-get-current-options)))
8618 (and (string-match "#\\+CATEGORY" s)
8619 (setq s (substring s 0 (match-beginning 0))))
8620 (insert s)))
8621
8622 (defun org-toggle-fixed-width-section (arg)
8623 "Toggle the fixed-width indicator at the beginning of lines in the region.
8624 If there is no active region, only acts on the current line.
8625 If the first non-white character in the first line of the region is a
8626 vertical bar \"|\", then the command removes the bar from all lines in
8627 the region. If the first character is not a bar, the command adds a
8628 bar to all lines, in the column given by the beginning of the region.
8629
8630 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8631 (interactive "P")
8632 (let* ((cc 0)
8633 (regionp (org-region-active-p))
8634 (beg (if regionp (region-beginning) (point)))
8635 (end (if regionp (region-end)))
8636 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8637 (re "[ \t]*\\(:\\)")
8638 off)
8639 (save-excursion
8640 (goto-char beg)
8641 (setq cc (current-column))
8642 (beginning-of-line 1)
8643 (setq off (looking-at re))
8644 (while (> nlines 0)
8645 (setq nlines (1- nlines))
8646 (beginning-of-line 1)
8647 (cond
8648 (arg
8649 (move-to-column cc t)
8650 (insert ":\n")
8651 (forward-line -1))
8652 ((and off (looking-at re))
8653 (replace-match "" t t nil 1))
8654 ((not off) (move-to-column cc t) (insert ":")))
8655 (forward-line 1)))))
8656
8657 (defun org-export-as-html-and-open (arg)
8658 "Export the outline as HTML and immediately open it with a browser.
8659 If there is an active region, export only the region.
8660 The prefix ARG specifies how many levels of the outline should become
8661 headlines. The default is 3. Lower levels will become bulleted lists."
8662 (interactive "P")
8663 (org-export-as-html arg 'hidden)
8664 (org-open-file (buffer-file-name)))
8665
8666 (defun org-export-as-html-batch ()
8667 "Call `org-export-as-html', may be used in batch processing as
8668 emacs --batch
8669 --load=$HOME/lib/emacs/org.el
8670 --eval \"(setq org-export-headline-levels 2)\"
8671 --visit=MyFile --funcall org-export-as-html-batch"
8672 (org-export-as-html org-export-headline-levels 'hidden))
8673
8674 (defun org-export-as-html (arg &optional hidden)
8675 "Export the outline as a pretty HTML file.
8676 If there is an active region, export only the region.
8677 The prefix ARG specifies how many levels of the outline should become
8678 headlines. The default is 3. Lower levels will become bulleted lists."
8679 (interactive "P")
8680 (setq-default org-todo-line-regexp org-todo-line-regexp)
8681 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8682 (setq-default org-done-string org-done-string)
8683 (let* ((region-p (org-region-active-p))
8684 (region
8685 (buffer-substring
8686 (if region-p (region-beginning) (point-min))
8687 (if region-p (region-end) (point-max))))
8688 (all_lines
8689 (org-skip-comments (org-split-string region "[\r\n]")))
8690 (lines (org-export-find-first-heading-line all_lines))
8691 (level 0) (line "") (origline "") txt todo
8692 (umax nil)
8693 (filename (concat (file-name-sans-extension (buffer-file-name))
8694 ".html"))
8695 (buffer (find-file-noselect filename))
8696 (levels-open (make-vector org-level-max nil))
8697 (date (format-time-string "%Y/%m/%d" (current-time)))
8698 (time (format-time-string "%X" (current-time)))
8699 (author user-full-name)
8700 (title (buffer-name))
8701 (options nil)
8702 (email user-mail-address)
8703 (language org-export-default-language)
8704 (text nil)
8705 (lang-words nil)
8706 (head-count 0) cnt
8707 (start 0)
8708 table-open type
8709 table-buffer table-orig-buffer
8710 )
8711 (message "Exporting...")
8712
8713 (setq org-last-level 1)
8714 (org-init-section-numbers)
8715
8716 ;; Search for the export key lines
8717 (org-parse-key-lines)
8718 (setq lang-words (or (assoc language org-export-language-setup)
8719 (assoc "en" org-export-language-setup)))
8720
8721 ;; Switch to the output buffer
8722 (if (or hidden (not org-export-html-show-new-buffer))
8723 (set-buffer buffer)
8724 (switch-to-buffer-other-window buffer))
8725 (erase-buffer)
8726 (fundamental-mode)
8727 (let ((case-fold-search nil))
8728 (if options (org-parse-export-options options))
8729 (setq umax (if arg (prefix-numeric-value arg)
8730 org-export-headline-levels))
8731
8732 ;; File header
8733 (insert (format
8734 "<html lang=\"%s\"><head>
8735 <title>%s</title>
8736 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8737 <meta name=generator content=\"Org-mode\">
8738 <meta name=generated content=\"%s %s\">
8739 <meta name=author content=\"%s\">
8740 </head><body>
8741 "
8742 language (org-html-expand title) date time author))
8743 (if title (insert (concat "<H1 align=\"center\">"
8744 (org-html-expand title) "</H1>\n")))
8745 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8746 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8747 email "&gt;</a>\n")))
8748 (if (or author email) (insert "<br>\n"))
8749 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8750 date " " time "<br>\n")))
8751 (if text (insert (concat "<p>\n" (org-html-expand text))))
8752 (if org-export-with-toc
8753 (progn
8754 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8755 (insert "<ul>\n")
8756 (mapcar '(lambda (line)
8757 (if (string-match org-todo-line-regexp line)
8758 ;; This is a headline
8759 (progn
8760 (setq level (- (match-end 1) (match-beginning 1))
8761 txt (save-match-data
8762 (org-html-expand
8763 (match-string 3 line)))
8764 todo
8765 (or (and (match-beginning 2)
8766 (not (equal (match-string 2 line)
8767 org-done-string)))
8768 ; TODO, not DONE
8769 (and (= level umax)
8770 (org-search-todo-below
8771 line lines level))))
8772 (if org-export-with-section-numbers
8773 (setq txt (concat (org-section-number level)
8774 " " txt)))
8775 (if (<= level umax)
8776 (progn
8777 (setq head-count (+ head-count 1))
8778 (if (> level org-last-level)
8779 (progn
8780 (setq cnt (- level org-last-level))
8781 (while (>= (setq cnt (1- cnt)) 0)
8782 (insert "<ul>"))
8783 (insert "\n")))
8784 (if (< level org-last-level)
8785 (progn
8786 (setq cnt (- org-last-level level))
8787 (while (>= (setq cnt (1- cnt)) 0)
8788 (insert "</ul>"))
8789 (insert "\n")))
8790 (insert
8791 (format
8792 (if todo
8793 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8794 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8795 head-count txt))
8796 (setq org-last-level level))
8797 ))))
8798 lines)
8799 (while (> org-last-level 0)
8800 (setq org-last-level (1- org-last-level))
8801 (insert "</ul>\n"))
8802 ))
8803 (setq head-count 0)
8804 (org-init-section-numbers)
8805 (while (setq line (pop lines) origline line)
8806 ;; Protect the links
8807 (setq start 0)
8808 (while (string-match org-link-maybe-angles-regexp line start)
8809 (setq start (match-end 0))
8810 (setq line (replace-match
8811 (concat "\000" (match-string 1 line) "\000")
8812 t t line)))
8813
8814 ;; replace "<" and ">" by "&lt;" and "&gt;"
8815 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8816 (setq line (org-html-expand line))
8817
8818 ;; Verbatim lines
8819 (if (and org-export-with-fixed-width
8820 (string-match "^[ \t]*:\\(.*\\)" line))
8821 (progn
8822 (let ((l (match-string 1 line)))
8823 (while (string-match " " l)
8824 (setq l (replace-match "&nbsp;" t t l)))
8825 (insert "\n<span style='font-family:Courier'>"
8826 l "</span>"
8827 (if (and lines
8828 (not (string-match "^[ \t]+\\(:.*\\)"
8829 (car lines))))
8830 "<br>\n" "\n"))))
8831 (setq start 0)
8832 (while (string-match org-protected-link-regexp line start)
8833 (setq start (- (match-end 0) 2))
8834 (setq type (match-string 1 line))
8835 (cond
8836 ((member type '("http" "https" "ftp" "mailto" "news"))
8837 ;; standard URL
8838 (setq line (replace-match
8839 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8840 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8841 nil nil line)))
8842 ((string= type "file")
8843 ;; FILE link
8844 (let* ((filename (match-string 2 line))
8845 (abs-p (file-name-absolute-p filename))
8846 (thefile (if abs-p (expand-file-name filename) filename))
8847 (thefile (save-match-data
8848 (if (string-match ":[0-9]+$" thefile)
8849 (replace-match "" t t thefile)
8850 thefile)))
8851 (file-is-image-p
8852 (save-match-data
8853 (string-match (org-image-file-name-regexp) thefile))))
8854 (setq line (replace-match
8855 (if (and org-export-html-inline-images
8856 file-is-image-p)
8857 (concat "<img src=\"" thefile "\"/>")
8858 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8859 nil nil line))))
8860
8861 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8862 (setq line (replace-match
8863 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
8864
8865 ;; TODO items
8866 (if (and (string-match org-todo-line-regexp line)
8867 (match-beginning 2))
8868 (if (equal (match-string 2 line) org-done-string)
8869 (setq line (replace-match
8870 "<span style='color:green'>\\2</span>"
8871 nil nil line 2))
8872 (setq line (replace-match "<span style='color:red'>\\2</span>"
8873 nil nil line 2))))
8874
8875 ;; DEADLINES
8876 (if (string-match org-deadline-line-regexp line)
8877 (progn
8878 (if (save-match-data
8879 (string-match "<a href"
8880 (substring line 0 (match-beginning 0))))
8881 nil ; Don't do the replacement - it is inside a link
8882 (setq line (replace-match "<span style='color:red'>\\&</span>"
8883 nil nil line 1)))))
8884
8885 (cond
8886 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8887 ;; This is a headline
8888 (setq level (- (match-end 1) (match-beginning 1))
8889 txt (match-string 2 line))
8890 (if (<= level umax) (setq head-count (+ head-count 1)))
8891 (org-html-level-start level txt umax
8892 (and org-export-with-toc (<= level umax))
8893 head-count))
8894
8895 ((and org-export-with-tables
8896 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8897 (if (not table-open)
8898 ;; New table starts
8899 (setq table-open t table-buffer nil table-orig-buffer nil))
8900 ;; Accumulate lines
8901 (setq table-buffer (cons line table-buffer)
8902 table-orig-buffer (cons origline table-orig-buffer))
8903 (when (or (not lines)
8904 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8905 (car lines))))
8906 (setq table-open nil
8907 table-buffer (nreverse table-buffer)
8908 table-orig-buffer (nreverse table-orig-buffer))
8909 (insert (org-format-table-html table-buffer table-orig-buffer))))
8910 (t
8911 ;; Normal lines
8912 ;; Lines starting with "-", and empty lines make new paragraph.
8913 ;; FIXME: Should we add + and *?
8914 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8915 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8916 ))
8917 (if org-export-html-with-timestamp
8918 (insert org-export-html-html-helper-timestamp))
8919 (insert "</body>\n</html>\n")
8920 (normal-mode)
8921 (save-buffer)
8922 (goto-char (point-min)))))
8923
8924 (defun org-format-table-html (lines olines)
8925 "Find out which HTML converter to use and return the HTML code."
8926 (if (string-match "^[ \t]*|" (car lines))
8927 ;; A normal org table
8928 (org-format-org-table-html lines)
8929 ;; Table made by table.el - test for spanning
8930 (let* ((hlines (delq nil (mapcar
8931 (lambda (x)
8932 (if (string-match "^[ \t]*\\+-" x) x
8933 nil))
8934 lines)))
8935 (first (car hlines))
8936 (ll (and (string-match "\\S-+" first)
8937 (match-string 0 first)))
8938 (re (concat "^[ \t]*" (regexp-quote ll)))
8939 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8940 hlines))))
8941 (if (and (not spanning)
8942 (not org-export-prefer-native-exporter-for-tables))
8943 ;; We can use my own converter with HTML conversions
8944 (org-format-table-table-html lines)
8945 ;; Need to use the code generator in table.el, with the original text.
8946 (org-format-table-table-html-using-table-generate-source olines)))))
8947
8948 (defun org-format-org-table-html (lines)
8949 "Format a table into html."
8950 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8951 (setq lines (nreverse lines))
8952 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8953 (setq lines (nreverse lines))
8954 (let ((head (and org-export-highlight-first-table-line
8955 (delq nil (mapcar
8956 (lambda (x) (string-match "^[ \t]*|-" x))
8957 (cdr lines)))))
8958 line fields html)
8959 (setq html (concat org-export-html-table-tag "\n"))
8960 (while (setq line (pop lines))
8961 (catch 'next-line
8962 (if (string-match "^[ \t]*|-" line)
8963 (progn
8964 (setq head nil) ;; head ends here, first time around
8965 ;; ignore this line
8966 (throw 'next-line t)))
8967 ;; Break the line into fields
8968 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8969 (setq html (concat
8970 html
8971 "<tr>"
8972 (mapconcat (lambda (x)
8973 (if head
8974 (concat "<th>" x "</th>")
8975 (concat "<td valign=\"top\">" x "</td>")))
8976 fields "")
8977 "</tr>\n"))))
8978 (setq html (concat html "</table>\n"))
8979 html))
8980
8981 (defun org-fake-empty-table-line (line)
8982 "Replace everything except \"|\" with spaces."
8983 (let ((i (length line))
8984 (newstr (copy-sequence line)))
8985 (while (> i 0)
8986 (setq i (1- i))
8987 (if (not (eq (aref newstr i) ?|))
8988 (aset newstr i ?\ )))
8989 newstr))
8990
8991 (defun org-format-table-table-html (lines)
8992 "Format a table generated by table.el into html.
8993 This conversion does *not* use `table-generate-source' from table.el.
8994 This has the advantage that Org-mode's HTML conversions can be used.
8995 But it has the disadvantage, that no cell- or row-spanning is allowed."
8996 (let (line field-buffer
8997 (head org-export-highlight-first-table-line)
8998 fields html empty)
8999 (setq html (concat org-export-html-table-tag "\n"))
9000 (while (setq line (pop lines))
9001 (setq empty "&nbsp")
9002 (catch 'next-line
9003 (if (string-match "^[ \t]*\\+-" line)
9004 (progn
9005 (if field-buffer
9006 (progn
9007 (setq html (concat
9008 html
9009 "<tr>"
9010 (mapconcat
9011 (lambda (x)
9012 (if (equal x "") (setq x empty))
9013 (if head
9014 (concat "<th valign=\"top\">" x
9015 "</th>\n")
9016 (concat "<td valign=\"top\">" x
9017 "</td>\n")))
9018 field-buffer "\n")
9019 "</tr>\n"))
9020 (setq head nil)
9021 (setq field-buffer nil)))
9022 ;; Ignore this line
9023 (throw 'next-line t)))
9024 ;; Break the line into fields and store the fields
9025 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9026 (if field-buffer
9027 (setq field-buffer (mapcar
9028 (lambda (x)
9029 (concat x "<br>" (pop fields)))
9030 field-buffer))
9031 (setq field-buffer fields))))
9032 (setq html (concat html "</table>\n"))
9033 html))
9034
9035 (defun org-format-table-table-html-using-table-generate-source (lines)
9036 "Format a table into html, using `table-generate-source' from table.el.
9037 This has the advantage that cell- or row-spanning is allowed.
9038 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9039 (require 'table)
9040 (with-current-buffer (get-buffer-create " org-tmp1 ")
9041 (erase-buffer)
9042 (insert (mapconcat 'identity lines "\n"))
9043 (goto-char (point-min))
9044 (if (not (re-search-forward "|[^+]" nil t))
9045 (error "Error processing table"))
9046 (table-recognize-table)
9047 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9048 (table-generate-source 'html " org-tmp2 ")
9049 (set-buffer " org-tmp2 ")
9050 (buffer-substring (point-min) (point-max))))
9051
9052 (defun org-html-expand (string)
9053 "Prepare STRING for HTML export. Applies all active conversions."
9054 ;; First check if there is a link in the line - if yes, apply conversions
9055 ;; only before the start of the link.
9056 (let* ((m (string-match org-link-regexp string))
9057 (s (if m (substring string 0 m) string))
9058 (r (if m (substring string m) "")))
9059 ;; convert < to &lt; and > to &gt;
9060 (while (string-match "<" s)
9061 (setq s (replace-match "&lt;" t t s)))
9062 (while (string-match ">" s)
9063 (setq s (replace-match "&gt;" t t s)))
9064 (if org-export-html-expand
9065 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9066 (setq s (replace-match "<\\1>" nil nil s))))
9067 (if org-export-with-emphasize
9068 (setq s (org-export-html-convert-emphasize s)))
9069 (if org-export-with-sub-superscripts
9070 (setq s (org-export-html-convert-sub-super s)))
9071 (if org-export-with-TeX-macros
9072 (let ((start 0) wd ass)
9073 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9074 (setq wd (match-string 1 s))
9075 (if (setq ass (assoc wd org-html-entities))
9076 (setq s (replace-match (or (cdr ass)
9077 (concat "&" (car ass) ";"))
9078 t t s))
9079 (setq start (+ start (length wd)))))))
9080 (concat s r)))
9081
9082 (defun org-create-multibrace-regexp (left right n)
9083 "Create a regular expression which will match a balanced sexp.
9084 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9085 as single character strings.
9086 The regexp returned will match the entire expression including the
9087 delimiters. It will also define a single group which contains the
9088 match except for the outermost delimiters. The maximum depth of
9089 stacked delimiters is N. Escaping delimiters is not possible."
9090 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9091 (or "\\|")
9092 (re nothing)
9093 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9094 (while (> n 1)
9095 (setq n (1- n)
9096 re (concat re or next)
9097 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9098 (concat left "\\(" re "\\)" right)))
9099
9100 (defvar org-match-substring-regexp
9101 (concat
9102 "\\([^\\]\\)\\([_^]\\)\\("
9103 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9104 "\\|"
9105 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9106 "\\|"
9107 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9108 "The regular expression matching a sub- or superscript.")
9109
9110 (defun org-export-html-convert-sub-super (string)
9111 "Convert sub- and superscripts in STRING to HTML."
9112 (let (key c)
9113 (while (string-match org-match-substring-regexp string)
9114 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9115 (setq c (or (match-string 8 string)
9116 (match-string 6 string)
9117 (match-string 5 string)))
9118 (setq string (replace-match
9119 (concat (match-string 1 string)
9120 "<" key ">" c "</" key ">")
9121 t t string)))
9122 (while (string-match "\\\\\\([_^]\\)" string)
9123 (setq string (replace-match (match-string 1 string) t t string))))
9124 string)
9125
9126 (defun org-export-html-convert-emphasize (string)
9127 (while (string-match
9128 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9129 string)
9130 (setq string (replace-match
9131 (concat "<b>" (match-string 3 string) "</b>")
9132 t t string 2)))
9133 (while (string-match
9134 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9135 string)
9136 (setq string (replace-match
9137 (concat "<i>" (match-string 3 string) "</i>")
9138 t t string 2)))
9139 (while (string-match
9140 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9141 string)
9142 (setq string (replace-match
9143 (concat "<u>" (match-string 3 string) "</u>")
9144 t t string 2)))
9145 string)
9146
9147 (defun org-parse-key-lines ()
9148 "Find the special key lines with the information for exporters."
9149 (save-excursion
9150 (goto-char 0)
9151 (let ((re (org-make-options-regexp
9152 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9153 key)
9154 (while (re-search-forward re nil t)
9155 (setq key (match-string 1))
9156 (cond ((string-equal key "TITLE")
9157 (setq title (match-string 2)))
9158 ((string-equal key "AUTHOR")
9159 (setq author (match-string 2)))
9160 ((string-equal key "EMAIL")
9161 (setq email (match-string 2)))
9162 ((string-equal key "LANGUAGE")
9163 (setq language (match-string 2)))
9164 ((string-equal key "TEXT")
9165 (setq text (concat text "\n" (match-string 2))))
9166 ((string-equal key "OPTIONS")
9167 (setq options (match-string 2))))))))
9168
9169 (defun org-parse-export-options (s)
9170 "Parse the export options line."
9171 (let ((op '(("H" . org-export-headline-levels)
9172 ("num" . org-export-with-section-numbers)
9173 ("toc" . org-export-with-toc)
9174 ("\\n" . org-export-preserve-breaks)
9175 ("@" . org-export-html-expand)
9176 (":" . org-export-with-fixed-width)
9177 ("|" . org-export-with-tables)
9178 ("^" . org-export-with-sub-superscripts)
9179 ("*" . org-export-with-emphasize)
9180 ("TeX" . org-export-with-TeX-macros)))
9181 o)
9182 (while (setq o (pop op))
9183 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9184 s)
9185 (set (make-local-variable (cdr o))
9186 (car (read-from-string (match-string 1 s))))))))
9187
9188 (defun org-html-level-start (level title umax with-toc head-count)
9189 "Insert a new level in HTML export."
9190 (let ((l (1+ (max level umax))))
9191 (while (<= l org-level-max)
9192 (if (aref levels-open (1- l))
9193 (progn
9194 (org-html-level-close l)
9195 (aset levels-open (1- l) nil)))
9196 (setq l (1+ l)))
9197 (if (> level umax)
9198 (progn
9199 (if (aref levels-open (1- level))
9200 (insert "<li>" title "<p>\n")
9201 (aset levels-open (1- level) t)
9202 (insert "<ul><li>" title "<p>\n")))
9203 (if org-export-with-section-numbers
9204 (setq title (concat (org-section-number level) " " title)))
9205 (setq level (+ level 1))
9206 (if with-toc
9207 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9208 level head-count title level))
9209 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9210
9211 (defun org-html-level-close (&rest args)
9212 "Terminate one level in HTML export."
9213 (insert "</ul>"))
9214
9215
9216 ;; Variable holding the vector with section numbers
9217 (defvar org-section-numbers (make-vector org-level-max 0))
9218
9219 (defun org-init-section-numbers ()
9220 "Initialize the vector for the section numbers."
9221 (let* ((level -1)
9222 (numbers (nreverse (org-split-string "" "\\.")))
9223 (depth (1- (length org-section-numbers)))
9224 (i depth) number-string)
9225 (while (>= i 0)
9226 (if (> i level)
9227 (aset org-section-numbers i 0)
9228 (setq number-string (or (car numbers) "0"))
9229 (if (string-match "\\`[A-Z]\\'" number-string)
9230 (aset org-section-numbers i
9231 (- (string-to-char number-string) ?A -1))
9232 (aset org-section-numbers i (string-to-int number-string)))
9233 (pop numbers))
9234 (setq i (1- i)))))
9235
9236 (defun org-section-number (&optional level)
9237 "Return a string with the current section number.
9238 When LEVEL is non-nil, increase section numbers on that level."
9239 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9240 (when level
9241 (when (> level -1)
9242 (aset org-section-numbers
9243 level (1+ (aref org-section-numbers level))))
9244 (setq idx (1+ level))
9245 (while (<= idx depth)
9246 (if (not (= idx 1))
9247 (aset org-section-numbers idx 0))
9248 (setq idx (1+ idx))))
9249 (setq idx 0)
9250 (while (<= idx depth)
9251 (setq n (aref org-section-numbers idx))
9252 (setq string (concat string (if (not (string= string "")) "." "")
9253 (int-to-string n)))
9254 (setq idx (1+ idx)))
9255 (save-match-data
9256 (if (string-match "\\`\\([@0]\\.\\)+" string)
9257 (setq string (replace-match "" nil nil string)))
9258 (if (string-match "\\(\\.0\\)+\\'" string)
9259 (setq string (replace-match "" nil nil string))))
9260 string))
9261
9262
9263 ;;; Key bindings
9264
9265 ;; - Bindings in Org-mode map are currently
9266 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9267 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9268 ;; e (?) useful from outline-mode
9269 ;; i k @ expendable from outline-mode
9270 ;; 0123456789 ! %^& ()_{} " `' free
9271
9272 (define-key org-mode-map "\C-i" 'org-cycle)
9273 (define-key org-mode-map [(meta tab)] 'org-complete)
9274 (define-key org-mode-map "\M-\C-i" 'org-complete)
9275 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9276 (define-key org-mode-map [(meta left)] 'org-metaleft)
9277 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9278 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9279 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9280 (define-key org-mode-map [(meta right)] 'org-metaright)
9281 (define-key org-mode-map [(meta up)] 'org-metaup)
9282 (define-key org-mode-map [(meta down)] 'org-metadown)
9283 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9284 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9285 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9286 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9287 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9288 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9289 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9290 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9291 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9292 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9293 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9294 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9295 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9296 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9297 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9298 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9299 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9300 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9301 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9302 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9303 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9304 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9305 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9306 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9307 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9308 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9309 (define-key org-mode-map "\C-c[" 'org-add-file)
9310 (define-key org-mode-map "\C-c]" 'org-remove-file)
9311 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9312 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9313 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9314 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9315 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9316 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9317 ;; The following line is necessary for German keyboards under Suse GNU/Linux
9318 (unless org-xemacs-p
9319 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9320 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9321 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9322 (define-key org-mode-map "\C-m" 'org-return)
9323 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9324 (define-key org-mode-map [(meta return)] 'org-meta-return)
9325 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9326 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9327 (define-key org-mode-map "\C-c+" 'org-table-sum)
9328 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9329 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9330 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9331 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9332 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9333 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9334 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9335 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9336 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9337 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9338 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9339 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9340 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9341 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9342 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9343 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9344 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9345
9346 (defsubst org-table-p () (org-at-table-p))
9347
9348 (defun org-self-insert-command (N)
9349 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9350 If the cursor is in a table looking at whitespace, the whitespace is
9351 overwritten, and the table is not marked as requiring realignment."
9352 (interactive "p")
9353 (if (and (org-table-p)
9354 (eq N 1)
9355 (looking-at "[^|\n]* +|"))
9356 (let (org-table-may-need-update)
9357 (goto-char (1- (match-end 0)))
9358 (delete-backward-char 1)
9359 (goto-char (match-beginning 0))
9360 (self-insert-command N))
9361 (setq org-table-may-need-update t)
9362 (self-insert-command N)))
9363
9364 ;; FIXME:
9365 ;; The following two functions might still be optimized to trigger
9366 ;; re-alignment less frequently.
9367
9368 (defun org-delete-backward-char (N)
9369 "Like `delete-backward-char', insert whitespace at field end in tables.
9370 When deleting backwards, in tables this function will insert whitespace in
9371 front of the next \"|\" separator, to keep the table aligned. The table will
9372 still be marked for re-alignment, because a narrow field may lead to a
9373 reduced column width."
9374 (interactive "p")
9375 (if (and (org-table-p)
9376 (eq N 1)
9377 (string-match "|" (buffer-substring (point-at-bol) (point)))
9378 (looking-at ".*?|"))
9379 (let ((pos (point)))
9380 (backward-delete-char N)
9381 (skip-chars-forward "^|")
9382 (insert " ")
9383 (goto-char (1- pos)))
9384 (backward-delete-char N)))
9385
9386 (defun org-delete-char (N)
9387 "Like `delete-char', but insert whitespace at field end in tables.
9388 When deleting characters, in tables this function will insert whitespace in
9389 front of the next \"|\" separator, to keep the table aligned. The table
9390 will still be marked for re-alignment, because a narrow field may lead to
9391 a reduced column width."
9392 (interactive "p")
9393 (if (and (org-table-p)
9394 (not (bolp))
9395 (not (= (char-after) ?|))
9396 (eq N 1))
9397 (if (looking-at ".*?|")
9398 (let ((pos (point)))
9399 (replace-match (concat
9400 (substring (match-string 0) 1 -1)
9401 " |"))
9402 (goto-char pos)))
9403 (delete-char N)))
9404
9405 ;; How to do this: Measure non-white length of current string
9406 ;; If equal to column width, we should realign.
9407
9408 (when (eq org-enable-table-editor 'optimized)
9409 ;; If the user wants maximum table support, we need to hijack
9410 ;; some standard editing functions
9411 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9412 org-mode-map global-map)
9413 (substitute-key-definition 'delete-char 'org-delete-char
9414 org-mode-map global-map)
9415 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9416 org-mode-map global-map)
9417 (define-key org-mode-map "|" 'self-insert-command))
9418
9419 (defun org-shiftcursor-error ()
9420 "Throw an error because Shift-Cursor command was applied in wrong context."
9421 (error "This command is only active in tables and on headlines"))
9422
9423 (defun org-shifttab ()
9424 "Call `(org-cycle t)' or `org-table-previous-field'."
9425 (interactive)
9426 (cond
9427 ((org-at-table-p) (org-table-previous-field))
9428 (t (org-cycle '(4)))))
9429
9430 (defun org-shiftmetaleft ()
9431 "Call `org-promote-subtree' or `org-table-delete-column'."
9432 (interactive)
9433 (cond
9434 ((org-at-table-p) (org-table-delete-column))
9435 ((org-on-heading-p) (org-promote-subtree))
9436 (t (org-shiftcursor-error))))
9437
9438 (defun org-shiftmetaright ()
9439 "Call `org-demote-subtree' or `org-table-insert-column'."
9440 (interactive)
9441 (cond
9442 ((org-at-table-p) (org-table-insert-column))
9443 ((org-on-heading-p) (org-demote-subtree))
9444 (t (org-shiftcursor-error))))
9445
9446 (defun org-shiftmetaup (&optional arg)
9447 "Call `org-move-subtree-up' or `org-table-kill-row'."
9448 (interactive "P")
9449 (cond
9450 ((org-at-table-p) (org-table-kill-row))
9451 ((org-on-heading-p) (org-move-subtree-up arg))
9452 (t (org-shiftcursor-error))))
9453 (defun org-shiftmetadown (&optional arg)
9454 "Call `org-move-subtree-down' or `org-table-insert-row'."
9455 (interactive "P")
9456 (cond
9457 ((org-at-table-p) (org-table-insert-row arg))
9458 ((org-on-heading-p) (org-move-subtree-down arg))
9459 (t (org-shiftcursor-error))))
9460
9461 (defun org-metaleft (&optional arg)
9462 "Call `org-do-promote' or `org-table-move-column' to left."
9463 (interactive "P")
9464 (cond
9465 ((org-at-table-p) (org-table-move-column 'left))
9466 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9467 (t (backward-word (prefix-numeric-value arg)))))
9468
9469 (defun org-metaright (&optional arg)
9470 "Call `org-do-demote' or `org-table-move-column' to right."
9471 (interactive "P")
9472 (cond
9473 ((org-at-table-p) (org-table-move-column nil))
9474 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9475 (t (forward-word (prefix-numeric-value arg)))))
9476
9477 (defun org-metaup (&optional arg)
9478 "Call `org-move-subtree-up' or `org-table-move-row' up."
9479 (interactive "P")
9480 (cond
9481 ((org-at-table-p) (org-table-move-row 'up))
9482 ((org-on-heading-p) (org-move-subtree-up arg))
9483 (t (org-shiftcursor-error))))
9484
9485 (defun org-metadown (&optional arg)
9486 "Call `org-move-subtree-down' or `org-table-move-row' down."
9487 (interactive "P")
9488 (cond
9489 ((org-at-table-p) (org-table-move-row nil))
9490 ((org-on-heading-p) (org-move-subtree-down arg))
9491 (t (org-shiftcursor-error))))
9492
9493 (defun org-shiftup (&optional arg)
9494 "Call `org-timestamp-up' or `org-priority-up'."
9495 (interactive "P")
9496 (cond
9497 ((org-at-timestamp-p) (org-timestamp-up arg))
9498 (t (org-priority-up))))
9499
9500 (defun org-shiftdown (&optional arg)
9501 "Call `org-timestamp-down' or `org-priority-down'."
9502 (interactive "P")
9503 (cond
9504 ((org-at-timestamp-p) (org-timestamp-down arg))
9505 (t (org-priority-down))))
9506
9507 (defun org-copy-special ()
9508 "Call either `org-table-copy' or `org-copy-subtree'."
9509 (interactive)
9510 (call-interactively
9511 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9512
9513 (defun org-cut-special ()
9514 "Call either `org-table-copy' or `org-cut-subtree'."
9515 (interactive)
9516 (call-interactively
9517 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9518
9519 (defun org-paste-special (arg)
9520 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9521 (interactive "P")
9522 (if (org-at-table-p)
9523 (org-table-paste-rectangle)
9524 (org-paste-subtree arg)))
9525
9526 (defun org-ctrl-c-ctrl-c (&optional arg)
9527 "Call realign table, or recognize a table.el table, or update keywords.
9528 When the cursor is inside a table created by the table.el package,
9529 activate that table. Otherwise, if the cursor is at a normal table
9530 created with org.el, re-align that table. This command works even if
9531 the automatic table editor has been turned off.
9532 If the cursor is in one of the special #+KEYWORD lines, this triggers
9533 scanning the buffer for these lines and updating the information."
9534 (interactive "P")
9535 (let ((org-enable-table-editor t))
9536 (cond
9537 ((org-at-table.el-p)
9538 (require 'table)
9539 (beginning-of-line 1)
9540 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9541 (table-recognize-table))
9542 ((org-at-table-p)
9543 (org-table-maybe-eval-formula)
9544 (if arg
9545 (org-table-recalculate t)
9546 (org-table-maybe-recalculate-line))
9547 (org-table-align))
9548 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9549 (cond
9550 ((equal (match-string 1) "TBLFM")
9551 ;; Recalculate the table before this line
9552 (save-excursion
9553 (beginning-of-line 1)
9554 (skip-chars-backward " \r\n\t")
9555 (if (org-at-table-p) (org-table-recalculate t))))
9556 (t
9557 (let ((org-inhibit-startup t)) (org-mode)))))
9558 ((org-region-active-p)
9559 (org-table-convert-region (region-beginning) (region-end) arg))
9560 ((and (region-beginning) (region-end))
9561 (if (y-or-n-p "Convert inactive region to table? ")
9562 (org-table-convert-region (region-beginning) (region-end) arg)
9563 (error "Abort")))
9564 (t (error "No table at point, and no region to make one")))))
9565
9566 (defun org-return ()
9567 "Call `org-table-next-row' or `newline'."
9568 (interactive)
9569 (cond
9570 ((org-at-table-p)
9571 (org-table-justify-field-maybe)
9572 (org-table-next-row))
9573 (t (newline))))
9574
9575 (defun org-meta-return (&optional arg)
9576 "Call `org-insert-heading' or `org-table-wrap-region'."
9577 (interactive "P")
9578 (cond
9579 ((org-at-table-p)
9580 (org-table-wrap-region arg))
9581 (t (org-insert-heading))))
9582
9583 ;;; Menu entries
9584
9585 ;; Define the Org-mode menus
9586 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9587 '("Tbl"
9588 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9589 ["Next Field" org-cycle (org-at-table-p)]
9590 ["Previous Field" org-shifttab (org-at-table-p)]
9591 ["Next Row" org-return (org-at-table-p)]
9592 "--"
9593 ["Blank Field" org-table-blank-field (org-at-table-p)]
9594 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9595 "--"
9596 ("Column"
9597 ["Move Column Left" org-metaleft (org-at-table-p)]
9598 ["Move Column Right" org-metaright (org-at-table-p)]
9599 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9600 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9601 ("Row"
9602 ["Move Row Up" org-metaup (org-at-table-p)]
9603 ["Move Row Down" org-metadown (org-at-table-p)]
9604 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9605 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9606 "--"
9607 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9608 ("Rectangle"
9609 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9610 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9611 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9612 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9613 "--"
9614 ("Calculate"
9615 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
9616 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9617 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
9618 "--"
9619 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9620 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9621 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9622 "--"
9623 ["Sum Column/Rectangle" org-table-sum
9624 (or (org-at-table-p) (org-region-active-p))]
9625 ["Which Column?" org-table-current-column (org-at-table-p)])
9626 ["Debug Formulas"
9627 (setq org-table-formula-debug (not org-table-formula-debug))
9628 :style toggle :selected org-table-formula-debug]
9629 "--"
9630 ["Invisible Vlines" org-table-toggle-vline-visibility
9631 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9632 "--"
9633 ["Create" org-table-create (and (not (org-at-table-p))
9634 org-enable-table-editor)]
9635 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9636 ["Import from File" org-table-import (not (org-at-table-p))]
9637 ["Export to File" org-table-export (org-at-table-p)]
9638 "--"
9639 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9640
9641 (easy-menu-define org-org-menu org-mode-map "Org menu"
9642 '("Org"
9643 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9644 ["Sparse Tree" org-occur t]
9645 ["Show All" show-all t]
9646 "--"
9647 ["New Heading" org-insert-heading t]
9648 ("Navigate Headings"
9649 ["Up" outline-up-heading t]
9650 ["Next" outline-next-visible-heading t]
9651 ["Previous" outline-previous-visible-heading t]
9652 ["Next Same Level" outline-forward-same-level t]
9653 ["Previous Same Level" outline-backward-same-level t]
9654 "--"
9655 ["Jump" org-goto t])
9656 ("Edit Structure"
9657 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9658 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9659 "--"
9660 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9661 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9662 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9663 "--"
9664 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9665 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9666 ["Demote Heading" org-metaright (not (org-at-table-p))]
9667 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9668 "--"
9669 ["Archive Subtree" org-archive-subtree t])
9670 "--"
9671 ("TODO Lists"
9672 ["TODO/DONE/-" org-todo t]
9673 ["Show TODO Tree" org-show-todo-tree t]
9674 "--"
9675 ["Set Priority" org-priority t]
9676 ["Priority Up" org-shiftup t]
9677 ["Priority Down" org-shiftdown t])
9678 ("Dates and Scheduling"
9679 ["Timestamp" org-time-stamp t]
9680 ("Change Date"
9681 ["1 Day Later" org-timestamp-up-day t]
9682 ["1 Day Earlier" org-timestamp-down-day t]
9683 ["1 ... Later" org-shiftup t]
9684 ["1 ... Earlier" org-shiftdown t])
9685 ["Compute Time Range" org-evaluate-time-range t]
9686 ["Schedule Item" org-schedule t]
9687 ["Deadline" org-deadline t]
9688 "--"
9689 ["Goto Calendar" org-goto-calendar t]
9690 ["Date from Calendar" org-date-from-calendar t])
9691 "--"
9692 ("Timeline/Agenda"
9693 ["Show TODO Tree this File" org-show-todo-tree t]
9694 ["Check Deadlines this File" org-check-deadlines t]
9695 ["Timeline Current File" org-timeline t]
9696 "--"
9697 ["Agenda" org-agenda t])
9698 ("File List for Agenda")
9699 "--"
9700 ("Hyperlinks"
9701 ["Store Link (Global)" org-store-link t]
9702 ["Insert Link" org-insert-link t]
9703 ["Follow Link" org-open-at-point t])
9704 "--"
9705 ("Export"
9706 ["ASCII" org-export-as-ascii t]
9707 ["Extract Visible Text" org-export-copy-visible t]
9708 ["HTML" org-export-as-html t]
9709 ["HTML and Open" org-export-as-html-and-open t]
9710 ; ["OPML" org-export-as-opml nil]
9711 "--"
9712 ["Option Template" org-insert-export-options-template t]
9713 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9714 "--"
9715 ("Documentation"
9716 ["Show Version" org-version t]
9717 ["Info Documentation" org-info t])
9718 ("Customize"
9719 ["Browse Org Group" org-customize t]
9720 "--"
9721 ["Build Full Customize Menu" org-create-customize-menu
9722 (fboundp 'customize-menu-create)])
9723 ))
9724
9725 (defun org-info (&optional node)
9726 "Read documentation for Org-mode in the info system.
9727 With optional NODE, go directly to that node."
9728 (interactive)
9729 (require 'info)
9730 (Info-goto-node (format "(org)%s" (or node ""))))
9731
9732 (defun org-install-agenda-files-menu ()
9733 (easy-menu-change
9734 '("Org") "File List for Agenda"
9735 (append
9736 (list
9737 ["Edit File List" (customize-variable 'org-agenda-files) t]
9738 ["Add Current File to List" org-add-file t]
9739 ["Remove Current File from List" org-remove-file t]
9740 "--")
9741 (mapcar 'org-file-menu-entry org-agenda-files))))
9742
9743 ;;; Documentation
9744
9745 (defun org-customize ()
9746 "Call the customize function with org as argument."
9747 (interactive)
9748 (customize-browse 'org))
9749
9750 (defun org-create-customize-menu ()
9751 "Create a full customization menu for Org-mode, insert it into the menu."
9752 (interactive)
9753 (if (fboundp 'customize-menu-create)
9754 (progn
9755 (easy-menu-change
9756 '("Org") "Customize"
9757 `(["Browse Org group" org-customize t]
9758 "--"
9759 ,(customize-menu-create 'org)
9760 ["Set" Custom-set t]
9761 ["Save" Custom-save t]
9762 ["Reset to Current" Custom-reset-current t]
9763 ["Reset to Saved" Custom-reset-saved t]
9764 ["Reset to Standard Settings" Custom-reset-standard t]))
9765 (message "\"Org\"-menu now contains full customization menu"))
9766 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9767
9768 ;;; Miscellaneous stuff
9769
9770 (defun org-move-line-down (arg)
9771 "Move the current line down. With prefix argument, move it past ARG lines."
9772 (interactive "p")
9773 (let ((col (current-column))
9774 beg end pos)
9775 (beginning-of-line 1) (setq beg (point))
9776 (beginning-of-line 2) (setq end (point))
9777 (beginning-of-line (+ 1 arg))
9778 (setq pos (move-marker (make-marker) (point)))
9779 (insert (delete-and-extract-region beg end))
9780 (goto-char pos)
9781 (move-to-column col)))
9782
9783 (defun org-move-line-up (arg)
9784 "Move the current line up. With prefix argument, move it past ARG lines."
9785 (interactive "p")
9786 (let ((col (current-column))
9787 beg end pos)
9788 (beginning-of-line 1) (setq beg (point))
9789 (beginning-of-line 2) (setq end (point))
9790 (beginning-of-line (- arg))
9791 (setq pos (move-marker (make-marker) (point)))
9792 (insert (delete-and-extract-region beg end))
9793 (goto-char pos)
9794 (move-to-column col)))
9795
9796 ;; Functions needed for Emacs/XEmacs region compatibility
9797
9798 (defun org-region-active-p ()
9799 "Is `transient-mark-mode' on and the region active?
9800 Works on both Emacs and XEmacs."
9801 (if org-ignore-region
9802 nil
9803 (if org-xemacs-p
9804 (and zmacs-regions (region-active-p))
9805 (and transient-mark-mode mark-active))))
9806
9807 (defun org-add-to-invisibility-spec (arg)
9808 "Add elements to `buffer-invisibility-spec'.
9809 See documentation for `buffer-invisibility-spec' for the kind of elements
9810 that can be added."
9811 (cond
9812 ((fboundp 'add-to-invisibility-spec)
9813 (add-to-invisibility-spec arg))
9814 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9815 (setq buffer-invisibility-spec (list arg)))
9816 (t
9817 (setq buffer-invisibility-spec
9818 (cons arg buffer-invisibility-spec)))))
9819
9820 (defun org-remove-from-invisibility-spec (arg)
9821 "Remove elements from `buffer-invisibility-spec'."
9822 (if (fboundp 'remove-from-invisibility-spec)
9823 (remove-from-invisibility-spec arg)
9824 (if (consp buffer-invisibility-spec)
9825 (setq buffer-invisibility-spec
9826 (delete arg buffer-invisibility-spec)))))
9827
9828 (defun org-in-invisibility-spec-p (arg)
9829 "Is ARG a member of `buffer-invisibility-spec'?."
9830 (if (consp buffer-invisibility-spec)
9831 (member arg buffer-invisibility-spec)
9832 nil))
9833
9834 (defun org-image-file-name-regexp ()
9835 "Return regexp matching the file names of images."
9836 (if (fboundp 'image-file-name-regexp)
9837 (image-file-name-regexp)
9838 (let ((image-file-name-extensions
9839 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9840 "xbm" "xpm" "pbm" "pgm" "ppm")))
9841 (concat "\\."
9842 (regexp-opt (nconc (mapcar 'upcase
9843 image-file-name-extensions)
9844 image-file-name-extensions)
9845 t)
9846 "\\'"))))
9847
9848 ;; Functions needed for compatibility with old outline.el
9849
9850 ;; The following functions capture almost the entire compatibility code
9851 ;; between the different versions of outline-mode. The only other place
9852 ;; where this is important are the font-lock-keywords. Search for
9853 ;; `org-noutline-p' to find it.
9854
9855 ;; C-a should go to the beginning of a *visible* line, also in the
9856 ;; new outline.el. I guess this should be patched into Emacs?
9857 (defun org-beginning-of-line ()
9858 "Go to the beginning of the current line. If that is invisible, continue
9859 to a visible line beginning. This makes the function of C-a more intuitive."
9860 (interactive)
9861 (beginning-of-line 1)
9862 (if (bobp)
9863 nil
9864 (backward-char 1)
9865 (if (org-invisible-p)
9866 (while (and (not (bobp)) (org-invisible-p))
9867 (backward-char 1)
9868 (beginning-of-line 1))
9869 (forward-char 1))))
9870 (when org-noutline-p
9871 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9872
9873 (defun org-invisible-p ()
9874 "Check if point is at a character currently not visible."
9875 (if org-noutline-p
9876 ;; Early versions of noutline don't have `outline-invisible-p'.
9877 (if (fboundp 'outline-invisible-p)
9878 (outline-invisible-p)
9879 (get-char-property (point) 'invisible))
9880 (save-excursion
9881 (skip-chars-backward "^\r\n")
9882 (equal (char-before) ?\r))))
9883
9884 (defun org-back-to-heading (&optional invisible-ok)
9885 "Move to previous heading line, or beg of this line if it's a heading.
9886 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9887 (if org-noutline-p
9888 (outline-back-to-heading invisible-ok)
9889 (if (looking-at outline-regexp)
9890 t
9891 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9892 outline-regexp)
9893 nil t)
9894 (if invisible-ok
9895 (progn (goto-char (match-end 1))
9896 (looking-at outline-regexp)))
9897 (error "Before first heading")))))
9898
9899 (defun org-on-heading-p (&optional invisible-ok)
9900 "Return t if point is on a (visible) heading line.
9901 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9902 (if org-noutline-p
9903 (outline-on-heading-p 'invisible-ok)
9904 (save-excursion
9905 (skip-chars-backward "^\n\r")
9906 (and (looking-at outline-regexp)
9907 (or invisible-ok
9908 (bobp)
9909 (equal (char-before) ?\n))))))
9910
9911 (defun org-up-heading-all (arg)
9912 "Move to the heading line of which the present line is a subheading.
9913 This function considers both visible and invisible heading lines.
9914 With argument, move up ARG levels."
9915 (if org-noutline-p
9916 (if (fboundp 'outline-up-heading-all)
9917 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9918 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9919 (org-back-to-heading t)
9920 (looking-at outline-regexp)
9921 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9922 (error "Cannot move up %d levels" arg)
9923 (re-search-backward
9924 (concat "[\n\r]" (regexp-quote
9925 (make-string (- (match-end 0) (match-beginning 0) arg)
9926 ?*))
9927 "[^*]"))
9928 (forward-char 1))))
9929
9930 (defun org-show-hidden-entry ()
9931 "Show an entry where even the heading is hidden."
9932 (save-excursion
9933 (if (not org-noutline-p)
9934 (progn
9935 (org-back-to-heading t)
9936 (org-flag-heading nil)))
9937 (org-show-entry)))
9938
9939 (defun org-check-occur-regexp (regexp)
9940 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9941 Of course, only for the old outline mode."
9942 (if org-noutline-p
9943 regexp
9944 (if (string-match "^\\^" regexp)
9945 (concat "[\n\r]" (substring regexp 1))
9946 regexp)))
9947
9948 (defun org-flag-heading (flag &optional entry)
9949 "Flag the current heading. FLAG non-nil means make invisible.
9950 When ENTRY is non-nil, show the entire entry."
9951 (save-excursion
9952 (org-back-to-heading t)
9953 (if (not org-noutline-p)
9954 ;; Make the current headline visible
9955 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9956 ;; Check if we should show the entire entry
9957 (if entry
9958 (progn
9959 (org-show-entry)
9960 (save-excursion ;; FIXME: Is this the fix for points in the -|
9961 ;; middle of text? |
9962 (and (outline-next-heading) ;; |
9963 (org-flag-heading nil)))) ; show the next heading _|
9964 (outline-flag-region (max 1 (1- (point)))
9965 (save-excursion (outline-end-of-heading) (point))
9966 (if org-noutline-p
9967 flag
9968 (if flag ?\r ?\n))))))
9969
9970 (defun org-show-subtree ()
9971 "Show everything after this heading at deeper levels."
9972 (outline-flag-region
9973 (point)
9974 (save-excursion
9975 (outline-end-of-subtree) (outline-next-heading) (point))
9976 (if org-noutline-p nil ?\n)))
9977
9978 (defun org-show-entry ()
9979 "Show the body directly following this heading.
9980 Show the heading too, if it is currently invisible."
9981 (interactive)
9982 (save-excursion
9983 (org-back-to-heading t)
9984 (outline-flag-region
9985 (1- (point))
9986 (save-excursion
9987 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9988 (or (match-beginning 1) (point-max)))
9989 (if org-noutline-p nil ?\n))))
9990
9991
9992 (defun org-make-options-regexp (kwds)
9993 "Make a regular expression for keyword lines."
9994 (concat
9995 (if org-noutline-p "^" "[\n\r]")
9996 "#?[ \t]*\\+\\("
9997 (mapconcat 'regexp-quote kwds "\\|")
9998 "\\):[ \t]*"
9999 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10000
10001 ;; Advise the bookmark-jump function to make jump position visible
10002 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
10003 (eval-after-load "bookmark"
10004 '(defadvice bookmark-jump (after org-make-visible activate)
10005 "Make the position visible."
10006 (and (eq major-mode 'org-mode)
10007 (org-invisible-p)
10008 (org-show-hierarchy-above))))
10009
10010 ;;; Finish up
10011
10012 (provide 'org)
10013
10014 (run-hooks 'org-load-hook)
10015
10016 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10017 ;;; org.el ends here