]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Update FSF's address.
[gnu-emacs] / lisp / textmodes / org.el
1 ;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005 Free Software Foundation
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 3.13
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke.
80 ;;
81 ;; Changes:
82 ;; -------
83 ;; Version 3.13
84 ;; - Efficiency improvements: Fewer table re-alignments needed.
85 ;; - New special lines in tables, for defining names for individual cells.
86 ;;
87 ;; Version 3.12
88 ;; - Tables can store formulas (one per column) and compute fields.
89 ;; Not quite like a full spreadsheet, but very powerful.
90 ;; - table.el keybinding is now `C-c ~'.
91 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
92 ;; - Small changes to keys in agenda buffer. Affected keys:
93 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
94 ;; - Bug fixes.
95 ;;
96 ;; Version 3.11
97 ;; - Links inserted with C-c C-l are now by default enclosed in angle
98 ;; brackets. See the new variable `org-link-format'.
99 ;; - ">" terminates a link, this is a way to have several links in a line.
100 ;; Both "<" and ">" are no longer allowed as characters in a link.
101 ;; - Archiving of finished tasks.
102 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
103 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
104 ;; - Compatibility problems with viper-mode fixed.
105 ;; - Improved html export of tables.
106 ;; - Various clean-up changes.
107 ;;
108 ;; Version 3.10
109 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
110 ;;
111 ;; Version 3.09
112 ;; - Time-of-day specifications in agenda are extracted and placed
113 ;; into the prefix. Timed entries can be placed into a time grid for
114 ;; day.
115 ;;
116 ;; Version 3.08
117 ;; - "|" no longer allowed as part of a link, to allow links in tables.
118 ;; - The prefix of items in the agenda buffer can be configured.
119 ;; - Cleanup.
120 ;;
121 ;; Version 3.07
122 ;; - Some folding incinsistencies removed.
123 ;; - BBDB links to company-only entries.
124 ;; - Bug fixes and global cleanup.
125 ;;
126 ;; Version 3.06
127 ;; - M-S-RET inserts a new TODO heading.
128 ;; - New startup option `content'.
129 ;; - Better visual response when TODO items in agenda change status.
130 ;; - Window positioning after visibility state changes optimized and made
131 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
132 ;;
133 ;; Version 3.05
134 ;; - Agenda entries from the diary are linked to the diary file, so
135 ;; adding and editing diary entries can be done directly from the agenda.
136 ;; - Many calendar/diary commands available directly from agenda.
137 ;; - Field copying in tables with S-RET does increment.
138 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
139 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
140 ;;
141 ;; Version 3.04
142 ;; - Table editor optimized to need fewer realignments, and to keep
143 ;; table shape when typing in fields.
144 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
145 ;; into arbitrary major modes.
146 ;; - Fixed bug with realignment in XEmacs.
147 ;; - Startup options can be set with special #+STARTUP line.
148 ;; - Heading following a match in org-occur can be suppressed.
149 ;;
150 ;; Version 3.03
151 ;; - Copyright transfer to the FSF.
152 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
153 ;; - Timeline now always contains today, and `.' jumps to it.
154 ;; - Table editor:
155 ;; - cut and paste of rectangular regions in tables
156 ;; - command to convert org-mode table to table.el table and back
157 ;; - command to treat several cells like a paragraph and fill it
158 ;; - command to convert a buffer region to a table
159 ;; - import/export tables as tab-separated files (exchange with Excel)
160 ;; - Agenda:
161 ;; - Sorting mechanism for agenda items rewritten from scratch.
162 ;; - Sorting fully configurable.
163 ;; - Entries specifying a time are sorted together.
164 ;; - Completion also covers option keywords after `#-'.
165 ;; - Bug fixes.
166 ;;
167 ;; Version 3.01
168 ;; - New reference card, thanks to Philip Rooke for creating it.
169 ;; - Single file agenda renamed to "Timeline". It no longer shows
170 ;; warnings about upcoming deadlines/overdue scheduled items.
171 ;; That functionality is now limited to the (multifile) agenda.
172 ;; - When reading a date, the calendar can be manipulated with keys.
173 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
174 ;; - Minor bug fixes and documentation improvements.
175
176 ;;; Code:
177
178 (eval-when-compile (require 'cl) (require 'calendar))
179 (require 'outline)
180 (require 'time-date)
181 (require 'easymenu)
182
183 ;;; Customization variables
184
185 (defvar org-version "3.13"
186 "The version number of the file org.el.")
187 (defun org-version ()
188 (interactive)
189 (message "Org-mode version %s" org-version))
190
191 ;; The following two constants are for compatibility with different Emacs
192 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
193 ;; The compatibility code in org.el is based on these two constants.
194 (defconst org-xemacs-p (featurep 'xemacs)
195 "Are we running xemacs?")
196 (defconst org-noutline-p (featurep 'noutline)
197 "Are we using the new outline mode?")
198
199 (defgroup org nil
200 "Outline-based notes management and organizer "
201 :tag "Org"
202 :group 'outlines
203 :group 'hypermedia
204 :group 'calendar)
205
206 (defgroup org-startup nil
207 "Options concerning startup of Org-mode."
208 :tag "Org Startup"
209 :group 'org)
210
211 (defcustom org-CUA-compatible nil
212 "Non-nil means use alternative key bindings for S-<cursor movement>.
213 Org-mode used S-<cursor movement> for changing timestamps and priorities.
214 S-<cursor movement> is also used for example by `CUA-mode' to select text.
215 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
216 alternative bindings. Setting this variable to t will replace the following
217 keys both in Org-mode and in the Org-agenda buffer.
218
219 S-RET -> C-S-RET
220 S-up -> M-p
221 S-down -> M-n
222 S-left -> M--
223 S-right -> M-+
224
225 If you do not like the alternative keys, take a look at the variable
226 `org-disputed-keys'.
227
228 This option is only relevant at load-time of Org-mode. Changing it requires
229 a restart of Emacs to become effective."
230 :group 'org-startup
231 :type 'boolean)
232
233 (defvar org-disputed-keys
234 '((S-up [(shift up)] [(meta ?p)])
235 (S-down [(shift down)] [(meta ?n)])
236 (S-left [(shift left)] [(meta ?-)])
237 (S-right [(shift right)] [(meta ?+)])
238 (S-return [(shift return)] [(control shift return)]))
239 "Keys for which Org-mode and other modes compete.
240 This is an alist, cars are symbols for lookup, 1st element is the default key,
241 second element will be used when `org-CUA-compatible' is t.")
242
243 (defun org-key (key)
244 "Select a key according to `org-CUA-compatible'."
245 (nth (if org-CUA-compatible 2 1)
246 (or (assq key org-disputed-keys)
247 (error "Invalid Key %s in `org-key'" key))))
248
249 (defcustom org-startup-folded t
250 "Non-nil means, entering Org-mode will switch to OVERVIEW.
251 This can also be configured on a per-file basis by adding one of
252 the following lines anywhere in the buffer:
253
254 #+STARTUP: fold
255 #+STARTUP: nofold
256 #+STARTUP: content"
257 :group 'org-startup
258 :type '(choice
259 (const :tag "nofold: show all" nil)
260 (const :tag "fold: overview" t)
261 (const :tag "content: all headlines" content)))
262
263 (defcustom org-startup-truncated t
264 "Non-nil means, entering Org-mode will set `truncate-lines'.
265 This is useful since some lines containing links can be very long and
266 uninteresting. Also tables look terrible when wrapped."
267 :group 'org-startup
268 :type 'boolean)
269
270 (defcustom org-startup-with-deadline-check nil
271 "Non-nil means, entering Org-mode will run the deadline check.
272 This means, if you start editing an org file, you will get an
273 immediate reminder of any due deadlines.
274 This can also be configured on a per-file basis by adding one of
275 the following lines anywhere in the buffer:
276
277 #+STARTUP: dlcheck
278 #+STARTUP: nodlcheck"
279 :group 'org-startup
280 :type 'boolean)
281
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
291
292 (defgroup org-keywords nil
293 "Options concerning TODO items in Org-mode."
294 :tag "Org Keywords"
295 :group 'org)
296
297 (defcustom org-todo-keywords '("TODO" "DONE")
298 "List of TODO entry keywords.
299 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
300 considered to mean that the entry is \"done\". All the other mean that
301 action is required, and will make the entry show up in todo lists, diaries
302 etc.
303 The command \\[org-todo] cycles an entry through these states, and an
304 additional state where no keyword is present. For details about this
305 cycling, see also the variable `org-todo-interpretation'
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type '(repeat (string :tag "Keyword")))
309
310 (defcustom org-todo-interpretation 'sequence
311 "Controls how TODO keywords are interpreted.
312 \\<org-mode-map>Possible values are `sequence' and `type'.
313 This variable is only relevant if `org-todo-keywords' contains more than two
314 states. There are two ways how these keywords can be used:
315
316 - As a sequence in the process of working on a TODO item, for example
317 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
318 org-todo-interpretation 'sequence)
319
320 - As different types of TODO items, for example
321 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
322 org-todo-interpretation 'type)
323
324 When the states are interpreted as a sequence, \\[org-todo] always cycles
325 to the next state, in order to walk through all different states. So with
326 \\[org-todo], you turn an empty entry into the state TODO. When you started
327 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
328 later to VERIFY and finally to DONE.
329
330 When the states are interpreted as types, \\[org-todo] still cycles through
331 when it is called several times in direct succession, in order to initially
332 select the type. However, if not called immediately after a previous
333 \\[org-todo], it switches from each type directly to DONE. So with the
334 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
335 RELAXED. If you later return to this entry and press \\[org-todo] again,
336 RELAXED will not be changed REMIND, but directly to DONE.
337
338 You can create a large number of types. To initially select a
339 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
340 type with completion. Of course, you can also type the keyword
341 directly into the buffer. M-TAB completes TODO keywords at the
342 beginning of a headline."
343 :group 'org-keywords
344 :type '(choice (const sequence)
345 (const type)))
346
347 (defcustom org-default-priority ?B
348 "The default priority of TODO items.
349 This is the priority an item get if no explicit priority is given."
350 :group 'org-keywords
351 :type 'character)
352
353 (defcustom org-lowest-priority ?C
354 "The lowest priority of TODO items. A character like ?A, ?B etc."
355 :group 'org-keywords
356 :type 'character)
357
358 (defcustom org-deadline-string "DEADLINE:"
359 "String to mark deadline entries.
360 A deadline is this string, followed by a time stamp. Should be a word,
361 terminated by a colon. You can insert a schedule keyword and
362 a timestamp with \\[org-deadline].
363 Changes become only effective after restarting Emacs."
364 :group 'org-keywords
365 :type 'string)
366
367 (defcustom org-scheduled-string "SCHEDULED:"
368 "String to mark scheduled TODO entries.
369 A schedule is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-schedule].
372 Changes become only effective after restarting Emacs."
373 :group 'org-keywords
374 :type 'string)
375
376 (defcustom org-comment-string "COMMENT"
377 "Entries starting with this keyword will never be exported.
378 An entry can be toggled between COMMENT and normal with
379 \\[org-toggle-comment].
380 Changes become only effective after restarting Emacs."
381 :group 'org-keywords
382 :type 'string)
383
384 (defcustom org-after-todo-state-change-hook nil
385 "Hook which is run after the state of a TODO item was changed.
386 The new state (a string with a todo keyword, or nil) is available in the
387 Lisp variable `state'."
388 :group 'org-keywords
389 :type 'hook)
390
391 ;; Variables for pre-computed regular expressions, all buffer local
392 (defvar org-todo-kwd-priority-p nil
393 "Do TODO items have priorities?")
394 (make-variable-buffer-local 'org-todo-kwd-priority-p)
395 (defvar org-todo-kwd-max-priority nil
396 "Maximum priority of TODO items.")
397 (make-variable-buffer-local 'org-todo-kwd-max-priority)
398 (defvar org-ds-keyword-length 12
399 "Maximum length of the Deadline and SCHEDULED keywords.")
400 (make-variable-buffer-local 'org-ds-keyword-length)
401 (defvar org-done-string nil
402 "The last string in `org-todo-keywords', indicating an item is DONE.")
403 (make-variable-buffer-local 'org-done-string)
404 (defvar org-todo-regexp nil
405 "Matches any of the TODO state keywords.")
406 (make-variable-buffer-local 'org-todo-regexp)
407 (defvar org-not-done-regexp nil
408 "Matches any of the TODO state keywords except the last one.")
409 (make-variable-buffer-local 'org-not-done-regexp)
410 (defvar org-todo-line-regexp nil
411 "Matches a headline and puts TODO state into group 2 if present.")
412 (make-variable-buffer-local 'org-todo-line-regexp)
413 (defvar org-nl-done-regexp nil
414 "Matches newline followed by a headline with the DONE keyword.")
415 (make-variable-buffer-local 'org-nl-done-regexp)
416 (defvar org-looking-at-done-regexp nil
417 "Matches the DONE keyword a point.")
418 (make-variable-buffer-local 'org-looking-at-done-regexp)
419 (defvar org-deadline-regexp nil
420 "Matches the DEADLINE keyword.")
421 (make-variable-buffer-local 'org-deadline-regexp)
422 (defvar org-deadline-time-regexp nil
423 "Matches the DEADLINE keyword together with a time stamp.")
424 (make-variable-buffer-local 'org-deadline-time-regexp)
425 (defvar org-deadline-line-regexp nil
426 "Matches the DEADLINE keyword and the rest of the line.")
427 (make-variable-buffer-local 'org-deadline-line-regexp)
428 (defvar org-scheduled-regexp nil
429 "Matches the SCHEDULED keyword.")
430 (make-variable-buffer-local 'org-scheduled-regexp)
431 (defvar org-scheduled-time-regexp nil
432 "Matches the SCHEDULED keyword together with a time stamp.")
433 (make-variable-buffer-local 'org-scheduled-time-regexp)
434
435 (defvar org-category nil
436 "Variable used by org files to set a category for agenda display.
437 Such files should use a file variable to set it, for example
438
439 -*- mode: org; org-category: \"ELisp\"
440
441 or contain a special line
442
443 #+CATEGORY: ELisp
444
445 If the file does not specify a category, then file's base name
446 is used instead.")
447
448 (defun org-set-regexps-and-options ()
449 "Precompute regular expressions for current buffer."
450 (when (eq major-mode 'org-mode)
451 (let ((re (org-make-options-regexp
452 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
453 "STARTUP" "ARCHIVE")))
454 (splitre "[ \t]+")
455 kwds int key value cat arch)
456 (save-excursion
457 (save-restriction
458 (widen)
459 (goto-char (point-min))
460 (while (re-search-forward re nil t)
461 (setq key (match-string 1) value (match-string 2))
462 (cond
463 ((equal key "CATEGORY")
464 (if (string-match "[ \t]+$" value)
465 (setq value (replace-match "" t t value)))
466 (setq cat (intern value)))
467 ((equal key "SEQ_TODO")
468 (setq int 'sequence
469 kwds (append kwds (org-split-string value splitre))))
470 ((equal key "PRI_TODO")
471 (setq int 'priority
472 kwds (append kwds (org-split-string value splitre))))
473 ((equal key "TYP_TODO")
474 (setq int 'type
475 kwds (append kwds (org-split-string value splitre))))
476 ((equal key "STARTUP")
477 (let ((opts (org-split-string value splitre))
478 (set '(("fold" org-startup-folded t)
479 ("nofold" org-startup-folded nil)
480 ("content" org-startup-folded content)
481 ("dlcheck" org-startup-with-deadline-check t)
482 ("nodlcheck" org-startup-with-deadline-check nil)))
483 l var val)
484 (while (setq l (assoc (pop opts) set))
485 (setq var (nth 1 l) val (nth 2 l))
486 (set (make-local-variable var) val))))
487 ((equal key "ARCHIVE")
488 (string-match " *$" value)
489 (setq arch (replace-match "" t t value))
490 (remove-text-properties 0 (length arch)
491 '(face t fontified t) arch)))
492 )))
493 (and cat (set (make-local-variable 'org-category) cat))
494 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
495 (and arch (set (make-local-variable 'org-archive-location) arch))
496 (and int (set (make-local-variable 'org-todo-interpretation) int)))
497 ;; Compute the regular expressions and other local variables
498 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
499 org-todo-kwd-max-priority (1- (length org-todo-keywords))
500 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
501 (length org-scheduled-string)))
502 org-done-string
503 (nth (1- (length org-todo-keywords)) org-todo-keywords)
504 org-todo-regexp
505 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
506 "\\|") "\\)\\>")
507 org-not-done-regexp
508 (concat "\\<\\("
509 (mapconcat 'regexp-quote
510 (nreverse (cdr (reverse org-todo-keywords)))
511 "\\|")
512 "\\)\\>")
513 org-todo-line-regexp
514 (concat "^\\(\\*+\\)[ \t]*\\("
515 (mapconcat 'regexp-quote org-todo-keywords "\\|")
516 "\\)? *\\(.*\\)")
517 org-nl-done-regexp
518 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
519 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
520 org-deadline-regexp (concat "\\<" org-deadline-string)
521 org-deadline-time-regexp
522 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
523 org-deadline-line-regexp
524 (concat "\\<\\(" org-deadline-string "\\).*")
525 org-scheduled-regexp
526 (concat "\\<" org-scheduled-string)
527 org-scheduled-time-regexp
528 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
529 (org-set-font-lock-defaults)))
530
531 (defgroup org-time nil
532 "Options concerning time stamps and deadlines in Org-mode."
533 :tag "Org Time"
534 :group 'org)
535
536 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
537 "Formats for `format-time-string' which are used for time stamps.
538 It is not recommended to change this constant.")
539
540
541 (defcustom org-deadline-warning-days 30
542 "No. of days before expiration during which a deadline becomes active.
543 This variable governs the display in the org file."
544 :group 'org-time
545 :type 'number)
546
547 (defcustom org-popup-calendar-for-date-prompt t
548 "Non-nil means, pop up a calendar when prompting for a date.
549 In the calendar, the date can be selected with mouse-1. However, the
550 minibuffer will also be active, and you can simply enter the date as well.
551 When nil, only the minibuffer will be available."
552 :group 'org-time
553 :type 'number)
554
555 (defcustom org-calendar-follow-timestamp-change t
556 "Non-nil means, make the calendar window follow timestamp changes.
557 When a timestamp is modified and the calendar window is visible, it will be
558 moved to the new date."
559 :group 'org-time
560 :type 'boolean)
561
562 (defgroup org-agenda nil
563 "Options concerning agenda display Org-mode."
564 :tag "Org Agenda"
565 :group 'org)
566
567 (defcustom org-agenda-files nil
568 "A list of org files for agenda/diary display.
569 Entries are added to this list with \\[org-add-file] and removed with
570 \\[org-remove-file]. You can also use customize to edit the list."
571 :group 'org-agenda
572 :type '(repeat file))
573
574 (defcustom org-select-timeline-window t
575 "Non-nil means, after creating a timeline, move cursor into Timeline window.
576 When nil, cursor will remain in the current window."
577 :group 'org-agenda
578 :type 'boolean)
579
580 (defcustom org-select-agenda-window t
581 "Non-nil means, after creating an agenda, move cursor into Agenda window.
582 When nil, cursor will remain in the current window."
583 :group 'org-agenda
584 :type 'boolean)
585
586 (defcustom org-fit-agenda-window t
587 "Non-nil means, change window size of agenda to fit content."
588 :group 'org-agenda
589 :type 'boolean)
590
591 (defcustom org-agenda-show-all-dates t
592 "Non-nil means, `org-agenda' shows every day in the selected range.
593 When nil, only the days which actually have entries are shown."
594 :group 'org-agenda
595 :type 'boolean)
596
597 ;; FIXME: First day of month works only for current month because it would
598 ;; require a variable ndays treatment.
599 (defcustom org-agenda-start-on-weekday 1
600 "Non-nil means, start the overview always on the specified weekday.
601 0 Denotes Sunday, 1 denotes Monday etc.
602 When nil, always start on the current day."
603 :group 'org-agenda
604 :type '(choice (const :tag "Today" nil)
605 (const :tag "First day of month" t)
606 (number :tag "Weekday No.")))
607
608 (defcustom org-agenda-ndays 7
609 "Number of days to include in overview display."
610 :group 'org-agenda
611 :type 'number)
612
613 (defcustom org-agenda-include-all-todo t
614 "Non-nil means, the agenda will always contain all TODO entries.
615 When nil, date-less entries will only be shown if `org-agenda' is called
616 with a prefix argument.
617 When non-nil, the TODO entries will be listed at the top of the agenda, before
618 the entries for specific days."
619 :group 'org-agenda
620 :type 'boolean)
621
622 (defcustom org-agenda-include-diary nil
623 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
624 :group 'org-agenda
625 :type 'boolean)
626
627 (defcustom org-calendar-to-agenda-key [?c]
628 "The key to be installed in `calendar-mode-map' for switching to the agenda.
629 The command `org-calendar-goto-agenda' will be bound to this key. The
630 default is the character `c' because then`c' can be used to switch back and
631 force between agenda and calendar."
632 :group 'org-agenda
633 :type 'sexp)
634
635 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
636 "Sorting structure for the agenda items of a single day.
637 This is a list of symbols which will be used in sequence to determine
638 if an entry should be listed before another entry. The following
639 symbols are recognized.
640
641 time-up Put entries with time-of-day indications first, early first
642 time-down Put entries with time-of-day indications first, late first
643 category-keep Keep the default order of categories, corresponding to the
644 sequence in `org-agenda-files'.
645 category-up Sort alphabetically by category, A-Z.
646 category-down Sort alphabetically by category, Z-A.
647 priority-up Sort numerically by priority, high priority last.
648 priority-down Sort numerically by priority, high priority first.
649
650 The different possibilities will be tried in sequence, and testing stops
651 if one comparison returns a \"not-equal\". For example, the default
652 '(time-up category-keep priority-down)
653 means: Pull out all entries having a specified time of day and sort them,
654 in order to make a time schedule for the current day the first thing in the
655 agenda listing for the day. Of the entries without a time indication, keep
656 the grouped in categories, don't sort the categories, but keep them in
657 the sequence given in `org-agenda-files'. Within each category sort by
658 priority.
659
660 Leaving out `category-keep' would mean that items will be sorted across
661 categories by priority."
662 :group 'org-agenda
663 :type '(repeat
664 (choice
665 (const time-up)
666 (const time-down)
667 (const category-keep)
668 (const category-up)
669 (const category-down)
670 (const priority-up)
671 (const priority-down))))
672
673 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
674 "Format specification for the prefix of items in the agenda buffer.
675 This format works similar to a printf format, with the following meaning:
676
677 %c the category of the item, \"Diary\" for entries from the diary, or
678 as given by the CATEGORY keyword or derived from the file name.
679 %t the time-of-day specification if one applies to the entry, in the
680 format HH:MM
681 %s Scheduling/Deadline information, a short string
682
683 All specifiers work basically like the standard `%s' of printf, but may
684 contain two additional characters: A question mark just after the `%' and
685 a whitespace/punctuation character just before the final letter.
686
687 If the first character after `%' is a question mark, the entire field
688 will only be included if the corresponding value applies to the
689 current entry. This is useful for fields which should have fixed
690 width when present, but zero width when absent. For example,
691 \"%?-12t\" will result in a 12 character time field if a time of the
692 day is specified, but will completely disappear in entries which do
693 not contain a time.
694
695 If there is punctuation or whitespace character just before the final
696 format letter, this character will be appended to the field value if
697 the value is not empty. For example, the format \"%-12:c\" leads to
698 \"Diary: \" if the category is \"Diary\". If the category were be
699 empty, no additional colon would be interted.
700
701 The default value of this option is \" %-12:c%?-12t% s\", meaning:
702 - Indent the line with two space characters
703 - Give the category in a 12 chars wide field, padded with whitespace on
704 the right (because of `-'). Append a colon if there is a category
705 (because of `:').
706 - If there is a time-of-day, put it into a 12 chars wide field. If no
707 time, don't put in an empty field, just skip it (because of '?').
708 - Finally, put the scheduling information and append a whitespace.
709
710 As another example, if you don't want the time-of-day of entries in
711 the prefix, you could use:
712
713 (setq org-agenda-prefix-format \" %-11:c% s\")
714
715 See also the variable `org-agenda-remove-times-when-in-prefix'."
716 :type 'string
717 :group 'org-agenda)
718
719 (defcustom org-timeline-prefix-format " % s"
720 "Like `org-agenda-prefix-format', but for the timeline of a single file."
721 :type 'string
722 :group 'org-agenda)
723
724 (defvar org-prefix-format-compiled nil
725 "The compiled version of the most recently used prefix format.
726 Depending on which command was used last, this may be the compiled version
727 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
728
729 (defcustom org-agenda-use-time-grid t
730 "Non-nil means, show a time grid in the agenda schedule.
731 A time grid is a set of lines for specific times (like every two hours between
732 8:00 and 20:00. The items scheduled for a day at specific times are
733 sorted in between these lines.
734 For deails about when the grid will be shown, and what it will look like, see
735 the variable `org-agenda-time-grid'."
736 :group 'org-agenda
737 :type 'boolean)
738
739 (defcustom org-agenda-time-grid
740 '((daily today require-timed)
741 "----------------"
742 (800 1000 1200 1400 1600 1800 2000))
743
744 "The settings for time grid for agenda display.
745 This is a list of three items. The first item is again a list. It contains
746 symbols specifying conditions when the grid should be displayed:
747
748 daily if the agenda shows a single day
749 weekly if the agenda shows an entire week
750 today show grid on current date, independent of daily/weekly display
751 require-timed show grid only if at least on item has a time specification
752
753 The second item is a string which will be places behing the grid time.
754
755 The third item is a list of integers, indicating the times that should have
756 a grid line."
757 :group 'org-agenda
758 :type
759 '(list
760 (set :greedy t :tag "Grid Display Options"
761 (const :tag "Show grid in single day agenda display" daily)
762 (const :tag "Show grid in weekly agenda display" weekly)
763 (const :tag "Always show grid for today" today)
764 (const :tag "Show grid only if any timed entries are present"
765 require-timed)
766 (const :tag "Skip grid times already present in an entry"
767 remove-match))
768 (string :tag "Grid String")
769 (repeat :tag "Grid Times" (integer :tag "Time"))))
770
771 (defcustom org-agenda-remove-times-when-in-prefix t
772 "Non-nil means, remove duplicate time specifications in agenda items.
773 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
774 time-of-day specification in a headline or diary entry is extracted and
775 placed into the prefix. If this option is non-nil, the original specification
776 \(a timestamp or -range, or just a plain time(range) specification like
777 11:30-4pm) will be removed for agenda display. This makes the agenda less
778 cluttered.
779 The option can be t or nil. It may also be the symbol `beg', indicating
780 that the time should only be removed what it is located at the beginning of
781 the headline/diary entry."
782 :group 'org-agenda
783 :type '(choice
784 (const :tag "Always" t)
785 (const :tag "Never" nil)
786 (const :tag "When at beginning of entry" beg)))
787
788 (defcustom org-sort-agenda-notime-is-late t
789 "Non-nil means, items without time are considered late.
790 This is only relevant for sorting. When t, items which have no explicit
791 time like 15:30 will be considered as 24:01, i.e. later than any items which
792 do have a time. When nil, the default time is before 0:00. You can use this
793 option to decide if the schedule for today should come before or after timeless
794 agenda entries."
795 :group 'org-agenda
796 :type 'boolean)
797
798 (defgroup org-structure nil
799 "Options concerning structure editing in Org-mode."
800 :tag "Org Structure"
801 :group 'org)
802
803 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
804 "Hook that is run after `org-cycle' has changed the buffer visibility.
805 The function(s) in this hook must accept a single argument which indicates
806 the new state that was set by the most recent `org-cycle' command. The
807 argument is a symbol. After a global state change, it can have the values
808 `overview', `content', or `all'. After a local state change, it can have
809 the values `folded', `children', or `subtree'."
810 :group 'org-structure
811 :type 'hook)
812
813 (defcustom org-occur-hook '(org-first-headline-recenter)
814 "Hook that is run after `org-occur' has constructed a sparse tree.
815 This can be used to recenter the window to show as much of the structure
816 as possible."
817 :group 'org-structure
818 :type 'hook)
819
820 (defcustom org-adapt-indentation t
821 "Non-nil means, adapt indentation when promoting and demoting.
822 When this is set and the *entire* text in an entry is indented, the
823 indentation is increased by one space in a demotion command, and
824 decreased by one in a promotion command. If any line in the entry
825 body starts at column 0, indentation is not changed at all."
826 :group 'org-structure
827 :type 'boolean)
828
829 (defcustom org-cycle-emulate-tab t
830 "Where should `org-cycle' emulate TAB.
831 nil Never
832 white Only in completely white lines
833 t Everywhere except in headlines"
834 :group 'org-structure
835 :type '(choice (const :tag "Never" nil)
836 (const :tag "Only in completely white lines" white)
837 (const :tag "Everywhere except in headlines" t)
838 ))
839
840 (defcustom org-show-following-heading t
841 "Non-nil means, show heading following match in `org-occur'.
842 When doing an `org-occur' it is useful to show the headline which
843 follows the match, even if they do not match the regexp. This makes it
844 easier to edit directly inside the sparse tree. However, if you use
845 org-occur mainly as an overview, the following headlines are
846 unnecessary clutter."
847 :group 'org-structure
848 :type 'boolean)
849
850 (defcustom org-archive-location "%s_archive::"
851 "The location where subtrees should be archived.
852 This string consists of two parts, separated by a double-colon.
853
854 The first part is a file name - when omitted, archiving happens in the same
855 file. %s will be replaced by the current file name (without directory part).
856 Archiving to a different file is useful to keep archived entries from
857 contributing to the Org-mode Agenda.
858
859 The part after the double colon is a headline. The archived entries will be
860 filed under that headline. When omitted, the subtrees are simply filed away
861 at the end of the file, as top-level entries.
862
863 Here are a few examples:
864 \"%s_archive::\"
865 If the current file is Projects.org, archive in file
866 Projects.org_archive, as top-level trees. This is the default.
867
868 \"::* Archived Tasks\"
869 Archive in the current file, under the top-level headline
870 \"* Archived Tasks\".
871
872 \"~/org/archive.org::\"
873 Archive in file ~/org/archive.org (absolute path), as top-level trees.
874
875 \"basement::** Finished Tasks\"
876 Archive in file ./basement (relative path), as level 3 trees
877 below the level 2 heading \"** Finished Tasks\".
878
879 You may set this option on a per-file basis by adding to the buffer a
880 line like
881
882 #+ARCHIVE: basement::** Finished Tasks"
883 :group 'org-structure
884 :type 'string)
885
886 (defcustom org-archive-mark-done t
887 "Non-nil means, mark archived entries as DONE."
888 :group 'org-structure
889 :type 'boolean)
890
891 (defcustom org-archive-stamp-time t
892 "Non-nil means, add a time stamp to archived entries.
893 The time stamp will be added directly after the TODO state keyword in the
894 first line, so it is probably best to use this in combinations with
895 `org-archive-mark-done'."
896 :group 'org-structure
897 :type 'boolean)
898
899 (defgroup org-link nil
900 "Options concerning links in Org-mode."
901 :tag "Org Link"
902 :group 'org)
903
904 (defcustom org-link-format "<%s>"
905 "Default format for linkes in the buffer.
906 This is a format string for printf, %s will be replaced by the link text.
907 If you want to make sure that your link is always properly terminated,
908 include angle brackets into this format, like \"<%s>\". Some people also
909 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
910 :group 'org-link
911 :type '(choice
912 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
913 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
914 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
915 (string :tag "Other" :value "<%s>")))
916
917 (defcustom org-allow-space-in-links t
918 "Non-nil means, file names in links may contain space characters.
919 When nil, it becomes possible to put several links into a line.
920 Note that in tables, a link never extends accross fields, so in a table
921 it is always possible to put several links into a line.
922 Changing this varable requires a re-launch of Emacs of become effective."
923 :group 'org-link
924 :type 'boolean)
925
926 (defcustom org-line-numbers-in-file-links t
927 "Non-nil means, file links from `org-store-link' contain line numbers.
928 The line number will be added to the file name with :NNN and interpreted
929 by the command `org-open-at-point'.
930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
931 negates this setting for the duration of the command."
932 :group 'org-link
933 :type 'boolean)
934
935 (defcustom org-keep-stored-link-after-insertion nil
936 "Non-nil means, keep link in list for entire session.
937
938 The command `org-store-link' adds a link pointing to the current
939 location to an internal list. These links accumulate during a session.
940 The command `org-insert-link' can be used to insert links into any
941 Org-mode file (offering completion for all stored links). When this
942 option is nil, every link which has been inserted once using \\[org-insert-link]
943 will be removed from the list, to make completing the unused links
944 more efficient."
945 :group 'org-link
946 :type 'boolean)
947
948 (defcustom org-link-frame-setup
949 '((vm . vm-visit-folder-other-frame)
950 (gnus . gnus-other-frame)
951 (file . find-file-other-window))
952 "Setup the frame configuration for following links.
953 When following a link with Emacs, it may often be useful to display
954 this link in another window or frame. This variable can be used to
955 set this up for the different types of links.
956 For VM, use any of
957 `vm-visit-folder'
958 `vm-visit-folder-other-frame'
959 For Gnus, use any of
960 `gnus'
961 `gnus-other-frame'
962 For FILE, use any of
963 `find-file'
964 `find-file-other-window'
965 `find-file-other-frame'
966 For the calendar, use the variable `calendar-setup'.
967 For BBDB, it is currently only possible to display the matches in
968 another window."
969 :group 'org-link
970 :type '(list
971 (cons (const vm)
972 (choice
973 (const vm-visit-folder)
974 (const vm-visit-folder-other-window)
975 (const vm-visit-folder-other-frame)))
976 (cons (const gnus)
977 (choice
978 (const gnus)
979 (const gnus-other-frame)))
980 (cons (const file)
981 (choice
982 (const find-file)
983 (const find-file-other-window)
984 (const find-file-other-frame)))))
985
986 (defcustom org-usenet-links-prefer-google nil
987 "Non-nil means, `org-store-link' will create web links to google groups.
988 When nil, Gnus will be used for such links.
989 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
990 negates this setting for the duration of the command."
991 :group 'org-link
992 :type 'boolean)
993
994 (defcustom org-open-non-existing-files nil
995 "Non-nil means, `org-open-file' will open non-existing file.
996 When nil, an error will be generated."
997 :group 'org-link
998 :type 'boolean)
999
1000 (defcustom org-confirm-shell-links t
1001 "Non-nil means, ask for confirmation before executing shell links.
1002 The default is true, to keep new users from shooting into their own foot."
1003 :group 'org-link
1004 :type 'boolean)
1005
1006 (defconst org-file-apps-defaults-gnu
1007 '((t . emacs)
1008 ("jpg" . "xv %s")
1009 ("gif" . "xv %s")
1010 ("ppm" . "xv %s")
1011 ("pgm" . "xv %s")
1012 ("pbm" . "xv %s")
1013 ("tif" . "xv %s")
1014 ("png" . "xv %s")
1015 ("ps" . "gv %s")
1016 ("ps.gz" . "gv %s")
1017 ("eps" . "gv %s")
1018 ("eps.gz" . "gv %s")
1019 ("dvi" . "xdvi %s")
1020 ("mpeg" . "plaympeg %s")
1021 ("mp3" . "plaympeg %s")
1022 ("fig" . "xfig %s")
1023 ("pdf" . "acroread %s")
1024 ("doc" . "soffice %s")
1025 ("ppt" . "soffice %s")
1026 ("pps" . "soffice %s")
1027 ("html" . "netscape -remote openURL(%s,new-window)")
1028 ("htm" . "netscape -remote openURL(%s,new-window)")
1029 ("xs" . "soffice %s"))
1030 "Default file applications on a UNIX/LINUX system.
1031 See `org-file-apps'.")
1032
1033 (defconst org-file-apps-defaults-macosx
1034 '((t . "open %s")
1035 ("ps" . "gv %s")
1036 ("ps.gz" . "gv %s")
1037 ("eps" . "gv %s")
1038 ("eps.gz" . "gv %s")
1039 ("dvi" . "xdvi %s")
1040 ("fig" . "xfig %s"))
1041 "Default file applications on a MacOS X system.
1042 The system \"open\" is known as a default, but we use X11 applications
1043 for some files for which the OS does not have a good default.
1044 See `org-file-apps'.")
1045
1046 (defconst org-file-apps-defaults-windowsnt
1047 '((t . (w32-shell-execute "open" file)))
1048 "Default file applications on a Windows NT system.
1049 The system \"open\" is used for most files.
1050 See `org-file-apps'.")
1051
1052 (defcustom org-file-apps
1053 '(
1054 ("txt" . emacs)
1055 ("tex" . emacs)
1056 ("ltx" . emacs)
1057 ("org" . emacs)
1058 ("el" . emacs)
1059 )
1060 "External applications for opening `file:path' items in a document.
1061 Org-mode uses system defaults for different file types, but
1062 you can use this variable to set the application for a given file
1063 extension. The entries in this list are cons cells with a file extension
1064 and the corresponding command. Possible values for the command are:
1065 `emacs' The file will be visited by the current Emacs process.
1066 `default' Use the default application for this file type.
1067 string A command to be executed by a shell; %s will be replaced
1068 by the path to the file.
1069 sexp A Lisp form which will be evaluated. The file path will
1070 be available in the Lisp variable `file'.
1071 For more examples, see the system specific constants
1072 `org-file-apps-defaults-macosx'
1073 `org-file-apps-defaults-windowsnt'
1074 `org-file-apps-defaults-gnu'."
1075 :group 'org-link
1076 :type '(repeat
1077 (cons (string :tag "Extension")
1078 (choice :value ""
1079 (const :tag "Visit with Emacs" 'emacs)
1080 (const :tag "Use system default" 'default)
1081 (string :tag "Command")
1082 (sexp :tag "Lisp form")))))
1083
1084
1085 (defgroup org-remember nil
1086 "Options concerning interaction with remember.el."
1087 :tag "Org Remember"
1088 :group 'org)
1089
1090 (defcustom org-directory "~/org"
1091 "Directory with org files.
1092 This directory will be used as default to prompt for org files.
1093 Used by the hooks for remember.el."
1094 :group 'org-remember
1095 :type 'directory)
1096
1097 (defcustom org-default-notes-file "~/.notes"
1098 "Default target for storing notes.
1099 Used by the hooks for remember.el. This can be a string, or nil to mean
1100 the value of `remember-data-file'."
1101 :group 'org-remember
1102 :type '(choice
1103 (const :tag "Default from remember-data-file" nil)
1104 file))
1105
1106 (defcustom org-reverse-note-order nil
1107 "Non-nil means, store new notes at the beginning of a file or entry.
1108 When nil, new notes will be filed to the end of a file or entry."
1109 :group 'org-remember
1110 :type '(choice
1111 (const :tag "Reverse always" t)
1112 (const :tag "Reverse never" nil)
1113 (repeat :tag "By file name regexp"
1114 (cons regexp boolean))))
1115
1116 (defgroup org-table nil
1117 "Options concerning tables in Org-mode."
1118 :tag "Org Table"
1119 :group 'org)
1120
1121 (defcustom org-enable-table-editor 'optimized
1122 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1123 When nil, such lines will be treated like ordinary lines.
1124
1125 When equal to the symbol `optimized', the table editor will be optimized to
1126 do the following
1127 - Use automatic overwrite mode in front of whitespace in table fields.
1128 This make the structure of the table stay in tact as long as the edited
1129 field does not exceed the column width.
1130 - Minimize the number of realigns. Normally, the table is aligned each time
1131 TAB or RET are pressed to move to another field. With optimization this
1132 happens only if changes to a field might have changed the column width.
1133 Optimization requires replacing the functions `self-insert-command',
1134 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1135 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1136 very good at guessing when a re-align will be necessary, but you can always
1137 force one with `C-c C-c'.
1138
1139 If you would like to use the optimized version in Org-mode, but the
1140 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1141
1142 This variable can be used to turn on and off the table editor during a session,
1143 but in order to toggle optimization, a restart is required."
1144 :group 'org-table
1145 :type '(choice
1146 (const :tag "off" nil)
1147 (const :tag "on" t)
1148 (const :tag "on, optimized" optimized)))
1149
1150 (defcustom org-table-default-size "5x2"
1151 "The default size for newly created tables, Columns x Rows."
1152 :group 'org-table
1153 :type 'string)
1154
1155 (defcustom org-table-automatic-realign t
1156 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1157 When nil, aligning is only done with \\[org-table-align], or after column
1158 removal/insertion."
1159 :group 'org-table
1160 :type 'boolean)
1161
1162 (defcustom org-table-spaces-around-separators '(1 . 1)
1163 "The number of spaces to be placed before and after separators."
1164 :group 'org-table
1165 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1166
1167 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1168 "The number of spaces to be placed before and after separators.
1169 This option applies when the column separators have been made invisible."
1170 :group 'org-table
1171 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1172
1173 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1174 "Regular expression for recognizing numbers in table columns.
1175 If a table column contains mostly numbers, it will be aligned to the
1176 right. If not, it will be aligned to the left.
1177
1178 The default value of this option is a regular expression which allows
1179 anything which looks remotely like a number as used in scientific
1180 context. For example, all of the following will be considered a
1181 number:
1182 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1183
1184 Other options offered by the customize interface are more restrictive."
1185 :group 'org-table
1186 :type '(choice
1187 (const :tag "Positive Integers"
1188 "^[0-9]+$")
1189 (const :tag "Integers"
1190 "^[-+]?[0-9]+$")
1191 (const :tag "Floating Point Numbers"
1192 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1193 (const :tag "Floating Point Number or Integer"
1194 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1195 (const :tag "Exponential, Floating point, Integer"
1196 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1197 (const :tag "Very General Number-Like"
1198 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1199 (string :tag "Regexp:")))
1200
1201 (defcustom org-table-number-fraction 0.5
1202 "Fraction of numbers in a column required to make the column align right.
1203 In a column all non-white fields are considered. If at least this
1204 fraction of fields is matched by `org-table-number-fraction',
1205 alignment to the right border applies."
1206 :group 'org-table
1207 :type 'number)
1208
1209 (defcustom org-export-highlight-first-table-line t
1210 "Non-nil means, highlight the first table line.
1211 In HTML export, this means use <th> instead of <td>.
1212 In tables created with table.el, this applies to the first table line.
1213 In Org-mode tables, all lines before the first horizontal separator
1214 line will be formatted with <th> tags."
1215 :group 'org-table
1216 :type 'boolean)
1217
1218
1219 (defgroup org-table-calculation nil
1220 "Options concerning tables in Org-mode."
1221 :tag "Org Table Calculation"
1222 :group 'org)
1223
1224 (defcustom org-table-copy-increment t
1225 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1226 :group 'org-table-calculation
1227 :type 'boolean)
1228
1229 (defcustom org-calc-default-modes
1230 '(calc-internal-prec 12
1231 calc-float-format (float 5)
1232 calc-angle-mode deg
1233 calc-prefer-frac nil
1234 calc-symbolic-mode nil
1235 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1236 calc-display-working-message t
1237 )
1238 "List with Calc mode settings for use in calc-eval for table formulas.
1239 The list must contain alternating symbols (calc modes variables and values.
1240 Don't remove any of the default settings, just change the values. Org-mode
1241 relies on the variables to be present in the list."
1242 :group 'org-table-calculation
1243 :type 'plist)
1244
1245 (defcustom org-table-formula-evaluate-inline t
1246 "Non-nil means, TAB and RET evaluate a formula in current table field.
1247 If the current field starts with an equal sign, it is assumed to be a formula
1248 which should be evaluated as described in the manual and in the documentation
1249 string of the command `org-table-eval-formula'. This feature requires the
1250 Emacs calc package.
1251 When this variable is nil, formula calculation is only available through
1252 the command \\[org-table-eval-formula]."
1253 :group 'org-table-calculation
1254 :type 'boolean)
1255
1256
1257 (defcustom org-table-formula-use-constants t
1258 "Non-nil means, interpret constants in formulas in tables.
1259 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1260 by the value given in `org-table-formula-constants', or by a value obtained
1261 from the `constants.el' package."
1262 :group 'org-table-calculation
1263 :type 'boolean)
1264
1265 (defcustom org-table-formula-constants nil
1266 "Alist with constant names and values, for use in table formulas.
1267 The car of each element is a name of a constant, without the `$' before it.
1268 The cdr is the value as a string. For example, if you'd like to use the
1269 speed of light in a formula, you would configure
1270
1271 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1272
1273 and then use it in an equation like `$1*$c'."
1274 :group 'org-table-calculation
1275 :type '(repeat
1276 (cons (string :tag "name")
1277 (string :tag "value"))))
1278
1279 (defcustom org-table-formula-numbers-only nil
1280 "Non-nil means, calculate only with numbers in table formulas.
1281 Then all input fields will be converted to a number, and the result
1282 must also be a number. When nil, calc's full potential is available
1283 in table calculations, including symbolics etc."
1284 :group 'org-table-calculation
1285 :type 'boolean)
1286
1287 (defcustom org-table-tab-recognizes-table.el t
1288 "Non-nil means, TAB will automatically notice a table.el table.
1289 When it sees such a table, it moves point into it and - if necessary -
1290 calls `table-recognize-table'."
1291 :group 'org-table
1292 :type 'boolean)
1293
1294 (defcustom org-export-prefer-native-exporter-for-tables nil
1295 "Non-nil means, always export tables created with table.el natively.
1296 Natively means, use the HTML code generator in table.el.
1297 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1298 the table does not use row- or column-spanning). This has the
1299 advantage, that the automatic HTML conversions for math symbols and
1300 sub/superscripts can be applied. Org-mode's HTML generator is also
1301 much faster."
1302 :group 'org-table
1303 :type 'boolean)
1304
1305 (defcustom org-enable-fixed-width-editor t
1306 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1307 This currently only means, they are never auto-wrapped.
1308 When nil, such lines will be treated like ordinary lines."
1309 :group 'org-table
1310 :type 'boolean)
1311
1312 (defgroup org-export nil
1313 "Options for exporting org-listings."
1314 :tag "Org Export"
1315 :group 'org)
1316
1317 (defcustom org-export-language-setup
1318 '(("en" "Author" "Date" "Table of Contents")
1319 ("da" "Ophavsmand" "Dato" "Indhold")
1320 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1321 ("es" "Autor" "Fecha" "\xccndice")
1322 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1323 ("it" "Autore" "Data" "Indice")
1324 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1325 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1326 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1327 "Terms used in export text, translated to different languages.
1328 Use the variable `org-export-default-language' to set the language,
1329 or use the +OPTION lines for a per-file setting."
1330 :group 'org-export
1331 :type '(repeat
1332 (list
1333 (string :tag "HTML language tag")
1334 (string :tag "Author")
1335 (string :tag "Date")
1336 (string :tag "Table of Contents"))))
1337
1338 (defcustom org-export-default-language "en"
1339 "The default language of HTML export, as a string.
1340 This should have an association in `org-export-language-setup'"
1341 :group 'org-export
1342 :type 'string)
1343
1344 (defcustom org-export-headline-levels 3
1345 "The last level which is still exported as a headline.
1346 Inferior levels will produce itemize lists when exported.
1347 Note that a numeric prefix argument to an exporter function overrides
1348 this setting.
1349
1350 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1351 :group 'org-export
1352 :type 'number)
1353
1354 (defcustom org-export-with-section-numbers t
1355 "Non-nil means, add section numbers to headlines when exporting.
1356
1357 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1358 :group 'org-export
1359 :type 'boolean)
1360
1361 (defcustom org-export-with-toc t
1362 "Non-nil means, create a table of contents in exported files.
1363 The TOC contains headlines with levels up to`org-export-headline-levels'.
1364
1365 Headlines which contain any TODO items will be marked with \"(*)\" in
1366 ASCII export, and with red color in HTML output.
1367
1368 In HTML output, the TOC will be clickable.
1369
1370 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1371 :group 'org-export
1372 :type 'boolean)
1373
1374 (defcustom org-export-preserve-breaks nil
1375 "Non-nil means, preserve all line breaks when exporting.
1376 Normally, in HTML output paragraphs will be reformatted. In ASCII
1377 export, line breaks will always be preserved, regardless of this variable.
1378
1379 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1380 :group 'org-export
1381 :type 'boolean)
1382
1383 (defcustom org-export-html-inline-images t
1384 "Non-nil means, inline images into exported HTML pages.
1385 The link will still be to the original location of the image file.
1386 So if you are moving the page, lets say to your public HTML site,
1387 you will have to move the image and maybe change the link."
1388 :group 'org-export
1389 :type 'boolean)
1390
1391 (defcustom org-export-html-expand t
1392 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1393 When nil, these tags will be exported as plain text and therefore
1394 not be interpreted by a browser.
1395
1396 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1397 :group 'org-export
1398 :type 'boolean)
1399
1400 (defcustom org-export-with-fixed-width t
1401 "Non-nil means, lines starting with \":\" will be in fixed width font.
1402 This can be used to have pre-formatted text, fragments of code etc. For
1403 example
1404 : ;; Some Lisp examples
1405 : (while (defc cnt)
1406 : (ding))
1407 will be looking just like this in also HTML. In ASCII export, this option
1408 has no effect.
1409
1410 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1411 :group 'org-export
1412 :type 'boolean)
1413
1414 (defcustom org-export-with-tables t
1415 "If non-nil, lines starting with \"|\" define a table.
1416 For example:
1417
1418 | Name | Address | Birthday |
1419 |-------------+----------+-----------|
1420 | Arthur Dent | England | 29.2.2100 |
1421
1422 In ASCII export, this option has no effect.
1423
1424 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1425 :group 'org-export
1426 :type 'boolean)
1427
1428 (defcustom org-export-html-table-tag
1429 "<table border=1 cellspacing=0 cellpadding=6>"
1430 "The HTML tag used to start a table.
1431 This must be a <table> tag, but you may change the options like
1432 borders and spacing."
1433 :group 'org-export
1434 :type 'string)
1435
1436 (defcustom org-export-with-emphasize t
1437 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1438 If the export target supports emphasizing text, the word will be
1439 typeset in bold, italic, or underlined, respectively. Works only for
1440 single words, but you can say: I *really* *mean* *this*.
1441 In ASCII export, this option has no effect.
1442
1443 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1444 :group 'org-export
1445 :type 'boolean)
1446
1447 (defcustom org-match-sexp-depth 3
1448 "Number of stacked braces for sub/superscript matching.
1449 This has to be set before loading org.el to be effective."
1450 :group 'org-export
1451 :type 'integer)
1452
1453 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1454 (defcustom org-export-with-sub-superscripts t
1455 "Non-nil means, interpret \"_\" and \"^\" for export.
1456 When this option is turned on, you can use TeX-like syntax for sub- and
1457 superscripts. Several characters after \"_\" or \"^\" will be
1458 considered as a single item - so grouping with {} is normally not
1459 needed. For example, the following things will be parsed as single
1460 sub- or superscripts.
1461
1462 10^24 or 10^tau several digits will be considered 1 item
1463 10^-12 or 10^-tau a leading sign with digits or a word
1464 x^2-y^3 will be read as x^2 - y^3, because items are
1465 terminated by almost any nonword/nondigit char.
1466 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1467
1468 Still, ambiguity is possible - so when in doubt use {} to enclose the
1469 sub/superscript.
1470 In ASCII export, this option has no effect.
1471
1472 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1473 :group 'org-export
1474 :type 'boolean)
1475
1476 (defcustom org-export-with-TeX-macros t
1477 "Non-nil means, interpret simple TeX-like macros when exporting.
1478 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1479 No only real TeX macros will work here, but the standard HTML entities
1480 for math can be used as macro names as well. For a list of supported
1481 names in HTML export, see the constant `org-html-entities'.
1482 In ASCII export, this option has no effect.
1483
1484 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1485 :group 'org-export
1486 :type 'boolean)
1487
1488 (defcustom org-export-html-with-timestamp nil
1489 "If non-nil, write `org-export-html-html-helper-timestamp'
1490 into the exported html text. Otherwise, the buffer will just be saved
1491 to a file."
1492 :group 'org-export
1493 :type 'boolean)
1494
1495 (defcustom org-export-html-html-helper-timestamp
1496 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1497 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1498 :group 'org-export
1499 :type 'string)
1500
1501 (defcustom org-export-ascii-show-new-buffer t
1502 "Non-nil means, popup buffer containing the exported ASCII text.
1503 Otherwise the buffer will just be saved to a file and stay hidden."
1504 :group 'org-export
1505 :type 'boolean)
1506
1507 (defcustom org-export-html-show-new-buffer nil
1508 "Non-nil means, popup buffer containing the exported html text.
1509 Otherwise, the buffer will just be saved to a file and stay hidden."
1510 :group 'org-export
1511 :type 'boolean)
1512
1513 (defgroup org-faces nil
1514 "Faces for highlighting in Org-mode."
1515 :tag "Org Faces"
1516 :group 'org)
1517
1518 (defface org-level-1 ;; font-lock-function-name-face
1519 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1520 (((class color) (background light)) (:foreground "Blue"))
1521 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1522 (t (:inverse-video t :bold t)))
1523 "Face used for level 1 headlines."
1524 :group 'org-faces)
1525
1526 (defface org-level-2 ;; font-lock-variable-name-face
1527 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1528 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1529 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1530 (t (:bold t :italic t)))
1531 "Face used for level 2 headlines."
1532 :group 'org-faces)
1533
1534 (defface org-level-3 ;; font-lock-keyword-face
1535 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1536 (((class color) (background light)) (:foreground "Purple"))
1537 (((class color) (background dark)) (:foreground "Cyan"))
1538 (t (:bold t)))
1539 "Face used for level 3 headlines."
1540 :group 'org-faces)
1541
1542 (defface org-level-4 ;; font-lock-comment-face
1543 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1544 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1545 (((class color) (background light)) (:foreground "Firebrick"))
1546 (((class color) (background dark)) (:foreground "chocolate1"))
1547 (t (:bold t :italic t)))
1548 "Face used for level 4 headlines."
1549 :group 'org-faces)
1550
1551 (defface org-level-5 ;; font-lock-type-face
1552 '((((type tty) (class color)) (:foreground "green"))
1553 (((class color) (background light)) (:foreground "ForestGreen"))
1554 (((class color) (background dark)) (:foreground "PaleGreen"))
1555 (t (:bold t :underline t)))
1556 "Face used for level 5 headlines."
1557 :group 'org-faces)
1558
1559 (defface org-level-6 ;; font-lock-constant-face
1560 '((((type tty) (class color)) (:foreground "magenta"))
1561 (((class color) (background light)) (:foreground "CadetBlue"))
1562 (((class color) (background dark)) (:foreground "Aquamarine"))
1563 (t (:bold t :underline t)))
1564 "Face used for level 6 headlines."
1565 :group 'org-faces)
1566
1567 (defface org-level-7 ;; font-lock-builtin-face
1568 '((((type tty) (class color)) (:foreground "blue" :weight light))
1569 (((class color) (background light)) (:foreground "Orchid"))
1570 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1571 (t (:bold t)))
1572 "Face used for level 7 headlines."
1573 :group 'org-faces)
1574
1575 (defface org-level-8 ;; font-lock-string-face
1576 '((((type tty) (class color)) (:foreground "green"))
1577 (((class color) (background light)) (:foreground "RosyBrown"))
1578 (((class color) (background dark)) (:foreground "LightSalmon"))
1579 (t (:italic t)))
1580 "Face used for level 8 headlines."
1581 :group 'org-faces)
1582
1583 (defface org-warning ;; font-lock-warning-face
1584 '((((type tty) (class color)) (:foreground "red"))
1585 (((class color) (background light)) (:foreground "Red" :bold t))
1586 (((class color) (background dark)) (:foreground "Red1" :bold t))
1587 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1588 (t (:inverse-video t :bold t)))
1589 "Face for deadlines and TODO keywords."
1590 :group 'org-faces)
1591
1592 (defcustom org-fontify-done-headline nil
1593 "Non-nil means, change the face of a headline if it is marked DONE.
1594 Normally, only the TODO/DONE keyword indicates the state of a headline.
1595 When this is non-nil, the headline after the keyword is set to the
1596 `org-headline-done' as an additional indication."
1597 :group 'org-faces
1598 :type 'boolean)
1599
1600 (defface org-headline-done ;; font-lock-string-face
1601 '((((type tty) (class color)) (:foreground "green"))
1602 (((class color) (background light)) (:foreground "RosyBrown"))
1603 (((class color) (background dark)) (:foreground "LightSalmon"))
1604 (t (:italic t)))
1605 "Face used to indicate that a headline is DONE. See also the variable
1606 `org-fontify-done-headline'."
1607 :group 'org-faces)
1608
1609 ;; Inheritance does not yet work for xemacs. So we just copy...
1610
1611 (defface org-deadline-announce
1612 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1613 (((class color) (background light)) (:foreground "Blue"))
1614 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1615 (t (:inverse-video t :bold t)))
1616 "Face for upcoming deadlines."
1617 :group 'org-faces)
1618
1619 (defface org-scheduled-today
1620 '((((type tty) (class color)) (:foreground "green"))
1621 (((class color) (background light)) (:foreground "DarkGreen"))
1622 (((class color) (background dark)) (:foreground "PaleGreen"))
1623 (t (:bold t :underline t)))
1624 "Face for items scheduled for a certain day."
1625 :group 'org-faces)
1626
1627 (defface org-scheduled-previously
1628 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1629 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1630 (((class color) (background light)) (:foreground "Firebrick"))
1631 (((class color) (background dark)) (:foreground "chocolate1"))
1632 (t (:bold t :italic t)))
1633 "Face for items scheduled previously, and not yet done."
1634 :group 'org-faces)
1635
1636 (defface org-formula
1637 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1638 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1639 (((class color) (background light)) (:foreground "Firebrick"))
1640 (((class color) (background dark)) (:foreground "chocolate1"))
1641 (t (:bold t :italic t)))
1642 "Face for items scheduled previously, and not yet done."
1643 :group 'org-faces)
1644
1645 (defface org-link
1646 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1647 (((class color) (background light)) (:foreground "Purple"))
1648 (((class color) (background dark)) (:foreground "Cyan"))
1649 (t (:bold t)))
1650 "Face for links."
1651 :group 'org-faces)
1652
1653 (defface org-done ;; font-lock-type-face
1654 '((((type tty) (class color)) (:foreground "green"))
1655 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1656 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1657 (t (:bold t :underline t)))
1658 "Face used for DONE."
1659 :group 'org-faces)
1660
1661 (defface org-table ;; font-lock-function-name-face
1662 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1663 (((class color) (background light)) (:foreground "Blue"))
1664 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1665 (t (:inverse-video t :bold t)))
1666 "Face used for tables."
1667 :group 'org-faces)
1668
1669 (defface org-time-grid ;; font-lock-variable-name-face
1670 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1671 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1672 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1673 (t (:bold t :italic t)))
1674 "Face used for level 2 headlines."
1675 :group 'org-faces)
1676
1677 (defvar org-level-faces
1678 '(
1679 org-level-1
1680 org-level-2
1681 org-level-3
1682 org-level-4
1683 org-level-5
1684 org-level-6
1685 org-level-7
1686 org-level-8
1687 ))
1688 (defvar org-n-levels (length org-level-faces))
1689
1690 ;; Tell the compiler about dynamically scoped variables,
1691 ;; and variables from other packages
1692 (eval-when-compile
1693 (defvar zmacs-regions)
1694 (defvar original-date)
1695 (defvar org-transient-mark-mode)
1696 (defvar org-old-auto-fill-inhibit-regexp)
1697 (defvar orgtbl-mode-menu)
1698 (defvar org-html-entities)
1699 (defvar org-goto-start-pos)
1700 (defvar org-cursor-color)
1701 (defvar org-time-was-given)
1702 (defvar org-ts-what)
1703 (defvar mark-active)
1704 (defvar timecnt)
1705 (defvar levels-open)
1706 (defvar title)
1707 (defvar author)
1708 (defvar email)
1709 (defvar text)
1710 (defvar entry)
1711 (defvar date)
1712 (defvar language)
1713 (defvar options)
1714 (defvar ans1)
1715 (defvar ans2)
1716 (defvar starting-day)
1717 (defvar include-all-loc)
1718 (defvar vm-message-pointer)
1719 (defvar vm-folder-directory)
1720 (defvar wl-summary-buffer-elmo-folder)
1721 (defvar wl-summary-buffer-folder-name)
1722 (defvar gnus-group-name)
1723 (defvar gnus-article-current)
1724 (defvar w3m-current-url)
1725 (defvar org-selected-point)
1726 (defvar calendar-mode-map)
1727 (defvar remember-save-after-remembering)
1728 (defvar remember-data-file))
1729
1730
1731 ;;; Define the mode
1732
1733 (defvar org-mode-map (copy-keymap outline-mode-map)
1734 "Keymap for Org-mode.")
1735
1736 (defvar org-struct-menu)
1737 (defvar org-org-menu)
1738 (defvar org-tbl-menu)
1739
1740 ;; We use a before-change function to check if a table might need
1741 ;; an update.
1742 (defvar org-table-may-need-update t
1743 "Indicates of a table might need an update.
1744 This variable is set by `org-before-change-function'. `org-table-align'
1745 sets it back to nil.")
1746 (defvar org-mode-hook nil)
1747 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1748
1749
1750 ;;;###autoload
1751 (define-derived-mode org-mode outline-mode "Org"
1752 "Outline-based notes management and organizer, alias
1753 \"Carstens outline-mode for keeping track of everything.\"
1754
1755 Org-mode develops organizational tasks around a NOTES file which
1756 contains information about projects as plain text. Org-mode is
1757 implemented on top of outline-mode, which is ideal to keep the content
1758 of large files well structured. It supports ToDo items, deadlines and
1759 time stamps, which magically appear in the diary listing of the Emacs
1760 calendar. Tables are easily created with a built-in table editor.
1761 Plain text URL-like links connect to websites, emails (VM), Usenet
1762 messages (Gnus), BBDB entries, and any files related to the project.
1763 For printing and sharing of notes, an Org-mode file (or a part of it)
1764 can be exported as a structured ASCII or HTML file.
1765
1766 The following commands are available:
1767
1768 \\{org-mode-map}"
1769 (easy-menu-add org-org-menu)
1770 (easy-menu-add org-tbl-menu)
1771 (org-install-agenda-files-menu)
1772 (setq outline-regexp "\\*+")
1773 (if org-startup-truncated (setq truncate-lines t))
1774 (org-set-regexps-and-options)
1775 (set (make-local-variable 'font-lock-unfontify-region-function)
1776 'org-unfontify-region)
1777 ;; Activate before-change-function
1778 (set (make-local-variable 'org-table-may-need-update) t)
1779 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1780 (add-hook 'before-change-functions 'org-before-change-function nil
1781 'local)
1782 ;; Paragraph regular expressions
1783 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1784 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1785 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1786 (set (make-local-variable 'auto-fill-inhibit-regexp)
1787 (concat "\\*\\|#"
1788 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1789 (concat
1790 "\\|[ \t]*["
1791 (if org-enable-table-editor "|" "")
1792 (if org-enable-fixed-width-editor ":" "")
1793 "]"))))
1794 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1795 ;; Settings for Calc embedded mode
1796 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1797 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1798 (if (and org-insert-mode-line-in-empty-file
1799 (interactive-p)
1800 (= (point-min) (point-max)))
1801 (insert " -*- mode: org -*-\n\n"))
1802
1803 ;; Get rid of Outline menus, they are not needed
1804 ;; Need to do this here because define-derived-mode sets up
1805 ;; the keymap so late.
1806 (if org-xemacs-p
1807 (progn
1808 (delete-menu-item '("Headings"))
1809 (delete-menu-item '("Show"))
1810 (delete-menu-item '("Hide"))
1811 (set-menubar-dirty-flag))
1812 (define-key org-mode-map [menu-bar headings] 'undefined)
1813 (define-key org-mode-map [menu-bar hide] 'undefined)
1814 (define-key org-mode-map [menu-bar show] 'undefined))
1815
1816 (unless org-inhibit-startup
1817 (if org-startup-with-deadline-check
1818 (call-interactively 'org-check-deadlines)
1819 (cond
1820 ((eq org-startup-folded t)
1821 (org-cycle '(4)))
1822 ((eq org-startup-folded 'content)
1823 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1824 (org-cycle '(4)) (org-cycle '(4))))))))
1825
1826 (defun org-fill-paragraph (&optional justify)
1827 "Re-align a table, pass through to fill-paragraph if no table."
1828 (save-excursion
1829 (beginning-of-line 1)
1830 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1831
1832 (defsubst org-current-line (&optional pos)
1833 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1834
1835 ;;; Font-Lock stuff
1836
1837 (defvar org-mouse-map (make-sparse-keymap))
1838 (define-key org-mouse-map
1839 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1840 (define-key org-mouse-map
1841 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1842
1843 (require 'font-lock)
1844
1845 (defconst org-non-link-chars "\t\n\r|<>\000")
1846 (defconst org-link-regexp
1847 (if org-allow-space-in-links
1848 (concat
1849 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1850 (concat
1851 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1852 )
1853 "Regular expression for matching links.")
1854 (defconst org-link-maybe-angles-regexp
1855 (concat "<?\\(" org-link-regexp "\\)>?")
1856 "Matches a link and optionally surrounding angle brackets.")
1857 (defconst org-protected-link-regexp
1858 (concat "\000" org-link-regexp "\000")
1859 "Matches a link and optionally surrounding angle brackets.")
1860
1861 (defconst org-ts-lengths
1862 (cons (length (format-time-string (car org-time-stamp-formats)))
1863 (length (format-time-string (cdr org-time-stamp-formats))))
1864 "This holds the lengths of the two different time formats.")
1865 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1866 "Regular expression for fast time stamp matching.")
1867 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1868 "Regular expression matching time strings for analysis.")
1869 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1870 "Regular expression matching time stamps, with groups.")
1871 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1872 "Regular expression matching a time stamp range.")
1873 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1874 org-ts-regexp "\\)?")
1875 "Regular expression matching a time stamp or time stamp range.")
1876
1877 (defun org-activate-links (limit)
1878 "Run through the buffer and add overlays to links."
1879 (if (re-search-forward org-link-regexp limit t)
1880 (progn
1881 (add-text-properties (match-beginning 0) (match-end 0)
1882 (list 'mouse-face 'highlight
1883 'keymap org-mouse-map))
1884 t)))
1885
1886 (defun org-activate-dates (limit)
1887 "Run through the buffer and add overlays to dates."
1888 (if (re-search-forward org-tsr-regexp limit t)
1889 (progn
1890 (add-text-properties (match-beginning 0) (match-end 0)
1891 (list 'mouse-face 'highlight
1892 'keymap org-mouse-map))
1893 t)))
1894
1895 (defun org-font-lock-level ()
1896 (save-excursion
1897 (org-back-to-heading t)
1898 (- (match-end 0) (match-beginning 0))))
1899
1900 (defvar org-font-lock-keywords nil)
1901
1902 (defun org-set-font-lock-defaults ()
1903 (let ((org-font-lock-extra-keywords
1904 (list
1905 '(org-activate-links (0 'org-link))
1906 '(org-activate-dates (0 'org-link))
1907 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1908 '(1 'org-warning t))
1909 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning t))
1910 (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1911 (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1912 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1913 ;; (3 'bold))
1914 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1915 ;; (3 'italic))
1916 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1917 ;; (3 'underline))
1918 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1919 '(1 'org-warning t))
1920 '("^#.*" (0 'font-lock-comment-face t))
1921 (if org-fontify-done-headline
1922 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1923 '(1 'org-done t) '(2 'org-headline-done t))
1924 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1925 '(1 'org-done t)))
1926 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1927 (1 'org-table t))
1928 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1929 '("| *\\(=[^|\n]*\\)" (1 'org-formula t))
1930 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
1931 )))
1932 (set (make-local-variable 'org-font-lock-keywords)
1933 (append
1934 (if org-noutline-p ; FIXME: I am not sure if eval will work
1935 ; on XEmacs if noutline is ever ported
1936 '((eval . (list "^\\(\\*+\\).*"
1937 0 '(nth
1938 (% (- (match-end 1) (match-beginning 1) 1)
1939 org-n-levels)
1940 org-level-faces)
1941 nil t)))
1942 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1943 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1944 org-n-levels)
1945 org-level-faces)
1946 nil t))))
1947 org-font-lock-extra-keywords))
1948 (set (make-local-variable 'font-lock-defaults)
1949 '(org-font-lock-keywords t nil nil backward-paragraph))
1950 (kill-local-variable 'font-lock-keywords) nil))
1951
1952 (defun org-unfontify-region (beg end &optional maybe_loudly)
1953 "Remove fontification and activation overlays from links."
1954 (font-lock-default-unfontify-region beg end)
1955 (let* ((buffer-undo-list t)
1956 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1957 (inhibit-modification-hooks t)
1958 deactivate-mark buffer-file-name buffer-file-truename)
1959 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1960
1961 ;;; Visibility cycling
1962
1963 (defvar org-cycle-global-status nil)
1964 (defvar org-cycle-subtree-status nil)
1965 (defun org-cycle (&optional arg)
1966 "Visibility cycling for Org-mode.
1967
1968 - When this function is called with a prefix argument, rotate the entire
1969 buffer through 3 states (global cycling)
1970 1. OVERVIEW: Show only top-level headlines.
1971 2. CONTENTS: Show all headlines of all levels, but no body text.
1972 3. SHOW ALL: Show everything.
1973
1974 - When point is at the beginning of a headline, rotate the subtree started
1975 by this line through 3 different states (local cycling)
1976 1. FOLDED: Only the main headline is shown.
1977 2. CHILDREN: The main headline and the direct children are shown. From
1978 this state, you can move to one of the children and
1979 zoom in further.
1980 3. SUBTREE: Show the entire subtree, including body text.
1981
1982 - When there is a numeric prefix, go up to a heading with level ARG, do
1983 a `show-subtree' and return to the previous cursor position. If ARG
1984 is negative, go up that many levels.
1985
1986 - When point is not at the beginning of a headline, execute
1987 `indent-relative', like TAB normally does. See the option
1988 `org-cycle-emulate-tab' for details.
1989
1990 - Special case: if point is the the beginning of the buffer and there is
1991 no headline in line 1, this function will act as if called with prefix arg."
1992 (interactive "P")
1993
1994 (if (or (and (bobp) (not (looking-at outline-regexp)))
1995 (equal arg '(4)))
1996 ;; special case: use global cycling
1997 (setq arg t))
1998
1999 (cond
2000
2001 ((org-at-table-p 'any)
2002 ;; Enter the table or move to the next field in the table
2003 (or (org-table-recognize-table.el)
2004 (progn
2005 (org-table-justify-field-maybe)
2006 (org-table-next-field))))
2007
2008 ((eq arg t) ;; Global cycling
2009
2010 (cond
2011 ((and (eq last-command this-command)
2012 (eq org-cycle-global-status 'overview))
2013 ;; We just created the overview - now do table of contents
2014 ;; This can be slow in very large buffers, so indicate action
2015 (message "CONTENTS...")
2016 (save-excursion
2017 ;; Visit all headings and show their offspring
2018 (goto-char (point-max))
2019 (catch 'exit
2020 (while (and (progn (condition-case nil
2021 (outline-previous-visible-heading 1)
2022 (error (goto-char (point-min))))
2023 t)
2024 (looking-at outline-regexp))
2025 (show-branches)
2026 (if (bobp) (throw 'exit nil))))
2027 (message "CONTENTS...done"))
2028 (setq org-cycle-global-status 'contents)
2029 (run-hook-with-args 'org-cycle-hook 'contents))
2030
2031 ((and (eq last-command this-command)
2032 (eq org-cycle-global-status 'contents))
2033 ;; We just showed the table of contents - now show everything
2034 (show-all)
2035 (message "SHOW ALL")
2036 (setq org-cycle-global-status 'all)
2037 (run-hook-with-args 'org-cycle-hook 'all))
2038
2039 (t
2040 ;; Default action: go to overview
2041 (hide-sublevels 1)
2042 (message "OVERVIEW")
2043 (setq org-cycle-global-status 'overview)
2044 (run-hook-with-args 'org-cycle-hook 'overview))))
2045
2046 ((integerp arg)
2047 ;; Show-subtree, ARG levels up from here.
2048 (save-excursion
2049 (org-back-to-heading)
2050 (outline-up-heading (if (< arg 0) (- arg)
2051 (- (outline-level) arg)))
2052 (org-show-subtree)))
2053
2054 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2055 ;; At a heading: rotate between three different views
2056 (org-back-to-heading)
2057 (let ((goal-column 0) eoh eol eos)
2058 ;; First, some boundaries
2059 (save-excursion
2060 (org-back-to-heading)
2061 (save-excursion
2062 (beginning-of-line 2)
2063 (while (and (not (eobp)) ;; this is like `next-line'
2064 (get-char-property (1- (point)) 'invisible))
2065 (beginning-of-line 2)) (setq eol (point)))
2066 (outline-end-of-heading) (setq eoh (point))
2067 (outline-end-of-subtree) (setq eos (point))
2068 (outline-next-heading))
2069 ;; Find out what to do next and set `this-command'
2070 (cond
2071 ((= eos eoh)
2072 ;; Nothing is hidden behind this heading
2073 (message "EMPTY ENTRY")
2074 (setq org-cycle-subtree-status nil))
2075 ((>= eol eos)
2076 ;; Entire subtree is hidden in one line: open it
2077 (org-show-entry)
2078 (show-children)
2079 (message "CHILDREN")
2080 (setq org-cycle-subtree-status 'children)
2081 (run-hook-with-args 'org-cycle-hook 'children))
2082 ((and (eq last-command this-command)
2083 (eq org-cycle-subtree-status 'children))
2084 ;; We just showed the children, now show everything.
2085 (org-show-subtree)
2086 (message "SUBTREE")
2087 (setq org-cycle-subtree-status 'subtree)
2088 (run-hook-with-args 'org-cycle-hook 'subtree))
2089 (t
2090 ;; Default action: hide the subtree.
2091 (hide-subtree)
2092 (message "FOLDED")
2093 (setq org-cycle-subtree-status 'folded)
2094 (run-hook-with-args 'org-cycle-hook 'folded)))))
2095
2096 ;; TAB emulation
2097 (buffer-read-only (org-back-to-heading))
2098 ((if (and (eq org-cycle-emulate-tab 'white)
2099 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2100 t
2101 (eq org-cycle-emulate-tab t))
2102 (if (and (looking-at "[ \n\r\t]")
2103 (string-match "^[ \t]*$" (buffer-substring
2104 (point-at-bol) (point))))
2105 (progn
2106 (beginning-of-line 1)
2107 (and (looking-at "[ \t]+") (replace-match ""))))
2108 (indent-relative))
2109
2110 (t (save-excursion
2111 (org-back-to-heading)
2112 (org-cycle)))))
2113
2114 (defun org-optimize-window-after-visibility-change (state)
2115 "Adjust the window after a change in outline visibility.
2116 This function is the default value of the hook `org-cycle-hook'."
2117 (cond
2118 ((eq state 'overview) (org-first-headline-recenter 1))
2119 ((eq state 'content) nil)
2120 ((eq state 'all) nil)
2121 ((eq state 'folded) nil)
2122 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2123 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2124
2125 (defun org-subtree-end-visible-p ()
2126 "Is the end of the current subtree visible?"
2127 (pos-visible-in-window-p
2128 (save-excursion (outline-end-of-subtree) (point))))
2129
2130 (defun org-first-headline-recenter (&optional N)
2131 "Move cursor to the first headline and recenter the headline.
2132 Optional argument N means, put the headline into the Nth line of the window."
2133 (goto-char (point-min))
2134 (when (re-search-forward (concat "^" outline-regexp) nil t)
2135 (beginning-of-line)
2136 (recenter (prefix-numeric-value N))))
2137
2138 (defvar org-goto-window-configuration nil)
2139 (defvar org-goto-marker nil)
2140 (defvar org-goto-map (make-sparse-keymap))
2141 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2142 (while (setq cmd (pop cmds))
2143 (substitute-key-definition cmd cmd org-goto-map global-map)))
2144 (define-key org-goto-map "\C-m" 'org-goto-ret)
2145 (define-key org-goto-map [(left)] 'org-goto-left)
2146 (define-key org-goto-map [(right)] 'org-goto-right)
2147 (define-key org-goto-map [(?q)] 'org-goto-quit)
2148 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2149 (define-key org-goto-map "\C-i" 'org-cycle)
2150 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2151 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2152 (define-key org-goto-map "n" 'outline-next-visible-heading)
2153 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2154 (define-key org-goto-map "f" 'outline-forward-same-level)
2155 (define-key org-goto-map "b" 'outline-backward-same-level)
2156 (define-key org-goto-map "u" 'outline-up-heading)
2157 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2158 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2159 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2160 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2161 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2162 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2163 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2164
2165 (defconst org-goto-help
2166 "Select a location to jump to, press RET
2167 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2168
2169 (defun org-goto ()
2170 "Go to a different location of the document, keeping current visibility.
2171
2172 When you want to go to a different location in a document, the fastest way
2173 is often to fold the entire buffer and then dive into the tree. This
2174 method has the disadvantage, that the previous location will be folded,
2175 which may not be what you want.
2176
2177 This command works around this by showing a copy of the current buffer in
2178 overview mode. You can dive into the tree in that copy, to find the
2179 location you want to reach. When pressing RET, the command returns to the
2180 original buffer in which the visibility is still unchanged. It then jumps
2181 to the new location, making it and the headline hierarchy above it visible."
2182 (interactive)
2183 (let* ((org-goto-start-pos (point))
2184 (selected-point
2185 (org-get-location (current-buffer) org-goto-help)))
2186 (if selected-point
2187 (progn
2188 (goto-char selected-point)
2189 (if (org-invisible-p) (org-show-hierarchy-above)))
2190 (error "Quit"))))
2191
2192 (defun org-get-location (buf help)
2193 "Let the user select a location in the Org-mode buffer BUF.
2194 This function uses a recursive edit. It returns the selected position
2195 or nil."
2196 (let (org-selected-point)
2197 (save-excursion
2198 (save-window-excursion
2199 (delete-other-windows)
2200 (switch-to-buffer (get-buffer-create "*org-goto*"))
2201 (with-output-to-temp-buffer "*Help*"
2202 (princ help))
2203 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2204 (setq buffer-read-only nil)
2205 (erase-buffer)
2206 (insert-buffer buf)
2207 (let ((org-startup-truncated t)
2208 (org-startup-folded t)
2209 (org-startup-with-deadline-check nil))
2210 (org-mode))
2211 (setq buffer-read-only t)
2212 (if (boundp 'org-goto-start-pos)
2213 (goto-char org-goto-start-pos)
2214 (goto-char (point-min)))
2215 (org-beginning-of-line)
2216 (message "Select location and press RET")
2217 ;; now we make sure that during selection, ony very few keys work
2218 ;; and that it is impossible to switch to another window.
2219 (let ((gm (current-global-map))
2220 (overriding-local-map org-goto-map))
2221 (unwind-protect
2222 (progn
2223 (use-global-map org-goto-map)
2224 (recursive-edit))
2225 (use-global-map gm)))))
2226 (kill-buffer "*org-goto*")
2227 org-selected-point))
2228
2229 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2230 (defun org-goto-ret (&optional arg)
2231 "Finish org-goto by going to the new location."
2232 (interactive "P")
2233 (setq org-selected-point (point)
2234 current-prefix-arg arg)
2235 (throw 'exit nil))
2236
2237 (defun org-goto-left ()
2238 "Finish org-goto by going to the new location."
2239 (interactive)
2240 (if (org-on-heading-p)
2241 (progn
2242 (beginning-of-line 1)
2243 (setq org-selected-point (point)
2244 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2245 (throw 'exit nil))
2246 (error "Not on a heading")))
2247
2248 (defun org-goto-right ()
2249 "Finish org-goto by going to the new location."
2250 (interactive)
2251 (if (org-on-heading-p)
2252 (progn
2253 (outline-end-of-subtree)
2254 (or (eobp) (forward-char 1))
2255 (setq org-selected-point (point)
2256 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2257 (throw 'exit nil))
2258 (error "Not on a heading")))
2259
2260 (defun org-goto-quit ()
2261 "Finish org-goto without cursor motion."
2262 (interactive)
2263 (setq org-selected-point nil)
2264 (throw 'exit nil))
2265
2266 ;;; Promotion, Demotion, Inserting new headlines
2267
2268 (defvar org-ignore-region nil
2269 "To temporarily disable the active region.")
2270
2271 (defun org-insert-heading ()
2272 "Insert a new heading with same depth at point."
2273 (interactive)
2274 (let* ((head (save-excursion
2275 (condition-case nil
2276 (org-back-to-heading)
2277 (error (outline-next-heading)))
2278 (prog1 (match-string 0)
2279 (funcall outline-level)))))
2280 (unless (bolp) (newline))
2281 (insert head)
2282 (unless (eolp)
2283 (save-excursion (newline-and-indent)))
2284 (unless (equal (char-before) ?\ )
2285 (insert " "))
2286 (run-hooks 'org-insert-heading-hook)))
2287
2288 (defun org-insert-todo-heading (arg)
2289 "Insert a new heading with the same level and TODO state as current heading.
2290 If the heading has no TODO state, or if the state is DONE, use the first
2291 state (TODO by default). Also with prefix arg, force first state."
2292 (interactive "P")
2293 (org-insert-heading)
2294 (save-excursion
2295 (org-back-to-heading)
2296 (outline-previous-heading)
2297 (looking-at org-todo-line-regexp))
2298 (if (or arg
2299 (not (match-beginning 2))
2300 (equal (match-string 2) org-done-string))
2301 (insert (car org-todo-keywords) " ")
2302 (insert (match-string 2) " ")))
2303
2304 (defun org-promote-subtree ()
2305 "Promote the entire subtree.
2306 See also `org-promote'."
2307 (interactive)
2308 (save-excursion
2309 (org-map-tree 'org-promote)))
2310
2311 (defun org-demote-subtree ()
2312 "Demote the entire subtree. See `org-demote'.
2313 See also `org-promote'."
2314 (interactive)
2315 (save-excursion
2316 (org-map-tree 'org-demote)))
2317
2318 (defun org-do-promote ()
2319 "Promote the current heading higher up the tree.
2320 If the region is active in `transient-mark-mode', promote all headings
2321 in the region."
2322 (interactive)
2323 (save-excursion
2324 (if (org-region-active-p)
2325 (org-map-region 'org-promote (region-beginning) (region-end))
2326 (org-promote)))
2327 (org-fix-position-after-promote))
2328
2329 (defun org-do-demote ()
2330 "Demote the current heading lower down the tree.
2331 If the region is active in `transient-mark-mode', demote all headings
2332 in the region."
2333 (interactive)
2334 (save-excursion
2335 (if (org-region-active-p)
2336 (org-map-region 'org-demote (region-beginning) (region-end))
2337 (org-demote)))
2338 (org-fix-position-after-promote))
2339
2340 (defun org-fix-position-after-promote ()
2341 "Make sure that after pro/demotion cursor position is right."
2342 (and (equal (char-after) ?\ )
2343 (equal (char-before) ?*)
2344 (forward-char 1)))
2345
2346 (defun org-promote ()
2347 "Promote the current heading higher up the tree.
2348 If the region is active in `transient-mark-mode', promote all headings
2349 in the region."
2350 (org-back-to-heading t)
2351 (let* ((level (save-match-data (funcall outline-level)))
2352 (up-head (make-string (1- level) ?*)))
2353 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2354 (replace-match up-head nil t)
2355 (if org-adapt-indentation
2356 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2357
2358 (defun org-demote ()
2359 "Demote the current heading lower down the tree.
2360 If the region is active in `transient-mark-mode', demote all headings
2361 in the region."
2362 (org-back-to-heading t)
2363 (let* ((level (save-match-data (funcall outline-level)))
2364 (down-head (make-string (1+ level) ?*)))
2365 (replace-match down-head nil t)
2366 (if org-adapt-indentation
2367 (org-fixup-indentation "^ " " " "^\\S-"))))
2368
2369 (defun org-map-tree (fun)
2370 "Call FUN for every heading underneath the current one."
2371 (org-back-to-heading)
2372 (let ((level (outline-level)))
2373 (save-excursion
2374 (funcall fun)
2375 (while (and (progn
2376 (outline-next-heading)
2377 (> (funcall outline-level) level))
2378 (not (eobp)))
2379 (funcall fun)))))
2380
2381 (defun org-map-region (fun beg end)
2382 "Call FUN for every heading between BEG and END."
2383 (let ((org-ignore-region t))
2384 (save-excursion
2385 (setq end (copy-marker end))
2386 (goto-char beg)
2387 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2388 (< (point) end))
2389 (funcall fun))
2390 (while (and (progn
2391 (outline-next-heading)
2392 (< (point) end))
2393 (not (eobp)))
2394 (funcall fun)))))
2395
2396 (defun org-fixup-indentation (from to prohibit)
2397 "Change the indentation in the current entry by re-replacing FROM with TO.
2398 However, if the regexp PROHIBIT matches at all, don't do anything.
2399 This is being used to change indentation along with the length of the
2400 heading marker. But if there are any lines which are not indented, nothing
2401 is changed at all."
2402 (save-excursion
2403 (let ((end (save-excursion (outline-next-heading)
2404 (point-marker))))
2405 (unless (save-excursion (re-search-forward prohibit end t))
2406 (while (re-search-forward from end t)
2407 (replace-match to)
2408 (beginning-of-line 2)))
2409 (move-marker end nil))))
2410
2411 ;;; Vertical tree motion, cutting and pasting of subtrees
2412
2413 (defun org-move-subtree-up (&optional arg)
2414 "Move the current subtree up past ARG headlines of the same level."
2415 (interactive "p")
2416 (org-move-subtree-down (- (prefix-numeric-value arg))))
2417
2418 (defun org-move-subtree-down (&optional arg)
2419 "Move the current subtree down past ARG headlines of the same level."
2420 (interactive "p")
2421 (setq arg (prefix-numeric-value arg))
2422 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2423 'outline-get-last-sibling))
2424 (ins-point (make-marker))
2425 (cnt (abs arg))
2426 beg end txt folded)
2427 ;; Select the tree
2428 (org-back-to-heading)
2429 (setq beg (point))
2430 (save-match-data
2431 (save-excursion (outline-end-of-heading)
2432 (setq folded (org-invisible-p)))
2433 (outline-end-of-subtree))
2434 (outline-next-heading)
2435 (setq end (point))
2436 ;; Find insertion point, with error handling
2437 (goto-char beg)
2438 (while (> cnt 0)
2439 (or (and (funcall movfunc) (looking-at outline-regexp))
2440 (progn (goto-char beg)
2441 (error "Cannot move past superior level or buffer limit")))
2442 (setq cnt (1- cnt)))
2443 (if (> arg 0)
2444 ;; Moving forward - still need to move over subtree
2445 (progn (outline-end-of-subtree)
2446 (outline-next-heading)
2447 (if (not (or (looking-at (concat "^" outline-regexp))
2448 (bolp)))
2449 (newline))))
2450 (move-marker ins-point (point))
2451 (setq txt (buffer-substring beg end))
2452 (delete-region beg end)
2453 (insert txt)
2454 (goto-char ins-point)
2455 (if folded (hide-subtree))
2456 (move-marker ins-point nil)))
2457
2458 (defvar org-subtree-clip ""
2459 "Clipboard for cut and paste of subtrees.
2460 This is actually only a copy of the kill, because we use the normal kill
2461 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2462
2463 (defvar org-subtree-clip-folded nil
2464 "Was the last copied subtree folded?
2465 This is used to fold the tree back after pasting.")
2466
2467 (defun org-cut-subtree ()
2468 "Cut the current subtree into the clipboard.
2469 This is a short-hand for marking the subtree and then cutting it."
2470 (interactive)
2471 (org-copy-subtree 'cut))
2472
2473 (defun org-copy-subtree (&optional cut)
2474 "Cut the current subtree into the clipboard.
2475 This is a short-hand for marking the subtree and then copying it.
2476 If CUT is non nil, actually cut the subtree."
2477 (interactive)
2478 (let (beg end folded)
2479 (org-back-to-heading)
2480 (setq beg (point))
2481 (save-match-data
2482 (save-excursion (outline-end-of-heading)
2483 (setq folded (org-invisible-p)))
2484 (outline-end-of-subtree))
2485 (if (equal (char-after) ?\n) (forward-char 1))
2486 (setq end (point))
2487 (goto-char beg)
2488 (when (> end beg)
2489 (setq org-subtree-clip-folded folded)
2490 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2491 (setq org-subtree-clip (current-kill 0))
2492 (message "%s: Subtree with %d characters"
2493 (if cut "Cut" "Copied")
2494 (length org-subtree-clip)))))
2495
2496 (defun org-paste-subtree (&optional level tree)
2497 "Paste the clipboard as a subtree, with modification of headline level.
2498 The entire subtree is promoted or demoted in order to match a new headline
2499 level. By default, the new level is derived from the visible headings
2500 before and after the insertion point, and taken to be the inferior headline
2501 level of the two. So if the previous visible heading is level 3 and the
2502 next is level 4 (or vice versa), level 4 will be used for insertion.
2503 This makes sure that the subtree remains an independent subtree and does
2504 not swallow low level entries.
2505
2506 You can also force a different level, either by using a numeric prefix
2507 argument, or by inserting the heading marker by hand. For example, if the
2508 cursor is after \"*****\", then the tree will be shifted to level 5.
2509
2510 If you want to insert the tree as is, just use \\[yank].
2511
2512 If optional TREE is given, use this text instead of the kill ring."
2513 (interactive "P")
2514 (unless (org-kill-is-subtree-p tree)
2515 (error
2516 (substitute-command-keys
2517 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2518 (let* ((txt (or tree (current-kill 0)))
2519 (^re (concat "^\\(" outline-regexp "\\)"))
2520 (re (concat "\\(" outline-regexp "\\)"))
2521 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2522
2523 (old-level (if (string-match ^re txt)
2524 (- (match-end 0) (match-beginning 0))
2525 -1))
2526 (force-level (cond (level (prefix-numeric-value level))
2527 ((string-match
2528 ^re_ (buffer-substring (point-at-bol) (point)))
2529 (- (match-end 0) (match-beginning 0)))
2530 (t nil)))
2531 (previous-level (save-excursion
2532 (condition-case nil
2533 (progn
2534 (outline-previous-visible-heading 1)
2535 (if (looking-at re)
2536 (- (match-end 0) (match-beginning 0))
2537 1))
2538 (error 1))))
2539 (next-level (save-excursion
2540 (condition-case nil
2541 (progn
2542 (outline-next-visible-heading 1)
2543 (if (looking-at re)
2544 (- (match-end 0) (match-beginning 0))
2545 1))
2546 (error 1))))
2547 (new-level (or force-level (max previous-level next-level)))
2548 (shift (if (or (= old-level -1)
2549 (= new-level -1)
2550 (= old-level new-level))
2551 0
2552 (- new-level old-level)))
2553 (shift1 shift)
2554 (delta (if (> shift 0) -1 1))
2555 (func (if (> shift 0) 'org-demote 'org-promote))
2556 beg end)
2557 ;; Remove the forces level indicator
2558 (if force-level
2559 (delete-region (point-at-bol) (point)))
2560 ;; Make sure we start at the beginning of an empty line
2561 (if (not (bolp)) (insert "\n"))
2562 (if (not (looking-at "[ \t]*$"))
2563 (progn (insert "\n") (backward-char 1)))
2564 ;; Paste
2565 (setq beg (point))
2566 (insert txt)
2567 (setq end (point))
2568 (goto-char beg)
2569 ;; Shift if necessary
2570 (if (= shift 0)
2571 (message "Pasted at level %d, without shift" new-level)
2572 (save-restriction
2573 (narrow-to-region beg end)
2574 (while (not (= shift 0))
2575 (org-map-region func (point-min) (point-max))
2576 (setq shift (+ delta shift)))
2577 (goto-char (point-min))
2578 (message "Pasted at level %d, with shift by %d levels"
2579 new-level shift1)))
2580 (if (and (eq org-subtree-clip (current-kill 0))
2581 org-subtree-clip-folded)
2582 ;; The tree was folded before it was killed/copied
2583 (hide-subtree))))
2584
2585 (defun org-kill-is-subtree-p (&optional txt)
2586 "Check if the current kill is an outline subtree, or a set of trees.
2587 Returns nil if kill does not start with a headline, or if the first
2588 headline level is not the largest headline level in the tree.
2589 So this will actually accept several entries of equal levels as well,
2590 which is OK for `org-paste-subtree'.
2591 If optional TXT is given, check this string instead of the current kill."
2592 (let* ((kill (or txt (current-kill 0) ""))
2593 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2594 (- (match-end 0) (match-beginning 0))))
2595 (re (concat "^" outline-regexp))
2596 (start 1))
2597 (if (not start-level)
2598 nil ;; does not even start with a heading
2599 (catch 'exit
2600 (while (setq start (string-match re kill (1+ start)))
2601 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2602 (throw 'exit nil)))
2603 t))))
2604
2605 (defun org-archive-subtree ()
2606 "Move the current subtree to the archive.
2607 The archive can be a certain top-level heading in the current file, or in
2608 a different file. The tree will be moved to that location, the subtree
2609 heading be marked DONE, and the current time will be added."
2610 (interactive)
2611 ;; Save all relevant TODO keyword-relatex variables
2612 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2613 (tr-org-todo-keywords org-todo-keywords)
2614 (tr-org-todo-interpretation org-todo-interpretation)
2615 (tr-org-done-string org-done-string)
2616 (tr-org-todo-regexp org-todo-regexp)
2617 (tr-org-todo-line-regexp org-todo-line-regexp)
2618 (this-buffer (current-buffer))
2619 file heading buffer level newfile-p)
2620 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2621 (progn
2622 (setq file (format (match-string 1 org-archive-location)
2623 (file-name-nondirectory (buffer-file-name)))
2624 heading (match-string 2 org-archive-location)))
2625 (error "Invalid `org-archive-location'"))
2626 (if (> (length file) 0)
2627 (setq newfile-p (not (file-exists-p file))
2628 buffer (find-file-noselect file))
2629 (setq buffer (current-buffer)))
2630 (unless buffer
2631 (error "Cannot access file \"%s\"" file))
2632 (if (and (> (length heading) 0)
2633 (string-match "^\\*+" heading))
2634 (setq level (match-end 0))
2635 (setq heading nil level 0))
2636 (save-excursion
2637 (org-copy-subtree) ; We first only copy, in case something goes wrong
2638 (set-buffer buffer)
2639 ;; Enforce org-mode for the archive buffer
2640 (if (not (eq major-mode 'org-mode))
2641 ;; Force the mode for future visits.
2642 (let ((org-insert-mode-line-in-empty-file t))
2643 (call-interactively 'org-mode)))
2644 (when newfile-p
2645 (goto-char (point-max))
2646 (insert (format "\nArchived entries from file %s\n\n"
2647 (buffer-file-name this-buffer))))
2648 ;; Force the TODO keywords of the original buffer
2649 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2650 (org-todo-keywords tr-org-todo-keywords)
2651 (org-todo-interpretation tr-org-todo-interpretation)
2652 (org-done-string tr-org-done-string)
2653 (org-todo-regexp tr-org-todo-regexp)
2654 (org-todo-line-regexp tr-org-todo-line-regexp))
2655 (goto-char (point-min))
2656 (if heading
2657 (progn
2658 (if (re-search-forward
2659 (concat "\\(^\\|\r\\)"
2660 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2661 nil t)
2662 (goto-char (match-end 0))
2663 ;; Heading not found, just insert it at the end
2664 (goto-char (point-max))
2665 (or (bolp) (insert "\n"))
2666 (insert "\n" heading "\n")
2667 (end-of-line 0))
2668 ;; Make the heading visible, and the following as well
2669 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2670 (if (re-search-forward
2671 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2672 nil t)
2673 (progn (goto-char (match-beginning 0)) (insert "\n")
2674 (beginning-of-line 0))
2675 (goto-char (point-max)) (insert "\n")))
2676 (goto-char (point-max)) (insert "\n"))
2677 ;; Paste
2678 (org-paste-subtree (1+ level))
2679 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2680 (if org-archive-mark-done
2681 (org-todo (length org-todo-keywords)))
2682 ;; Move cursor to right after the TODO keyword
2683 (when org-archive-stamp-time
2684 (beginning-of-line 1)
2685 (looking-at org-todo-line-regexp)
2686 (goto-char (or (match-end 2) (match-beginning 3)))
2687 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2688 (current-time))
2689 ")"))
2690 ;; Save the buffer, if it is not the same buffer.
2691 (if (not (eq this-buffer buffer)) (save-buffer))))
2692 ;; Here we are back in the original buffer. Everything seems to have
2693 ;; worked. So now cut the tree and finish up.
2694 (org-cut-subtree)
2695 (if (looking-at "[ \t]*$") (kill-line))
2696 (message "Subtree archived %s"
2697 (if (eq this-buffer buffer)
2698 (concat "under heading: " heading)
2699 (concat "in file: " (abbreviate-file-name file))))))
2700
2701 ;;; Completion
2702
2703 (defun org-complete (&optional arg)
2704 "Perform completion on word at point.
2705 At the beginning of a headline, this completes TODO keywords as given in
2706 `org-todo-keywords'.
2707 If the current word is preceded by a backslash, completes the TeX symbols
2708 that are supported for HTML support.
2709 If the current word is preceded by \"#+\", completes special words for
2710 setting file options.
2711 At all other locations, this simply calls `ispell-complete-word'."
2712 (interactive "P")
2713 (catch 'exit
2714 (let* ((end (point))
2715 (beg (save-excursion
2716 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2717 (skip-chars-backward "a-zA-Z0-9_:$")
2718 (point)))
2719 (texp (equal (char-before beg) ?\\))
2720 (form (equal (char-before beg) ?=))
2721 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2722 beg)
2723 "#+"))
2724 (pattern (buffer-substring-no-properties beg end))
2725 (completion-ignore-case opt)
2726 (type nil)
2727 (table (cond
2728 (opt
2729 (setq type :opt)
2730 (mapcar (lambda (x)
2731 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2732 (cons (match-string 2 x) (match-string 1 x)))
2733 (org-split-string (org-get-current-options) "\n")))
2734 (texp
2735 (setq type :tex)
2736 org-html-entities)
2737 (form
2738 (setq type :form)
2739 '(("sum") ("sumv") ("sumh")))
2740 ((string-match "\\`\\*+[ \t]*\\'"
2741 (buffer-substring (point-at-bol) beg))
2742 (setq type :todo)
2743 (mapcar 'list org-todo-keywords))
2744 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2745 (completion (try-completion pattern table)))
2746 (cond ((eq completion t)
2747 (if (equal type :opt)
2748 (insert (substring (cdr (assoc (upcase pattern) table))
2749 (length pattern)))))
2750 ((null completion)
2751 (message "Can't find completion for \"%s\"" pattern)
2752 (ding))
2753 ((not (string= pattern completion))
2754 (delete-region beg end)
2755 (if (string-match " +$" completion)
2756 (setq completion (replace-match "" t t completion)))
2757 (insert completion)
2758 (if (get-buffer-window "*Completions*")
2759 (delete-window (get-buffer-window "*Completions*")))
2760 (if (and (eq type :todo)
2761 (assoc completion table))
2762 (insert " "))
2763 (if (and (equal type :opt) (assoc completion table))
2764 (message (substitute-command-keys
2765 "Press \\[org-complete] again to insert example settings"))))
2766 (t
2767 (message "Making completion list...")
2768 (let ((list (sort (all-completions pattern table) 'string<)))
2769 (with-output-to-temp-buffer "*Completions*"
2770 (display-completion-list list)))
2771 (message "Making completion list...%s" "done"))))))
2772
2773 ;;; Comments, TODO and DEADLINE
2774
2775 (defun org-toggle-comment ()
2776 "Change the COMMENT state of an entry."
2777 (interactive)
2778 (save-excursion
2779 (org-back-to-heading)
2780 (if (looking-at (concat outline-regexp
2781 "\\( +\\<" org-comment-string "\\>\\)"))
2782 (replace-match "" t t nil 1)
2783 (if (looking-at outline-regexp)
2784 (progn
2785 (goto-char (match-end 0))
2786 (insert " " org-comment-string))))))
2787
2788 (defvar org-last-todo-state-is-todo nil
2789 "This is non-nil when the last TODO state change led to a TODO state.
2790 If the last change removed the TODO tag or switched to DONE, then
2791 this is nil.")
2792
2793 (defun org-todo (&optional arg)
2794 "Change the TODO state of an item.
2795 The state of an item is given by a keyword at the start of the heading,
2796 like
2797 *** TODO Write paper
2798 *** DONE Call mom
2799
2800 The different keywords are specified in the variable `org-todo-keywords'. By
2801 default the available states are \"TODO\" and \"DONE\".
2802 So for this example: when the item starts with TODO, it is changed to DONE.
2803 When it starts with DONE, the DONE is removed. And when neither TODO nor
2804 DONE are present, add TODO at the beginning of the heading.
2805
2806 With prefix arg, use completion to determined the new state. With numeric
2807 prefix arg, switch to that state."
2808 (interactive "P")
2809 (save-excursion
2810 (org-back-to-heading)
2811 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2812 (or (looking-at (concat " +" org-todo-regexp " *"))
2813 (looking-at " *"))
2814 (let* ((this (match-string 1))
2815 (completion-ignore-case t)
2816 (member (member this org-todo-keywords))
2817 (tail (cdr member))
2818 (state (cond
2819 ((equal arg '(4))
2820 ;; Read a state with completion
2821 (completing-read "State: " (mapcar (lambda(x) (list x))
2822 org-todo-keywords)
2823 nil t))
2824 (arg
2825 ;; user requests a specific state
2826 (nth (1- (prefix-numeric-value arg))
2827 org-todo-keywords))
2828 ((null member) (car org-todo-keywords))
2829 ((null tail) nil) ;; -> first entry
2830 ((eq org-todo-interpretation 'sequence)
2831 (car tail))
2832 ((memq org-todo-interpretation '(type priority))
2833 (if (eq this-command last-command)
2834 (car tail)
2835 (if (> (length tail) 0) org-done-string nil)))
2836 (t nil)))
2837 (next (if state (concat " " state " ") " ")))
2838 (replace-match next t t)
2839 (setq org-last-todo-state-is-todo
2840 (not (equal state org-done-string)))
2841 (run-hooks 'org-after-todo-state-change-hook)))
2842 ;; Fixup cursor location if close to the keyword
2843 (if (and (outline-on-heading-p)
2844 (not (bolp))
2845 (save-excursion (beginning-of-line 1)
2846 (looking-at org-todo-line-regexp))
2847 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2848 (progn
2849 (goto-char (or (match-end 2) (match-end 1)))
2850 (just-one-space))))
2851
2852 (defun org-show-todo-tree (arg)
2853 "Make a compact tree which shows all headlines marked with TODO.
2854 The tree will show the lines where the regexp matches, and all higher
2855 headlines above the match."
2856 (interactive "P")
2857 (let ((case-fold-search nil)
2858 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2859 (message "%d TODO entries found"
2860 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2861
2862 (defun org-deadline ()
2863 "Insert the DEADLINE: string to make a deadline.
2864 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2865 to modify it to the correct date."
2866 (interactive)
2867 (insert
2868 org-deadline-string " "
2869 (format-time-string (car org-time-stamp-formats)
2870 (org-read-date nil 'to-time)))
2871 (message (substitute-command-keys
2872 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2873
2874 (defun org-schedule ()
2875 "Insert the SCHEDULED: string to schedule a TODO item.
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-scheduled-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
2887 (defun org-occur (regexp &optional callback)
2888 "Make a compact tree which shows all matches of REGEXP.
2889 The tree will show the lines where the regexp matches, and all higher
2890 headlines above the match. It will also show the heading after the match,
2891 to make sure editing the matching entry is easy.
2892 if CALLBACK is non-nil, it is a function which is called to confirm
2893 that the match should indeed be shown."
2894 (interactive "sRegexp: ")
2895 (setq regexp (org-check-occur-regexp regexp))
2896 (let ((cnt 0))
2897 (save-excursion
2898 (goto-char (point-min))
2899 (hide-sublevels 1)
2900 (while (re-search-forward regexp nil t)
2901 (when (or (not callback)
2902 (funcall callback))
2903 (setq cnt (1+ cnt))
2904 (org-show-hierarchy-above))))
2905 (run-hooks 'org-occur-hook)
2906 (if (interactive-p)
2907 (message "%d match(es) for regexp %s" cnt regexp))
2908 cnt))
2909
2910 (defun org-show-hierarchy-above ()
2911 "Make sure point and the headings hierarchy above is visible."
2912 (if (org-on-heading-p t)
2913 (org-flag-heading nil) ; only show the heading
2914 (org-show-hidden-entry)) ; show entire entry
2915 (save-excursion
2916 (and org-show-following-heading
2917 (outline-next-heading)
2918 (org-flag-heading nil))) ; show the next heading
2919 (save-excursion ; show all higher headings
2920 (while (condition-case nil
2921 (progn (org-up-heading-all 1) t)
2922 (error nil))
2923 (org-flag-heading nil))))
2924
2925 ;;; Priorities
2926
2927 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2928 "Regular expression matching the priority indicator.")
2929
2930 (defvar org-remove-priority-next-time nil)
2931
2932 (defun org-priority-up ()
2933 "Increase the priority of the current item."
2934 (interactive)
2935 (org-priority 'up))
2936
2937 (defun org-priority-down ()
2938 "Decrease the priority of the current item."
2939 (interactive)
2940 (org-priority 'down))
2941
2942 (defun org-priority (&optional action)
2943 "Change the priority of an item by ARG.
2944 ACTION can be set, up, or down."
2945 (interactive)
2946 (setq action (or action 'set))
2947 (let (current new news have remove)
2948 (save-excursion
2949 (org-back-to-heading)
2950 (if (looking-at org-priority-regexp)
2951 (setq current (string-to-char (match-string 2))
2952 have t)
2953 (setq current org-default-priority))
2954 (cond
2955 ((eq action 'set)
2956 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2957 (setq new (read-char-exclusive))
2958 (cond ((equal new ?\ ) (setq remove t))
2959 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2960 (error "Priority must be between `%c' and `%c'"
2961 ?A org-lowest-priority))))
2962 ((eq action 'up)
2963 (setq new (1- current)))
2964 ((eq action 'down)
2965 (setq new (1+ current)))
2966 (t (error "Invalid action")))
2967 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2968 (setq news (format "%c" new))
2969 (if have
2970 (if remove
2971 (replace-match "" t t nil 1)
2972 (replace-match news t t nil 2))
2973 (if remove
2974 (error "No priority cookie found in line")
2975 (looking-at org-todo-line-regexp)
2976 (if (match-end 2)
2977 (progn
2978 (goto-char (match-end 2))
2979 (insert " [#" news "]"))
2980 (goto-char (match-beginning 3))
2981 (insert "[#" news "] ")))))
2982 (if remove
2983 (message "Priority removed")
2984 (message "Priority of current item set to %s" news))))
2985
2986
2987 (defun org-get-priority (s)
2988 "Find priority cookie and return priority."
2989 (save-match-data
2990 (if (not (string-match org-priority-regexp s))
2991 (* 1000 (- org-lowest-priority org-default-priority))
2992 (* 1000 (- org-lowest-priority
2993 (string-to-char (match-string 2 s)))))))
2994
2995 ;;; Timestamps
2996
2997 (defvar org-last-changed-timestamp nil)
2998
2999 (defun org-time-stamp (arg)
3000 "Prompt for a date/time and insert a time stamp.
3001 If the user specifies a time like HH:MM, or if this command is called
3002 with a prefix argument, the time stamp will contain date and time.
3003 Otherwise, only the date will be included. All parts of a date not
3004 specified by the user will be filled in from the current date/time.
3005 So if you press just return without typing anything, the time stamp
3006 will represent the current date/time. If there is already a timestamp
3007 at the cursor, it will be modified."
3008 (interactive "P")
3009 (let ((fmt (if arg (cdr org-time-stamp-formats)
3010 (car org-time-stamp-formats)))
3011 (org-time-was-given nil)
3012 time)
3013 (cond
3014 ((and (org-at-timestamp-p)
3015 (eq last-command 'org-time-stamp)
3016 (eq this-command 'org-time-stamp))
3017 (insert "--")
3018 (setq time (let ((this-command this-command))
3019 (org-read-date arg 'totime)))
3020 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3021 (insert (format-time-string fmt time)))
3022 ((org-at-timestamp-p)
3023 (setq time (let ((this-command this-command))
3024 (org-read-date arg 'totime)))
3025 (and (org-at-timestamp-p) (replace-match
3026 (setq org-last-changed-timestamp
3027 (format-time-string fmt time))
3028 t t))
3029 (message "Timestamp updated"))
3030 (t
3031 (setq time (let ((this-command this-command))
3032 (org-read-date arg 'totime)))
3033 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3034 (insert (format-time-string fmt time))))))
3035
3036 ;;; FIXME: Make the function take "Fri" as "next friday"
3037 (defun org-read-date (&optional with-time to-time)
3038 "Read a date and make things smooth for the user.
3039 The prompt will suggest to enter an ISO date, but you can also enter anything
3040 which will at least partially be understood by `parse-time-string'.
3041 Unrecognized parts of the date will default to the current day, month ,year,
3042 hour and minute. For example,
3043 3-2-5 --> 2003-02-05
3044 feb 15 --> currentyear-02-15
3045 sep 12 9 --> 2009-09-12
3046 12:45 --> today 12:45
3047 22 sept 0:34 --> currentyear-09-22 0:34
3048 12 --> currentyear-currentmonth-12
3049 etc.
3050 The function understands only English month and weekday abbreviations,
3051 but this can be configured with the variables `parse-time-months' and
3052 `parse-time-weekdays'.
3053
3054 While prompting, a calendar is popped up - you can also select the
3055 date with the mouse (button 1). The calendar shows a period of three
3056 month. To scroll it to other months, use the keys `>' and `<'.
3057 If you don't like the calendar, turn it off with
3058 \(setq org-popup-calendar-for-date-prompt nil).
3059
3060 With optional argument TO-TIME, the date will immediately be converted
3061 to an internal time.
3062 With an optional argument WITH-TIME, the prompt will suggest to also
3063 insert a time. Note that when WITH-TIME is not set, you can still
3064 enter a time, and this function will inform the calling routine about
3065 this change. The calling routine may then choose to change the format
3066 used to insert the time stamp into the buffer to include the time."
3067 (let* ((default-time
3068 ;; Default time is either today, or, when entering a range,
3069 ;; the range start.
3070 (if (save-excursion
3071 (re-search-backward
3072 (concat org-ts-regexp "--\\=")
3073 (- (point) 20) t))
3074 (apply
3075 'encode-time
3076 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3077 (parse-time-string (match-string 1))))
3078 (current-time)))
3079 (timestr (format-time-string
3080 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3081 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3082 ans ans1 ans2
3083 second minute hour day month year tl)
3084
3085 (if org-popup-calendar-for-date-prompt
3086 ;; Also show a calendar for date selection
3087 ;; Copied (with modifications) from planner.el by John Wiegley
3088 (save-excursion
3089 (save-window-excursion
3090 (calendar)
3091 (calendar-forward-day (- (time-to-days default-time)
3092 (calendar-absolute-from-gregorian
3093 (calendar-current-date))))
3094 (let* ((old-map (current-local-map))
3095 (map (copy-keymap calendar-mode-map))
3096 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3097 (define-key map (kbd "RET") 'org-calendar-select)
3098 (define-key map (if org-xemacs-p [button1] [mouse-1])
3099 'org-calendar-select)
3100 (define-key minibuffer-local-map [(meta shift left)]
3101 (lambda () (interactive)
3102 (org-eval-in-calendar '(calendar-backward-month 1))))
3103 (define-key minibuffer-local-map [(meta shift right)]
3104 (lambda () (interactive)
3105 (org-eval-in-calendar '(calendar-forward-month 1))))
3106 (define-key minibuffer-local-map [(shift up)]
3107 (lambda () (interactive)
3108 (org-eval-in-calendar '(calendar-backward-week 1))))
3109 (define-key minibuffer-local-map [(shift down)]
3110 (lambda () (interactive)
3111 (org-eval-in-calendar '(calendar-forward-week 1))))
3112 (define-key minibuffer-local-map [(shift left)]
3113 (lambda () (interactive)
3114 (org-eval-in-calendar '(calendar-backward-day 1))))
3115 (define-key minibuffer-local-map [(shift right)]
3116 (lambda () (interactive)
3117 (org-eval-in-calendar '(calendar-forward-day 1))))
3118 (define-key minibuffer-local-map ">"
3119 (lambda () (interactive)
3120 (org-eval-in-calendar '(scroll-calendar-left 1))))
3121 (define-key minibuffer-local-map "<"
3122 (lambda () (interactive)
3123 (org-eval-in-calendar '(scroll-calendar-right 1))))
3124 (unwind-protect
3125 (progn
3126 (use-local-map map)
3127 (setq ans (read-string prompt "" nil nil))
3128 (setq ans (or ans1 ans2 ans)))
3129 (use-local-map old-map)))))
3130 ;; Naked prompt only
3131 (setq ans (read-string prompt "" nil timestr)))
3132
3133 (if (string-match
3134 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3135 (progn
3136 (setq year (if (match-end 2)
3137 (string-to-number (match-string 2 ans))
3138 (string-to-number (format-time-string "%Y")))
3139 month (string-to-number (match-string 3 ans))
3140 day (string-to-number (match-string 4 ans)))
3141 (if (< year 100) (setq year (+ 2000 year)))
3142 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3143 t t ans))))
3144 (setq tl (parse-time-string ans)
3145 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3146 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3147 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3148 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3149 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3150 second (or (nth 0 tl) 0))
3151 (if (and (boundp 'org-time-was-given)
3152 (nth 2 tl))
3153 (setq org-time-was-given t))
3154 (if (< year 100) (setq year (+ 2000 year)))
3155 (if to-time
3156 (encode-time second minute hour day month year)
3157 (if (or (nth 1 tl) (nth 2 tl))
3158 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3159 (format "%04d-%02d-%02d" year month day)))))
3160
3161 (defun org-eval-in-calendar (form)
3162 "Eval FORM in the calendar window and return to current window.
3163 Also, store the cursor date in variable ans2."
3164 (let ((sw (selected-window)))
3165 (select-window (get-buffer-window "*Calendar*"))
3166 (eval form)
3167 (when (calendar-cursor-to-date)
3168 (let* ((date (calendar-cursor-to-date))
3169 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3170 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3171 (select-window sw)))
3172
3173 (defun org-calendar-select ()
3174 "Return to `org-read-date' with the date currently selected.
3175 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3176 (interactive)
3177 (when (calendar-cursor-to-date)
3178 (let* ((date (calendar-cursor-to-date))
3179 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3180 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3181 (if (active-minibuffer-window) (exit-minibuffer))))
3182
3183 (defun org-check-deadlines (ndays)
3184 "Check if there are any deadlines due or past due.
3185 A deadline is considered due if it happens within `org-deadline-warning-days'
3186 days from today's date. If the deadline appears in an entry marked DONE,
3187 it is not shown. The prefix arg NDAYS can be used to test that many
3188 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3189 (interactive "P")
3190 (let* ((org-warn-days
3191 (cond
3192 ((equal ndays '(4)) 100000)
3193 (ndays (prefix-numeric-value ndays))
3194 (t org-deadline-warning-days)))
3195 (case-fold-search nil)
3196 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3197 (callback
3198 (lambda ()
3199 (and (let ((d1 (time-to-days (current-time)))
3200 (d2 (time-to-days
3201 (org-time-string-to-time (match-string 1)))))
3202 (< (- d2 d1) org-warn-days))
3203 (not (org-entry-is-done-p))))))
3204 (message "%d deadlines past-due or due within %d days"
3205 (org-occur regexp callback)
3206 org-warn-days)))
3207
3208 (defun org-evaluate-time-range (&optional to-buffer)
3209 "Evaluate a time range by computing the difference between start and end.
3210 Normally the result is just printed in the echo area, but with prefix arg
3211 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3212 If the time range is actually in a table, the result is inserted into the
3213 next column.
3214 For time difference computation, a year is assumed to be exactly 365
3215 days in order to avoid rounding problems."
3216 (interactive "P")
3217 (save-excursion
3218 (unless (org-at-date-range-p)
3219 (goto-char (point-at-bol))
3220 (re-search-forward org-tr-regexp (point-at-eol) t))
3221 (if (not (org-at-date-range-p))
3222 (error "Not at a time-stamp range, and none found in current line")))
3223 (let* ((ts1 (match-string 1))
3224 (ts2 (match-string 2))
3225 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3226 (match-end (match-end 0))
3227 (time1 (org-time-string-to-time ts1))
3228 (time2 (org-time-string-to-time ts2))
3229 (t1 (time-to-seconds time1))
3230 (t2 (time-to-seconds time2))
3231 (diff (abs (- t2 t1)))
3232 (negative (< (- t2 t1) 0))
3233 ;; (ys (floor (* 365 24 60 60)))
3234 (ds (* 24 60 60))
3235 (hs (* 60 60))
3236 (fy "%dy %dd %02d:%02d")
3237 (fy1 "%dy %dd")
3238 (fd "%dd %02d:%02d")
3239 (fd1 "%dd")
3240 (fh "%02d:%02d")
3241 y d h m align)
3242 ;; FIXME: Should I re-introduce years, make year refer to same date?
3243 ;; This would be the only useful way to have years, actually.
3244 (if havetime
3245 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3246 y 0
3247 d (floor (/ diff ds)) diff (mod diff ds)
3248 h (floor (/ diff hs)) diff (mod diff hs)
3249 m (floor (/ diff 60)))
3250 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3251 y 0
3252 d (floor (+ (/ diff ds) 0.5))
3253 h 0 m 0))
3254 (if (not to-buffer)
3255 (message (org-make-tdiff-string y d h m))
3256 (when (org-at-table-p)
3257 (goto-char match-end)
3258 (setq align t)
3259 (and (looking-at " *|") (goto-char (match-end 0))))
3260 (if (looking-at
3261 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3262 (replace-match ""))
3263 (if negative (insert " -"))
3264 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3265 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3266 (insert " " (format fh h m))))
3267 (if align (org-table-align))
3268 (message "Time difference inserted"))))
3269
3270 (defun org-make-tdiff-string (y d h m)
3271 (let ((fmt "")
3272 (l nil))
3273 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3274 l (push y l)))
3275 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3276 l (push d l)))
3277 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3278 l (push h l)))
3279 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3280 l (push m l)))
3281 (apply 'format fmt (nreverse l))))
3282
3283 (defun org-time-string-to-time (s)
3284 (apply 'encode-time (org-parse-time-string s)))
3285
3286 (defun org-parse-time-string (s &optional nodefault)
3287 "Parse the standard Org-mode time string.
3288 This should be a lot faster than the normal `parse-time-string'.
3289 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3290 hour and minute fields will be nil if not given."
3291 (if (string-match org-ts-regexp1 s)
3292 (list 0
3293 (if (or (match-beginning 8) (not nodefault))
3294 (string-to-number (or (match-string 8 s) "0")))
3295 (if (or (match-beginning 7) (not nodefault))
3296 (string-to-number (or (match-string 7 s) "0")))
3297 (string-to-number (match-string 4 s))
3298 (string-to-number (match-string 3 s))
3299 (string-to-number (match-string 2 s))
3300 nil nil nil)
3301 (make-list 9 0)))
3302
3303 (defun org-timestamp-up (&optional arg)
3304 "Increase the date item at the cursor by one.
3305 If the cursor is on the year, change the year. If it is on the month or
3306 the day, change that.
3307 With prefix ARG, change by that many units."
3308 (interactive "p")
3309 (org-timestamp-change (prefix-numeric-value arg)))
3310
3311 (defun org-timestamp-down (&optional arg)
3312 "Decrease the date item at the cursor by one.
3313 If the cursor is on the year, change the year. If it is on the month or
3314 the day, change that.
3315 With prefix ARG, change by that many units."
3316 (interactive "p")
3317 (org-timestamp-change (- (prefix-numeric-value arg))))
3318
3319 (defun org-timestamp-up-day (&optional arg)
3320 "Increase the date in the time stamp by one day.
3321 With prefix ARG, change that many days."
3322 (interactive "p")
3323 (org-timestamp-change (prefix-numeric-value arg) 'day))
3324
3325 (defun org-timestamp-down-day (&optional arg)
3326 "Decrease the date in the time stamp by one day.
3327 With prefix ARG, change that many days."
3328 (interactive "p")
3329 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3330
3331 (defsubst org-pos-in-match-range (pos n)
3332 (and (match-beginning n)
3333 (<= (match-beginning n) pos)
3334 (>= (match-end n) pos)))
3335
3336 (defun org-at-timestamp-p ()
3337 "Determine if the cursor is or at a timestamp."
3338 (interactive)
3339 (let* ((tsr org-ts-regexp2)
3340 (pos (point))
3341 (ans (or (looking-at tsr)
3342 (save-excursion
3343 (skip-chars-backward "^<\n\r\t")
3344 (if (> (point) 1) (backward-char 1))
3345 (and (looking-at tsr)
3346 (> (- (match-end 0) pos) -1))))))
3347 (and (boundp 'org-ts-what)
3348 (setq org-ts-what
3349 (cond
3350 ((org-pos-in-match-range pos 2) 'year)
3351 ((org-pos-in-match-range pos 3) 'month)
3352 ((org-pos-in-match-range pos 7) 'hour)
3353 ((org-pos-in-match-range pos 8) 'minute)
3354 ((or (org-pos-in-match-range pos 4)
3355 (org-pos-in-match-range pos 5)) 'day)
3356 (t 'day))))
3357 ans))
3358
3359 (defun org-timestamp-change (n &optional what)
3360 "Change the date in the time stamp at point.
3361 The date will be changed by N times WHAT. WHAT can be `day', `month',
3362 `year', `minute', `second'. If WHAT is not given, the cursor position
3363 in the timestamp determines what will be changed."
3364 (let ((fmt (car org-time-stamp-formats))
3365 org-ts-what
3366 (pos (point))
3367 ts time time0)
3368 (if (not (org-at-timestamp-p))
3369 (error "Not at a timestamp"))
3370 (setq org-ts-what (or what org-ts-what))
3371 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3372 (- (match-end 0) (match-beginning 0))))
3373 1)
3374 (cdr org-time-stamp-formats)
3375 (car org-time-stamp-formats)))
3376 (setq ts (match-string 0))
3377 (replace-match "")
3378 (setq time0 (org-parse-time-string ts))
3379 (setq time
3380 (apply 'encode-time
3381 (append
3382 (list (or (car time0) 0))
3383 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3384 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3385 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3386 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3387 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3388 (nthcdr 6 time0))))
3389 (if (eq what 'calendar)
3390 (let ((cal-date
3391 (save-excursion
3392 (save-match-data
3393 (set-buffer "*Calendar*")
3394 (calendar-cursor-to-date)))))
3395 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3396 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3397 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3398 (setcar time0 (or (car time0) 0))
3399 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3400 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3401 (setq time (apply 'encode-time time0))))
3402 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3403 (goto-char pos)
3404 ;; Try to recenter the calendar window, if any
3405 (if (and org-calendar-follow-timestamp-change
3406 (get-buffer-window "*Calendar*" t)
3407 (memq org-ts-what '(day month year)))
3408 (org-recenter-calendar (time-to-days time)))))
3409
3410 (defun org-recenter-calendar (date)
3411 "If the calendar is visible, recenter it to DATE."
3412 (let* ((win (selected-window))
3413 (cwin (get-buffer-window "*Calendar*" t)))
3414 (when cwin
3415 (select-window cwin)
3416 (calendar-goto-date (if (listp date) date
3417 (calendar-gregorian-from-absolute date)))
3418 (select-window win))))
3419
3420 (defun org-goto-calendar (&optional arg)
3421 "Go to the Emacs calendar at the current date.
3422 If there is a time stamp in the current line, go to that date.
3423 A prefix ARG can be used force the current date."
3424 (interactive "P")
3425 (let ((tsr org-ts-regexp) diff)
3426 (if (or (org-at-timestamp-p)
3427 (save-excursion
3428 (beginning-of-line 1)
3429 (looking-at (concat ".*" tsr))))
3430 (let ((d1 (time-to-days (current-time)))
3431 (d2 (time-to-days
3432 (org-time-string-to-time (match-string 1)))))
3433 (setq diff (- d2 d1))))
3434 (calendar)
3435 (calendar-goto-today)
3436 (if (and diff (not arg)) (calendar-forward-day diff))))
3437
3438 (defun org-date-from-calendar ()
3439 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3440 If there is already a time stamp at the cursor position, update it."
3441 (interactive)
3442 (org-timestamp-change 0 'calendar))
3443
3444 ;;; Agenda, and Diary Integration
3445
3446 ;;; Define the mode
3447
3448 (defvar org-agenda-mode-map (make-sparse-keymap)
3449 "Keymap for `org-agenda-mode'.")
3450
3451 (defvar org-agenda-menu)
3452 (defvar org-agenda-follow-mode nil)
3453 (defvar org-agenda-buffer-name "*Org Agenda*")
3454 (defvar org-agenda-redo-command nil)
3455 (defvar org-agenda-mode-hook nil)
3456
3457 ;;;###autoload
3458 (defun org-agenda-mode ()
3459 "Mode for time-sorted view on action items in Org-mode files.
3460
3461 The following commands are available:
3462
3463 \\{org-agenda-mode-map}"
3464 (interactive)
3465 (kill-all-local-variables)
3466 (setq major-mode 'org-agenda-mode)
3467 (setq mode-name "Org-Agenda")
3468 (use-local-map org-agenda-mode-map)
3469 (easy-menu-add org-agenda-menu)
3470 (if org-startup-truncated (setq truncate-lines t))
3471 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3472 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3473 (setq org-agenda-follow-mode nil)
3474 (easy-menu-change
3475 '("Agenda") "Agenda Files"
3476 (append
3477 (list
3478 ["Edit File List" (customize-variable 'org-agenda-files) t]
3479 "--")
3480 (mapcar 'org-file-menu-entry org-agenda-files)))
3481 (org-agenda-set-mode-name)
3482 (apply
3483 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3484 org-agenda-mode-hook))
3485
3486 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3487 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3488 (define-key org-agenda-mode-map " " 'org-agenda-show)
3489 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3490 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3491 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3492 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3493 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3494 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3495 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3496 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3497 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3498
3499 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3500 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3501 (while l (define-key org-agenda-mode-map
3502 (int-to-string (pop l)) 'digit-argument)))
3503
3504 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3505 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3506 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3507 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3508 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3509 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3510 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3511 (define-key org-agenda-mode-map "n" 'next-line)
3512 (define-key org-agenda-mode-map "p" 'previous-line)
3513 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3514 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3515 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3516 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3517 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3518 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3519 (eval-after-load "calendar"
3520 '(define-key calendar-mode-map org-calendar-to-agenda-key
3521 'org-calendar-goto-agenda))
3522 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3523 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3524 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3525 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3526 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3527 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3528 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3529 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3530 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3531 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3532 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3533 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3534 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3535
3536 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3537 "Local keymap for agenda entries from Org-mode.")
3538
3539 (define-key org-agenda-keymap
3540 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3541 (define-key org-agenda-keymap
3542 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3543
3544 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3545 '("Agenda"
3546 ("Agenda Files")
3547 "--"
3548 ["Show" org-agenda-show t]
3549 ["Go To (other window)" org-agenda-goto t]
3550 ["Go To (one window)" org-agenda-switch-to t]
3551 ["Follow Mode" org-agenda-follow-mode
3552 :style toggle :selected org-agenda-follow-mode :active t]
3553 "--"
3554 ["Cycle TODO" org-agenda-todo t]
3555 ("Reschedule"
3556 ["Reschedule +1 day" org-agenda-date-later t]
3557 ["Reschedule -1 day" org-agenda-date-earlier t]
3558 "--"
3559 ["Reschedule to ..." org-agenda-date-prompt t])
3560 ("Priority"
3561 ["Set Priority" org-agenda-priority t]
3562 ["Increase Priority" org-agenda-priority-up t]
3563 ["Decrease Priority" org-agenda-priority-down t]
3564 ["Show Priority" org-agenda-show-priority t])
3565 "--"
3566 ["Rebuild buffer" org-agenda-redo t]
3567 ["Goto Today" org-agenda-goto-today t]
3568 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3569 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3570 "--"
3571 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3572 :style radio :selected (equal org-agenda-ndays 1)]
3573 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3574 :style radio :selected (equal org-agenda-ndays 7)]
3575 "--"
3576 ["Include Diary" org-agenda-toggle-diary
3577 :style toggle :selected org-agenda-include-diary :active t]
3578 ["Use Time Grid" org-agenda-toggle-time-grid
3579 :style toggle :selected org-agenda-use-time-grid :active t]
3580 "--"
3581 ["New Diary Entry" org-agenda-diary-entry t]
3582 ("Calendar Commands"
3583 ["Goto Calendar" org-agenda-goto-calendar t]
3584 ["Phases of the Moon" org-agenda-phases-of-moon t]
3585 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3586 ["Holidays" org-agenda-holidays t]
3587 ["Convert" org-agenda-convert-date t])
3588 "--"
3589 ["Quit" org-agenda-quit t]
3590 ["Exit and Release Buffers" org-agenda-exit t]
3591 ))
3592
3593 (defvar org-agenda-markers nil
3594 "List of all currently active markers created by `org-agenda'.")
3595 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3596 "Creation time of the last agenda marker.")
3597
3598 (defun org-agenda-new-marker (&optional pos)
3599 "Return a new agenda marker.
3600 Org-mode keeps a list of these markers and resets them when they are
3601 no longer in use."
3602 (let ((m (copy-marker (or pos (point)))))
3603 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3604 (push m org-agenda-markers)
3605 m))
3606
3607 (defun org-agenda-maybe-reset-markers (&optional force)
3608 "Reset markers created by `org-agenda'. But only if they are old enough."
3609 (if (or force
3610 (> (- (time-to-seconds (current-time))
3611 org-agenda-last-marker-time)
3612 5))
3613 (while org-agenda-markers
3614 (move-marker (pop org-agenda-markers) nil))))
3615
3616 (defvar org-agenda-new-buffers nil
3617 "Buffers created to visit agenda files.")
3618
3619 (defun org-get-agenda-file-buffer (file)
3620 "Get a buffer visiting FILE. If the buffer needs to be created, add
3621 it to the list of buffers which might be released later."
3622 (let ((buf (find-buffer-visiting file)))
3623 (if buf
3624 buf ; just return it
3625 ;; Make a new buffer and remember it
3626 (setq buf (find-file-noselect file))
3627 (if buf (push buf org-agenda-new-buffers))
3628 buf)))
3629
3630 (defun org-release-buffers (blist)
3631 "Release all buffers in list, asking the user for confirmation when needed.
3632 When a buffer is unmodified, it is just killed. When modified, it is saved
3633 \(if the user agrees) and then killed."
3634 (let (buf file)
3635 (while (setq buf (pop blist))
3636 (setq file (buffer-file-name buf))
3637 (when (and (buffer-modified-p buf)
3638 file
3639 (y-or-n-p (format "Save file %s? " file)))
3640 (with-current-buffer buf (save-buffer)))
3641 (kill-buffer buf))))
3642
3643 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3644
3645 (defun org-timeline (&optional include-all)
3646 "Show a time-sorted view of the entries in the current org file.
3647 Only entries with a time stamp of today or later will be listed. With
3648 one \\[universal-argument] prefix argument, past entries will also be listed.
3649 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3650 under the current date.
3651 If the buffer contains an active region, only check the region for
3652 dates."
3653 (interactive "P")
3654 (require 'calendar)
3655 (org-agenda-maybe-reset-markers 'force)
3656 (org-compile-prefix-format org-timeline-prefix-format)
3657 (let* ((dopast include-all)
3658 (dotodo (equal include-all '(16)))
3659 (entry (buffer-file-name))
3660 (org-agenda-files (list (buffer-file-name)))
3661 (date (calendar-current-date))
3662 (win (selected-window))
3663 (pos1 (point))
3664 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3665 (end (if (org-region-active-p) (region-end) (point-max)))
3666 (day-numbers (org-get-all-dates beg end 'no-ranges
3667 t)) ; always include today
3668 (today (time-to-days (current-time)))
3669 (org-respect-restriction t)
3670 (past t)
3671 s e rtn d)
3672 (setq org-agenda-redo-command
3673 (list 'progn
3674 (list 'switch-to-buffer-other-window (current-buffer))
3675 (list 'org-timeline (list 'quote include-all))))
3676 (if (not dopast)
3677 ;; Remove past dates from the list of dates.
3678 (setq day-numbers (delq nil (mapcar (lambda(x)
3679 (if (>= x today) x nil))
3680 day-numbers))))
3681 (switch-to-buffer-other-window
3682 (get-buffer-create org-agenda-buffer-name))
3683 (setq buffer-read-only nil)
3684 (erase-buffer)
3685 (org-agenda-mode) (setq buffer-read-only nil)
3686 (while (setq d (pop day-numbers))
3687 (if (and (>= d today)
3688 dopast
3689 past)
3690 (progn
3691 (setq past nil)
3692 (insert (make-string 79 ?-) "\n")))
3693 (setq date (calendar-gregorian-from-absolute d))
3694 (setq s (point))
3695 (if dotodo
3696 (setq rtn (org-agenda-get-day-entries
3697 entry date :todo :timestamp))
3698 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3699 (if (or rtn (equal d today))
3700 (progn
3701 (insert (calendar-day-name date) " "
3702 (number-to-string (extract-calendar-day date)) " "
3703 (calendar-month-name (extract-calendar-month date)) " "
3704 (number-to-string (extract-calendar-year date)) "\n")
3705 (put-text-property s (1- (point)) 'face
3706 'org-link)
3707 (if (equal d today)
3708 (put-text-property s (1- (point)) 'org-today t))
3709 (insert (org-finalize-agenda-entries rtn) "\n")
3710 (put-text-property s (1- (point)) 'day d))))
3711 (goto-char (point-min))
3712 (setq buffer-read-only t)
3713 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3714 (point-min)))
3715 (when (not org-select-timeline-window)
3716 (select-window win)
3717 (goto-char pos1))))
3718
3719 ;;;###autoload
3720 (defun org-agenda (&optional include-all start-day ndays)
3721 "Produce a weekly view from all files in variable `org-agenda-files'.
3722 The view will be for the current week, but from the overview buffer you
3723 will be able to go to other weeks.
3724 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3725 also be shown, under the current date.
3726 START-DAY defaults to TODAY, or to the most recent match for the weekday
3727 given in `org-agenda-start-on-weekday'.
3728 NDAYS defaults to `org-agenda-ndays'."
3729 (interactive "P")
3730 (org-agenda-maybe-reset-markers 'force)
3731 (org-compile-prefix-format org-agenda-prefix-format)
3732 (require 'calendar)
3733 (let* ((org-agenda-start-on-weekday
3734 (if (or (equal ndays 1)
3735 (and (null ndays) (equal 1 org-agenda-ndays)))
3736 nil org-agenda-start-on-weekday))
3737 (files (copy-sequence org-agenda-files))
3738 (win (selected-window))
3739 (today (time-to-days (current-time)))
3740 (sd (or start-day today))
3741 (start (if (or (null org-agenda-start-on-weekday)
3742 (< org-agenda-ndays 7))
3743 sd
3744 (let* ((nt (calendar-day-of-week
3745 (calendar-gregorian-from-absolute sd)))
3746 (n1 org-agenda-start-on-weekday)
3747 (d (- nt n1)))
3748 (- sd (+ (if (< d 0) 7 0) d)))))
3749 (day-numbers (list start))
3750 (inhibit-redisplay t)
3751 s e rtn rtnall file date d start-pos end-pos todayp nd)
3752 (setq org-agenda-redo-command
3753 (list 'org-agenda (list 'quote include-all) start-day ndays))
3754 ;; Make the list of days
3755 (setq ndays (or ndays org-agenda-ndays)
3756 nd ndays)
3757 (while (> ndays 1)
3758 (push (1+ (car day-numbers)) day-numbers)
3759 (setq ndays (1- ndays)))
3760 (setq day-numbers (nreverse day-numbers))
3761 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3762 (progn
3763 (delete-other-windows)
3764 (switch-to-buffer-other-window
3765 (get-buffer-create org-agenda-buffer-name))))
3766 (setq buffer-read-only nil)
3767 (erase-buffer)
3768 (org-agenda-mode) (setq buffer-read-only nil)
3769 (set (make-local-variable 'starting-day) (car day-numbers))
3770 (set (make-local-variable 'include-all-loc) include-all)
3771 (when (and (or include-all org-agenda-include-all-todo)
3772 (member today day-numbers))
3773 (setq files org-agenda-files
3774 rtnall nil)
3775 (while (setq file (pop files))
3776 (catch 'nextfile
3777 (org-check-agenda-file file)
3778 (setq date (calendar-gregorian-from-absolute today)
3779 rtn (org-agenda-get-day-entries
3780 file date :todo))
3781 (setq rtnall (append rtnall rtn))))
3782 (when rtnall
3783 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3784 (add-text-properties (point-min) (1- (point))
3785 (list 'face 'org-link))
3786 (insert (org-finalize-agenda-entries rtnall) "\n")))
3787 (while (setq d (pop day-numbers))
3788 (setq date (calendar-gregorian-from-absolute d)
3789 s (point))
3790 (if (or (setq todayp (= d today))
3791 (and (not start-pos) (= d sd)))
3792 (setq start-pos (point))
3793 (if (and start-pos (not end-pos))
3794 (setq end-pos (point))))
3795 (setq files org-agenda-files
3796 rtnall nil)
3797 (while (setq file (pop files))
3798 (catch 'nextfile
3799 (org-check-agenda-file file)
3800 (setq rtn (org-agenda-get-day-entries file date))
3801 (setq rtnall (append rtnall rtn))))
3802 (if org-agenda-include-diary
3803 (progn
3804 (require 'diary-lib)
3805 (setq rtn (org-get-entries-from-diary date))
3806 (setq rtnall (append rtnall rtn))))
3807 (if (or rtnall org-agenda-show-all-dates)
3808 (progn
3809 (insert (format "%-9s %2d %s %4d\n"
3810 (calendar-day-name date)
3811 (extract-calendar-day date)
3812 (calendar-month-name (extract-calendar-month date))
3813 (extract-calendar-year date)))
3814 (put-text-property s (1- (point)) 'face
3815 'org-link)
3816 (if rtnall (insert
3817 (org-finalize-agenda-entries ;; FIXME: condition needed
3818 (org-agenda-add-time-grid-maybe
3819 rtnall nd todayp))
3820 "\n"))
3821 (put-text-property s (1- (point)) 'day d))))
3822 (goto-char (point-min))
3823 (setq buffer-read-only t)
3824 (if org-fit-agenda-window
3825 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3826 (/ (frame-height) 2)))
3827 (unless (and (pos-visible-in-window-p (point-min))
3828 (pos-visible-in-window-p (point-max)))
3829 (goto-char (1- (point-max)))
3830 (recenter -1)
3831 (if (not (pos-visible-in-window-p (or start-pos 1)))
3832 (progn
3833 (goto-char (or start-pos 1))
3834 (recenter 1))))
3835 (goto-char (or start-pos 1))
3836 (if (not org-select-agenda-window) (select-window win))
3837 (message "")))
3838
3839 (defun org-check-agenda-file (file)
3840 "Make sure FILE exists. If not, ask user what to do."
3841 ;; FIXME: this does not correctly change the menus
3842 ;; Could probably be fixed by explicitly going to the buffer.
3843 (when (not (file-exists-p file))
3844 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3845 file)
3846 (let ((r (downcase (read-char-exclusive))))
3847 (cond
3848 ((equal r ?r)
3849 (org-remove-file file)
3850 (throw 'nextfile t))
3851 (t (error "Abort"))))))
3852
3853 (defun org-agenda-quit ()
3854 "Exit agenda by removing the window or the buffer."
3855 (interactive)
3856 (let ((buf (current-buffer)))
3857 (if (not (one-window-p)) (delete-window))
3858 (kill-buffer buf)
3859 (org-agenda-maybe-reset-markers 'force)))
3860
3861 (defun org-agenda-exit ()
3862 "Exit agenda by removing the window or the buffer.
3863 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3864 Org-mode buffers visited directly by the user will not be touched."
3865 (interactive)
3866 (org-release-buffers org-agenda-new-buffers)
3867 (setq org-agenda-new-buffers nil)
3868 (org-agenda-quit))
3869
3870 (defun org-agenda-redo ()
3871 "Rebuild Agenda."
3872 (interactive)
3873 (eval org-agenda-redo-command))
3874
3875 (defun org-agenda-goto-today ()
3876 "Go to today."
3877 (interactive)
3878 (if (boundp 'starting-day)
3879 (let ((cmd (car org-agenda-redo-command))
3880 (iall (nth 1 org-agenda-redo-command))
3881 (nday (nth 3 org-agenda-redo-command)))
3882 (eval (list cmd iall nil nday)))
3883 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3884 (point-min)))))
3885
3886 (defun org-agenda-later (arg)
3887 "Go forward in time by `org-agenda-ndays' days.
3888 With prefix ARG, go forward that many times `org-agenda-ndays'."
3889 (interactive "p")
3890 (unless (boundp 'starting-day)
3891 (error "Not allowed"))
3892 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3893 (+ starting-day (* arg org-agenda-ndays))))
3894
3895 (defun org-agenda-earlier (arg)
3896 "Go back in time by `org-agenda-ndays' days.
3897 With prefix ARG, go back that many times `org-agenda-ndays'."
3898 (interactive "p")
3899 (unless (boundp 'starting-day)
3900 (error "Not allowed"))
3901 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3902 (- starting-day (* arg org-agenda-ndays))))
3903
3904 (defun org-agenda-week-view ()
3905 "Switch to weekly view for agenda."
3906 (interactive)
3907 (unless (boundp 'starting-day)
3908 (error "Not allowed"))
3909 (setq org-agenda-ndays 7)
3910 (org-agenda include-all-loc
3911 (or (get-text-property (point) 'day)
3912 starting-day))
3913 (org-agenda-set-mode-name)
3914 (message "Switched to week view"))
3915
3916 (defun org-agenda-day-view ()
3917 "Switch to weekly view for agenda."
3918 (interactive)
3919 (unless (boundp 'starting-day)
3920 (error "Not allowed"))
3921 (setq org-agenda-ndays 1)
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 day view"))
3927
3928 (defun org-agenda-next-date-line (&optional arg)
3929 "Jump to the next line indicating a date in agenda buffer."
3930 (interactive "p")
3931 (beginning-of-line 1)
3932 (if (looking-at "^\\S-") (forward-char 1))
3933 (if (not (re-search-forward "^\\S-" nil t arg))
3934 (progn
3935 (backward-char 1)
3936 (error "No next date after this line in this buffer")))
3937 (goto-char (match-beginning 0)))
3938
3939 (defun org-agenda-previous-date-line (&optional arg)
3940 "Jump to the next line indicating a date in agenda buffer."
3941 (interactive "p")
3942 (beginning-of-line 1)
3943 (if (not (re-search-backward "^\\S-" nil t arg))
3944 (error "No previous date before this line in this buffer")))
3945
3946 ;; Initialize the highlight
3947 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3948 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3949 'face 'highlight)
3950
3951 (defun org-highlight (begin end &optional buffer)
3952 "Highlight a region with overlay."
3953 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3954 org-hl begin end (or buffer (current-buffer))))
3955
3956 (defun org-unhighlight ()
3957 "Detach overlay INDEX."
3958 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3959
3960
3961 (defun org-agenda-follow-mode ()
3962 "Toggle follow mode in an agenda buffer."
3963 (interactive)
3964 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3965 (org-agenda-set-mode-name)
3966 (message "Follow mode is %s"
3967 (if org-agenda-follow-mode "on" "off")))
3968
3969 (defun org-agenda-toggle-diary ()
3970 "Toggle follow mode in an agenda buffer."
3971 (interactive)
3972 (setq org-agenda-include-diary (not org-agenda-include-diary))
3973 (org-agenda-redo)
3974 (org-agenda-set-mode-name)
3975 (message "Diary inclusion turned %s"
3976 (if org-agenda-include-diary "on" "off")))
3977
3978 (defun org-agenda-toggle-time-grid ()
3979 "Toggle follow mode in an agenda buffer."
3980 (interactive)
3981 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3982 (org-agenda-redo)
3983 (org-agenda-set-mode-name)
3984 (message "Time-grid turned %s"
3985 (if org-agenda-use-time-grid "on" "off")))
3986
3987 (defun org-agenda-set-mode-name ()
3988 "Set the mode name to indicate all the small mode settings."
3989 (setq mode-name
3990 (concat "Org-Agenda"
3991 (if (equal org-agenda-ndays 1) " Day" "")
3992 (if (equal org-agenda-ndays 7) " Week" "")
3993 (if org-agenda-follow-mode " Follow" "")
3994 (if org-agenda-include-diary " Diary" "")
3995 (if org-agenda-use-time-grid " Grid" "")))
3996 (force-mode-line-update))
3997
3998 (defun org-agenda-post-command-hook ()
3999 (and (eolp) (not (bolp)) (backward-char 1))
4000 (if (and org-agenda-follow-mode
4001 (get-text-property (point) 'org-marker))
4002 (org-agenda-show)))
4003
4004 (defvar org-disable-diary nil) ;Dynamically-scoped param.
4005
4006 (defun org-get-entries-from-diary (date)
4007 "Get the (Emacs Calendar) diary entries for DATE."
4008 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4009 (diary-display-hook '(fancy-diary-display))
4010 (list-diary-entries-hook
4011 (cons 'org-diary-default-entry list-diary-entries-hook))
4012 entries
4013 (org-disable-diary t))
4014 (save-excursion
4015 (save-window-excursion
4016 (list-diary-entries date 1)))
4017 (if (not (get-buffer fancy-diary-buffer))
4018 (setq entries nil)
4019 (with-current-buffer fancy-diary-buffer
4020 (setq buffer-read-only nil)
4021 (if (= (point-max) 1)
4022 ;; No entries
4023 (setq entries nil)
4024 ;; Omit the date and other unnecessary stuff
4025 (org-agenda-cleanup-fancy-diary)
4026 ;; Add prefix to each line and extend the text properties
4027 (if (= (point-max) 1)
4028 (setq entries nil)
4029 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4030 (set-buffer-modified-p nil)
4031 (kill-buffer fancy-diary-buffer)))
4032 (when entries
4033 (setq entries (org-split-string entries "\n"))
4034 (setq entries
4035 (mapcar
4036 (lambda (x)
4037 (setq x (org-format-agenda-item "" x "Diary" 'time))
4038 ;; Extend the text properties to the beginning of the line
4039 (add-text-properties
4040 0 (length x)
4041 (text-properties-at (1- (length x)) x)
4042 x)
4043 x)
4044 entries)))))
4045
4046 (defun org-agenda-cleanup-fancy-diary ()
4047 "Remove unwanted stuff in buffer created by fancy-diary-display.
4048 This gets rid of the date, the underline under the date, and
4049 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4050 date. Itt also removes lines that contain only whitespace."
4051 (goto-char (point-min))
4052 (if (looking-at ".*?:[ \t]*")
4053 (progn
4054 (replace-match "")
4055 (re-search-forward "\n=+$" nil t)
4056 (replace-match "")
4057 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4058 (re-search-forward "\n=+$" nil t)
4059 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4060 (goto-char (point-min))
4061 (while (re-search-forward "^ +\n" nil t)
4062 (replace-match ""))
4063 (goto-char (point-min))
4064 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4065 (replace-match "")))
4066
4067 ;; Advise the add-to-diary-list function to allow org to jump to
4068 ;; diary entries. Wrapped into eval-after-load to avoid loading
4069 ;; advice unnecessarily
4070 (eval-after-load "diary-lib"
4071 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
4072 "Make the position visible."
4073 (if (and org-disable-diary ;; called from org-agenda
4074 (stringp string)
4075 (buffer-file-name))
4076 (add-text-properties
4077 0 (length string)
4078 (list 'mouse-face 'highlight
4079 'keymap org-agenda-keymap
4080 'help-echo
4081 (format
4082 "mouse-2 or RET jump to diary file %s"
4083 (abbreviate-file-name (buffer-file-name)))
4084 'org-agenda-diary-link t
4085 'org-marker (org-agenda-new-marker (point-at-bol)))
4086 string))))
4087
4088 (defun org-diary-default-entry ()
4089 "Add a dummy entry to the diary.
4090 Needed to avoid empty dates which mess up holiday display."
4091 ;; Catch the error if dealing with the new add-to-diary-alist
4092 (condition-case nil
4093 (add-to-diary-list original-date "Org-mode dummy" "")
4094 (error
4095 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
4096
4097 (defun org-add-file (&optional file)
4098 "Add current file to the list of files in variable `org-agenda-files'.
4099 These are the files which are being checked for agenda entries.
4100 Optional argument FILE means, use this file instead of the current.
4101 It is possible (but not recommended) to add this function to the
4102 `org-mode-hook'."
4103 (interactive)
4104 (catch 'exit
4105 (let* ((file (or file (buffer-file-name)
4106 (if (interactive-p)
4107 (error "Buffer is not visiting a file")
4108 (throw 'exit nil))))
4109 (true-file (file-truename file))
4110 (afile (abbreviate-file-name file))
4111 (present (delq nil (mapcar
4112 (lambda (x)
4113 (equal true-file (file-truename x)))
4114 org-agenda-files))))
4115 (if (not present)
4116 (progn
4117 (setq org-agenda-files
4118 (cons afile org-agenda-files))
4119 ;; Make sure custom.el does not end up with Org-mode
4120 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4121 (customize-save-variable 'org-agenda-files org-agenda-files))
4122 (org-install-agenda-files-menu)
4123 (message "Added file: %s" afile))
4124 (message "File was already in list: %s" afile)))))
4125
4126 (defun org-remove-file (&optional file)
4127 "Remove current file from the list of files in variable `org-agenda-files'.
4128 These are the files which are being checked for agenda entries.
4129 Optional argument FILE means, use this file instead of the current."
4130 (interactive)
4131 (let* ((file (or file (buffer-file-name)))
4132 (true-file (file-truename file))
4133 (afile (abbreviate-file-name file))
4134 (files (delq nil (mapcar
4135 (lambda (x)
4136 (if (equal true-file
4137 (file-truename x))
4138 nil x))
4139 org-agenda-files))))
4140 (if (not (= (length files) (length org-agenda-files)))
4141 (progn
4142 (setq org-agenda-files files)
4143 (customize-save-variable 'org-agenda-files org-agenda-files)
4144 (org-install-agenda-files-menu)
4145 (message "Removed file: %s" afile))
4146 (message "File was not in list: %s" afile))))
4147
4148 (defun org-file-menu-entry (file)
4149 (vector file (list 'find-file file) t))
4150
4151 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4152 "Return a list of all relevant day numbers from BEG to END buffer positions.
4153 If NO-RANGES is non-nil, include only the start and end dates of a range,
4154 not every single day in the range. If FORCE-TODAY is non-nil, make
4155 sure that TODAY is included in the list."
4156 (let (dates date day day1 day2 ts1 ts2)
4157 (if force-today
4158 (setq dates (list (time-to-days (current-time)))))
4159 (save-excursion
4160 (goto-char beg)
4161 (while (re-search-forward org-ts-regexp end t)
4162 (setq day (time-to-days (org-time-string-to-time
4163 (substring (match-string 1) 0 10))))
4164 (or (memq day dates) (push day dates)))
4165 (unless no-ranges
4166 (goto-char beg)
4167 (while (re-search-forward org-tr-regexp end t)
4168 (setq ts1 (substring (match-string 1) 0 10)
4169 ts2 (substring (match-string 2) 0 10)
4170 day1 (time-to-days (org-time-string-to-time ts1))
4171 day2 (time-to-days (org-time-string-to-time ts2)))
4172 (while (< (setq day1 (1+ day1)) day2)
4173 (or (memq day1 dates) (push day1 dates)))))
4174 (sort dates '<))))
4175
4176 ;;;###autoload
4177 (defun org-diary (&rest args)
4178 "Return diary information from org-files.
4179 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4180 It accesses org files and extracts information from those files to be
4181 listed in the diary. The function accepts arguments specifying what
4182 items should be listed. The following arguments are allowed:
4183
4184 :timestamp List the headlines of items containing a date stamp or
4185 date range matching the selected date. Deadlines will
4186 also be listed, on the expiration day.
4187
4188 :deadline List any deadlines past due, or due within
4189 `org-deadline-warning-days'. The listing occurs only
4190 in the diary for *today*, not at any other date. If
4191 an entry is marked DONE, it is no longer listed.
4192
4193 :scheduled List all items which are scheduled for the given date.
4194 The diary for *today* also contains items which were
4195 scheduled earlier and are not yet marked DONE.
4196
4197 :todo List all TODO items from the org-file. This may be a
4198 long list - so this is not turned on by default.
4199 Like deadlines, these entries only show up in the
4200 diary for *today*, not at any other date.
4201
4202 The call in the diary file should look like this:
4203
4204 &%%(org-diary) ~/path/to/some/orgfile.org
4205
4206 Use a separate line for each org file to check. Or, if you omit the file name,
4207 all files listed in `org-agenda-files' will be checked automatically:
4208
4209 &%%(org-diary)
4210
4211 If you don't give any arguments (as in the example above), the default
4212 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4213 also be written as
4214
4215 &%%(org-diary :deadline :timestamp :scheduled)
4216
4217 The function expects the lisp variables `entry' and `date' to be provided
4218 by the caller, because this is how the calendar works. Don't use this
4219 function from a program - use `org-agenda-get-day-entries' instead."
4220 (org-agenda-maybe-reset-markers)
4221 (org-compile-prefix-format org-agenda-prefix-format)
4222 (setq args (or args '(:deadline :scheduled :timestamp)))
4223 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4224 (list entry)
4225 org-agenda-files))
4226 file rtn results)
4227 ;; If this is called during org-agenda, don't return any entries to
4228 ;; the calendar. Org Agenda will list these entries itself.
4229 (if org-disable-diary (setq files nil))
4230 (while (setq file (pop files))
4231 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4232 (setq results (append results rtn)))
4233 (concat (org-finalize-agenda-entries results) "\n")))
4234
4235 (defun org-agenda-get-day-entries (file date &rest args)
4236 "Does the work for `org-diary' and `org-agenda'.
4237 FILE is the path to a file to be checked for entries. DATE is date like
4238 the one returned by `calendar-current-date'. ARGS are symbols indicating
4239 which kind of entries should be extracted. For details about these, see
4240 the documentation of `org-diary'."
4241 (setq args (or args '(:deadline :scheduled :timestamp)))
4242 (let* ((org-startup-with-deadline-check nil)
4243 (org-startup-folded nil)
4244 (buffer (if (file-exists-p file)
4245 (org-get-agenda-file-buffer file)
4246 (error "No such file %s" file)))
4247 arg results rtn)
4248 (if (not buffer)
4249 ;; If file does not exist, make sure an error message ends up in diary
4250 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4251 (with-current-buffer buffer
4252 (unless (eq major-mode 'org-mode)
4253 (error "Agenda file %s is not in `org-mode'" file))
4254 (let ((case-fold-search nil))
4255 (save-excursion
4256 (save-restriction
4257 (if org-respect-restriction
4258 (if (org-region-active-p)
4259 ;; Respect a region to restrict search
4260 (narrow-to-region (region-beginning) (region-end)))
4261 ;; If we work for the calendar or many files,
4262 ;; get rid of any restriction
4263 (widen))
4264 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4265 (while (setq arg (pop args))
4266 (cond
4267 ((and (eq arg :todo)
4268 (equal date (calendar-current-date)))
4269 (setq rtn (org-agenda-get-todos))
4270 (setq results (append results rtn)))
4271 ((eq arg :timestamp)
4272 (setq rtn (org-agenda-get-blocks))
4273 (setq results (append results rtn))
4274 (setq rtn (org-agenda-get-timestamps))
4275 (setq results (append results rtn)))
4276 ((eq arg :scheduled)
4277 (setq rtn (org-agenda-get-scheduled))
4278 (setq results (append results rtn)))
4279 ((and (eq arg :deadline)
4280 (equal date (calendar-current-date)))
4281 (setq rtn (org-agenda-get-deadlines))
4282 (setq results (append results rtn))))))))
4283 results))))
4284
4285 (defun org-entry-is-done-p ()
4286 "Is the current entry marked DONE?"
4287 (save-excursion
4288 (and (re-search-backward "[\r\n]\\*" nil t)
4289 (looking-at org-nl-done-regexp))))
4290
4291 (defun org-at-date-range-p ()
4292 "Is the cursor inside a date range?"
4293 (interactive)
4294 (save-excursion
4295 (catch 'exit
4296 (let ((pos (point)))
4297 (skip-chars-backward "^<\r\n")
4298 (skip-chars-backward "<")
4299 (and (looking-at org-tr-regexp)
4300 (>= (match-end 0) pos)
4301 (throw 'exit t))
4302 (skip-chars-backward "^<\r\n")
4303 (skip-chars-backward "<")
4304 (and (looking-at org-tr-regexp)
4305 (>= (match-end 0) pos)
4306 (throw 'exit t)))
4307 nil)))
4308
4309 (defun org-agenda-get-todos ()
4310 "Return the TODO information for agenda display."
4311 (let* ((props (list 'face nil
4312 'done-face 'org-done
4313 'mouse-face 'highlight
4314 'keymap org-agenda-keymap
4315 'help-echo
4316 (format "mouse-2 or RET jump to org file %s"
4317 (abbreviate-file-name (buffer-file-name)))))
4318 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4319 "[^\n\r]*\\)"))
4320 marker priority
4321 ee txt)
4322 (goto-char (point-min))
4323 (while (re-search-forward regexp nil t)
4324 (goto-char (match-beginning 1))
4325 (setq marker (org-agenda-new-marker (point-at-bol))
4326 txt (org-format-agenda-item "" (match-string 1))
4327 priority
4328 (+ (org-get-priority txt)
4329 (if org-todo-kwd-priority-p
4330 (- org-todo-kwd-max-priority -2
4331 (length
4332 (member (match-string 2) org-todo-keywords)))
4333 1)))
4334 (add-text-properties
4335 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4336 'priority priority)
4337 props)
4338 txt)
4339 (push txt ee)
4340 (goto-char (match-end 1)))
4341 (nreverse ee)))
4342
4343 (defconst org-agenda-no-heading-message
4344 "No heading for this item in buffer or region")
4345
4346 (defun org-agenda-get-timestamps ()
4347 "Return the date stamp information for agenda display."
4348 (let* ((props (list 'face nil
4349 'mouse-face 'highlight
4350 'keymap org-agenda-keymap
4351 'help-echo
4352 (format "mouse-2 or RET jump to org file %s"
4353 (abbreviate-file-name (buffer-file-name)))))
4354 (regexp (regexp-quote
4355 (substring
4356 (format-time-string
4357 (car org-time-stamp-formats)
4358 (apply 'encode-time ; DATE bound by calendar
4359 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4360 0 11)))
4361 marker hdmarker deadlinep scheduledp donep tmp priority
4362 ee txt timestr)
4363 (goto-char (point-min))
4364 (while (re-search-forward regexp nil t)
4365 (if (not (save-match-data (org-at-date-range-p)))
4366 (progn
4367 (setq marker (org-agenda-new-marker (match-beginning 0))
4368 tmp (buffer-substring (max (point-min)
4369 (- (match-beginning 0)
4370 org-ds-keyword-length))
4371 (match-beginning 0))
4372 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4373 deadlinep (string-match org-deadline-regexp tmp)
4374 scheduledp (string-match org-scheduled-regexp tmp)
4375 donep (org-entry-is-done-p))
4376 (if (string-match ">" timestr)
4377 ;; substring should only run to end of time stamp
4378 (setq timestr (substring timestr 0 (match-end 0))))
4379 (save-excursion
4380 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4381 (progn
4382 (goto-char (match-end 1))
4383 (setq hdmarker (org-agenda-new-marker))
4384 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4385 (setq txt (org-format-agenda-item
4386 (format "%s%s"
4387 (if deadlinep "Deadline: " "")
4388 (if scheduledp "Scheduled: " ""))
4389 (match-string 1) nil timestr)))
4390 (setq txt org-agenda-no-heading-message))
4391 (setq priority (org-get-priority txt))
4392 (add-text-properties
4393 0 (length txt) (append (list 'org-marker marker
4394 'org-hd-marker hdmarker) props)
4395 txt)
4396 (if deadlinep
4397 (add-text-properties
4398 0 (length txt)
4399 (list 'face
4400 (if donep 'org-done 'org-warning)
4401 'undone-face 'org-warning
4402 'done-face 'org-done
4403 'priority (+ 100 priority))
4404 txt)
4405 (if scheduledp
4406 (add-text-properties
4407 0 (length txt)
4408 (list 'face 'org-scheduled-today
4409 'undone-face 'org-scheduled-today
4410 'done-face 'org-done
4411 priority (+ 99 priority))
4412 txt)
4413 (add-text-properties
4414 0 (length txt)
4415 (list 'priority priority) txt)))
4416 (push txt ee))
4417 (outline-next-heading))))
4418 (nreverse ee)))
4419
4420 (defun org-agenda-get-deadlines ()
4421 "Return the deadline information for agenda display."
4422 (let* ((wdays org-deadline-warning-days)
4423 (props (list 'mouse-face 'highlight
4424 'keymap org-agenda-keymap
4425 'help-echo
4426 (format "mouse-2 or RET jump to org file %s"
4427 (abbreviate-file-name (buffer-file-name)))))
4428 (regexp org-deadline-time-regexp)
4429 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4430 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4431 d2 diff pos pos1
4432 ee txt head)
4433 (goto-char (point-min))
4434 (while (re-search-forward regexp nil t)
4435 (setq pos (1- (match-beginning 1))
4436 d2 (time-to-days
4437 (org-time-string-to-time (match-string 1)))
4438 diff (- d2 d1))
4439 ;; When to show a deadline in the calendar:
4440 ;; If the expiration is within wdays warning time.
4441 ;; Past-due deadlines are only shown on the current date
4442 (if (and (< diff wdays) todayp (not (= diff 0)))
4443 (save-excursion
4444 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4445 (progn
4446 (goto-char (match-end 0))
4447 (setq pos1 (match-end 1))
4448 (setq head (buffer-substring-no-properties
4449 (point)
4450 (progn (skip-chars-forward "^\r\n")
4451 (point))))
4452 (if (string-match org-looking-at-done-regexp head)
4453 (setq txt nil)
4454 (setq txt (org-format-agenda-item
4455 (format "In %3d d.: " diff) head))))
4456 (setq txt org-agenda-no-heading-message))
4457 (when txt
4458 (add-text-properties
4459 0 (length txt)
4460 (append
4461 (list 'org-marker (org-agenda-new-marker pos)
4462 'org-hd-marker (org-agenda-new-marker pos1)
4463 'priority (+ (- 10 diff) (org-get-priority txt))
4464 'face (cond ((<= diff 0) 'org-warning)
4465 ((<= diff 5) 'org-scheduled-previously)
4466 (t nil))
4467 'undone-face (cond
4468 ((<= diff 0) 'org-warning)
4469 ((<= diff 5) 'org-scheduled-previously)
4470 (t nil))
4471 'done-face 'org-done)
4472 props)
4473 txt)
4474 (push txt ee)))))
4475 ee))
4476
4477 (defun org-agenda-get-scheduled ()
4478 "Return the scheduled information for agenda display."
4479 (let* ((props (list 'face 'org-scheduled-previously
4480 'undone-face 'org-scheduled-previously
4481 'done-face 'org-done
4482 'mouse-face 'highlight
4483 'keymap org-agenda-keymap
4484 'help-echo
4485 (format "mouse-2 or RET jump to org file %s"
4486 (abbreviate-file-name (buffer-file-name)))))
4487 (regexp org-scheduled-time-regexp)
4488 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4489 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4490 d2 diff pos pos1
4491 ee txt head)
4492 (goto-char (point-min))
4493 (while (re-search-forward regexp nil t)
4494 (setq pos (1- (match-beginning 1))
4495 d2 (time-to-days
4496 (org-time-string-to-time (match-string 1)))
4497 diff (- d2 d1))
4498 ;; When to show a scheduled item in the calendar:
4499 ;; If it is on or past the date.
4500 (if (and (< diff 0) todayp)
4501 (save-excursion
4502 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4503 (progn
4504 (goto-char (match-end 0))
4505 (setq pos1 (match-end 1))
4506 (setq head (buffer-substring-no-properties
4507 (point)
4508 (progn (skip-chars-forward "^\r\n") (point))))
4509 (if (string-match org-looking-at-done-regexp head)
4510 (setq txt nil)
4511 (setq txt (org-format-agenda-item
4512 (format "Sched.%2dx: " (- 1 diff)) head))))
4513 (setq txt org-agenda-no-heading-message))
4514 (when txt
4515 (add-text-properties
4516 0 (length txt)
4517 (append (list 'org-marker (org-agenda-new-marker pos)
4518 'org-hd-marker (org-agenda-new-marker pos1)
4519 'priority (+ (- 5 diff) (org-get-priority txt)))
4520 props) txt)
4521 (push txt ee)))))
4522 ee))
4523
4524 (defun org-agenda-get-blocks ()
4525 "Return the date-range information for agenda display."
4526 (let* ((props (list 'face nil
4527 'mouse-face 'highlight
4528 'keymap org-agenda-keymap
4529 'help-echo
4530 (format "mouse-2 or RET jump to org file %s"
4531 (abbreviate-file-name (buffer-file-name)))))
4532 (regexp org-tr-regexp)
4533 (d0 (calendar-absolute-from-gregorian date))
4534 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4535 (goto-char (point-min))
4536 (while (re-search-forward regexp nil t)
4537 (setq timestr (match-string 0)
4538 s1 (match-string 1)
4539 s2 (match-string 2)
4540 d1 (time-to-days (org-time-string-to-time s1))
4541 d2 (time-to-days (org-time-string-to-time s2)))
4542 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4543 ;; Only allow days between the limits, because the normal
4544 ;; date stamps will catch the limits.
4545 (save-excursion
4546 (setq marker (org-agenda-new-marker (point)))
4547 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4548 (progn
4549 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4550 (goto-char (match-end 1))
4551 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4552 (setq txt (org-format-agenda-item
4553 (format (if (= d1 d2) "" "(%d/%d): ")
4554 (1+ (- d0 d1)) (1+ (- d2 d1)))
4555 (match-string 1) nil (if (= d0 d1) timestr))))
4556 (setq txt org-agenda-no-heading-message))
4557 (add-text-properties
4558 0 (length txt) (append (list 'org-marker marker
4559 'org-hd-marker hdmarker
4560 'priority (org-get-priority txt))
4561 props)
4562 txt)
4563 (push txt ee)))
4564 (outline-next-heading))
4565 ;; Sort the entries by expiration date.
4566 (nreverse ee)))
4567
4568
4569
4570 (defconst org-plain-time-of-day-regexp
4571 (concat
4572 "\\(\\<[012]?[0-9]"
4573 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4574 "\\(--?"
4575 "\\(\\<[012]?[0-9]"
4576 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4577 "\\)?")
4578 "Regular expression to match a plain time or time range.
4579 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4580 groups carry important information:
4581 0 the full match
4582 1 the first time, range or not
4583 8 the second time, if it is a range.")
4584
4585 (defconst org-stamp-time-of-day-regexp
4586 (concat
4587 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4588 "\\([012][0-9]:[0-5][0-9]\\)>"
4589 "\\(--?"
4590 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4591 "Regular expression to match a timestamp time or time range.
4592 After a match, the following groups carry important information:
4593 0 the full match
4594 1 date plus weekday, for backreferencing to make sure both times on same day
4595 2 the first time, range or not
4596 4 the second time, if it is a range.")
4597
4598 (defvar org-prefix-has-time nil
4599 "A flag, set by `org-compile-prefix-format'.
4600 The flag is set if the currently compiled format contains a `%t'.")
4601
4602 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4603 "Format TXT to be inserted into the agenda buffer.
4604 In particular, it adds the prefix and corresponding text properties. EXTRA
4605 must be a string and replaces the `%s' specifier in the prefix format.
4606 CATEGORY (string, symbol or nil) may be used to overule the default
4607 category taken from local variable or file name. It will replace the `%c'
4608 specifier in the format. DOTIME, when non-nil, indicates that a
4609 time-of-day should be extracted from TXT for sorting of this entry, and for
4610 the `%t' specifier in the format. When DOTIME is a string, this string is
4611 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4612 only the correctly processes TXT should be returned - this is used by
4613 `org-agenda-change-all-lines'."
4614 (save-match-data
4615 ;; Diary entries sometimes have extra whitespace at the beginning
4616 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4617 (let* ((category (or category
4618 org-category
4619 (if (buffer-file-name)
4620 (file-name-sans-extension
4621 (file-name-nondirectory (buffer-file-name)))
4622 "")))
4623 time ;; needed for the eval of the prefix format
4624 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4625 (time-of-day (and dotime (org-get-time-of-day ts)))
4626 stamp plain s0 s1 s2 rtn)
4627 (when (and dotime time-of-day org-prefix-has-time)
4628 ;; Extract starting and ending time and move them to prefix
4629 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4630 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4631 (setq s0 (match-string 0 ts)
4632 s1 (match-string (if plain 1 2) ts)
4633 s2 (match-string (if plain 8 4) ts))
4634
4635 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4636 ;; them, we might want to remove them there to avoid duplication.
4637 ;; The user can turn this off with a variable.
4638 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4639 (string-match (concat (regexp-quote s0) " *") txt)
4640 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4641 (= (match-beginning 0) 0)
4642 t))
4643 (setq txt (replace-match "" nil nil txt))))
4644 ;; Normalize the time(s) to 24 hour
4645 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4646 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4647
4648 ;; Create the final string
4649 (if noprefix
4650 (setq rtn txt)
4651 ;; Prepare the variables needed in the eval of the compiled format
4652 (setq time (cond (s2 (concat s1 "-" s2))
4653 (s1 (concat s1 "......"))
4654 (t ""))
4655 extra (or extra "")
4656 category (if (symbolp category) (symbol-name category) category))
4657 ;; Evaluate the compiled format
4658 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4659
4660 ;; And finally add the text properties
4661 (add-text-properties
4662 0 (length rtn) (list 'category (downcase category)
4663 'prefix-length (- (length rtn) (length txt))
4664 'time-of-day time-of-day
4665 'dotime dotime)
4666 rtn)
4667 rtn)))
4668
4669 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4670 (catch 'exit
4671 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4672 ((and todayp (member 'today (car org-agenda-time-grid))))
4673 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4674 ((member 'weekly (car org-agenda-time-grid)))
4675 (t (throw 'exit list)))
4676 (let* ((have (delq nil (mapcar
4677 (lambda (x) (get-text-property 1 'time-of-day x))
4678 list)))
4679 (string (nth 1 org-agenda-time-grid))
4680 (gridtimes (nth 2 org-agenda-time-grid))
4681 (req (car org-agenda-time-grid))
4682 (remove (member 'remove-match req))
4683 new time)
4684 (if (and (member 'require-timed req) (not have))
4685 ;; don't show empty grid
4686 (throw 'exit list))
4687 (while (setq time (pop gridtimes))
4688 (unless (and remove (member time have))
4689 (setq time (int-to-string time))
4690 (push (org-format-agenda-item
4691 nil string "" ;; FIXME: put a category?
4692 (concat (substring time 0 -2) ":" (substring time -2)))
4693 new)
4694 (put-text-property
4695 1 (length (car new)) 'face 'org-time-grid (car new))))
4696 (if (member 'time-up org-agenda-sorting-strategy)
4697 (append new list)
4698 (append list new)))))
4699
4700 (defun org-compile-prefix-format (format)
4701 "Compile the prefix format into a Lisp form that can be evaluated.
4702 The resulting form is returned and stored in the variable
4703 `org-prefix-format-compiled'."
4704 (setq org-prefix-has-time nil)
4705 (let ((start 0) varform vars var (s format) c f opt)
4706 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4707 s start)
4708 (setq var (cdr (assoc (match-string 4 s)
4709 '(("c" . category) ("t" . time) ("s" . extra))))
4710 c (or (match-string 3 s) "")
4711 opt (match-beginning 1)
4712 start (1+ (match-beginning 0)))
4713 (if (equal var 'time) (setq org-prefix-has-time t))
4714 (setq f (concat "%" (match-string 2 s) "s"))
4715 (if opt
4716 (setq varform
4717 `(if (equal "" ,var)
4718 ""
4719 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4720 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4721 (setq s (replace-match "%s" t nil s))
4722 (push varform vars))
4723 (setq vars (nreverse vars))
4724 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4725
4726 (defun org-get-time-of-day (s &optional string)
4727 "Check string S for a time of day.
4728 If found, return it as a military time number between 0 and 2400.
4729 If not found, return nil.
4730 The optional STRING argument forces conversion into a 5 character wide string
4731 HH:MM."
4732 (save-match-data
4733 (when
4734 (or
4735 (string-match
4736 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4737 (string-match
4738 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4739 (let* ((t0 (+ (* 100
4740 (+ (string-to-number (match-string 1 s))
4741 (if (and (match-beginning 4)
4742 (equal (downcase (match-string 4 s)) "pm"))
4743 12 0)))
4744 (if (match-beginning 3)
4745 (string-to-number (match-string 3 s))
4746 0)))
4747 (t1 (concat " " (int-to-string t0))))
4748 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4749
4750 (defun org-finalize-agenda-entries (list)
4751 "Sort and concatenate the agenda items."
4752 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4753
4754 (defsubst org-cmp-priority (a b)
4755 "Compare the priorities of string a and b."
4756 (let ((pa (or (get-text-property 1 'priority a) 0))
4757 (pb (or (get-text-property 1 'priority b) 0)))
4758 (cond ((> pa pb) +1)
4759 ((< pa pb) -1)
4760 (t nil))))
4761
4762 (defsubst org-cmp-category (a b)
4763 "Compare the string values of categories of strings a and b."
4764 (let ((ca (or (get-text-property 1 'category a) ""))
4765 (cb (or (get-text-property 1 'category b) "")))
4766 (cond ((string-lessp ca cb) -1)
4767 ((string-lessp cb ca) +1)
4768 (t nil))))
4769
4770 (defsubst org-cmp-time (a b)
4771 "Compare the time-of-day values of strings a and b."
4772 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4773 (ta (or (get-text-property 1 'time-of-day a) def))
4774 (tb (or (get-text-property 1 'time-of-day b) def)))
4775 (cond ((< ta tb) -1)
4776 ((< tb ta) +1)
4777 (t nil))))
4778
4779 (defun org-entries-lessp (a b)
4780 "Predicate for sorting agenda entries."
4781 ;; The following variables will be used when the form is evaluated.
4782 (let* ((time-up (org-cmp-time a b))
4783 (time-down (if time-up (- time-up) nil))
4784 (priority-up (org-cmp-priority a b))
4785 (priority-down (if priority-up (- priority-up) nil))
4786 (category-up (org-cmp-category a b))
4787 (category-down (if category-up (- category-up) nil))
4788 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4789 (cdr (assoc
4790 (eval (cons 'or org-agenda-sorting-strategy))
4791 '((-1 . t) (1 . nil) (nil . nil))))))
4792
4793 (defun org-agenda-show-priority ()
4794 "Show the priority of the current item.
4795 This priority is composed of the main priority given with the [#A] cookies,
4796 and by additional input from the age of a schedules or deadline entry."
4797 (interactive)
4798 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4799 (message "Priority is %d" (if pri pri -1000))))
4800
4801 (defun org-agenda-goto (&optional highlight)
4802 "Go to the Org-mode file which contains the item at point."
4803 (interactive)
4804 (let* ((marker (or (get-text-property (point) 'org-marker)
4805 (org-agenda-error)))
4806 (buffer (marker-buffer marker))
4807 (pos (marker-position marker)))
4808 (switch-to-buffer-other-window buffer)
4809 (widen)
4810 (goto-char pos)
4811 (when (eq major-mode 'org-mode)
4812 (org-show-hidden-entry)
4813 (save-excursion
4814 (and (outline-next-heading)
4815 (org-flag-heading nil)))) ; show the next heading
4816 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4817
4818 (defun org-agenda-switch-to ()
4819 "Go to the Org-mode file which contains the item at point."
4820 (interactive)
4821 (let* ((marker (or (get-text-property (point) 'org-marker)
4822 (org-agenda-error)))
4823 (buffer (marker-buffer marker))
4824 (pos (marker-position marker)))
4825 (switch-to-buffer buffer)
4826 (delete-other-windows)
4827 (widen)
4828 (goto-char pos)
4829 (when (eq major-mode 'org-mode)
4830 (org-show-hidden-entry)
4831 (save-excursion
4832 (and (outline-next-heading)
4833 (org-flag-heading nil)))))) ; show the next heading
4834
4835 (defun org-agenda-goto-mouse (ev)
4836 "Go to the Org-mode file which contains the item at the mouse click."
4837 (interactive "e")
4838 (mouse-set-point ev)
4839 (org-agenda-goto))
4840
4841 (defun org-agenda-show ()
4842 "Display the Org-mode file which contains the item at point."
4843 (interactive)
4844 (let ((win (selected-window)))
4845 (org-agenda-goto t)
4846 (select-window win)))
4847
4848 (defun org-agenda-recenter (arg)
4849 "Display the Org-mode file which contains the item at point and recenter."
4850 (interactive "P")
4851 (let ((win (selected-window)))
4852 (org-agenda-goto t)
4853 (recenter arg)
4854 (select-window win)))
4855
4856 (defun org-agenda-show-mouse (ev)
4857 "Display the Org-mode file which contains the item at the mouse click."
4858 (interactive "e")
4859 (mouse-set-point ev)
4860 (org-agenda-show))
4861
4862 (defun org-agenda-check-no-diary ()
4863 "Check if the entry is a diary link and abort if yes."
4864 (if (get-text-property (point) 'org-agenda-diary-link)
4865 (org-agenda-error)))
4866
4867 (defun org-agenda-error ()
4868 (error "Command not allowed in this line"))
4869
4870 (defvar org-last-heading-marker (make-marker)
4871 "Marker pointing to the headline that last changed its TODO state
4872 by a remote command from the agenda.")
4873
4874 (defun org-agenda-todo ()
4875 "Cycle TODO state of line at point, also in Org-mode file.
4876 This changes the line at point, all other lines in the agenda referring to
4877 the same tree node, and the headline of the tree node in the Org-mode file."
4878 (interactive)
4879 (org-agenda-check-no-diary)
4880 (let* ((col (current-column))
4881 (marker (or (get-text-property (point) 'org-marker)
4882 (org-agenda-error)))
4883 (buffer (marker-buffer marker))
4884 (pos (marker-position marker))
4885 (hdmarker (get-text-property (point) 'org-hd-marker))
4886 (buffer-read-only nil)
4887 newhead)
4888 (with-current-buffer buffer
4889 (widen)
4890 (goto-char pos)
4891 (org-show-hidden-entry)
4892 (save-excursion
4893 (and (outline-next-heading)
4894 (org-flag-heading nil))) ; show the next heading
4895 (org-todo)
4896 (forward-char 1)
4897 (setq newhead (org-get-heading))
4898 (save-excursion
4899 (org-back-to-heading)
4900 (move-marker org-last-heading-marker (point))))
4901 (beginning-of-line 1)
4902 (save-excursion
4903 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4904 (move-to-column col)))
4905
4906 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4907 "Change all lines in the agenda buffer which match hdmarker.
4908 The new content of the line will be NEWHEAD (as modified by
4909 `org-format-agenda-item'). HDMARKER is checked with
4910 `equal' against all `org-hd-marker' text properties in the file.
4911 If FIXFACE is non-nil, the face of each item is modified acording to
4912 the new TODO state."
4913 (let* (props m pl undone-face done-face finish new dotime)
4914 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4915 (save-excursion
4916 (goto-char (point-max))
4917 (beginning-of-line 1)
4918 (while (not finish)
4919 (setq finish (bobp))
4920 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4921 (equal m hdmarker))
4922 (setq props (text-properties-at (point))
4923 dotime (get-text-property (point) 'dotime)
4924 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4925 pl (get-text-property (point) 'prefix-length)
4926 undone-face (get-text-property (point) 'undone-face)
4927 done-face (get-text-property (point) 'done-face))
4928 (move-to-column pl)
4929 (if (looking-at ".*")
4930 (progn
4931 (replace-match new t t)
4932 (beginning-of-line 1)
4933 (add-text-properties (point-at-bol) (point-at-eol) props)
4934 (if fixface
4935 (add-text-properties
4936 (point-at-bol) (point-at-eol)
4937 (list 'face
4938 (if org-last-todo-state-is-todo
4939 undone-face done-face))))
4940 (beginning-of-line 1))
4941 (error "Line update did not work")))
4942 (beginning-of-line 0)))))
4943
4944 (defun org-agenda-priority-up ()
4945 "Increase the priority of line at point, also in Org-mode file."
4946 (interactive)
4947 (org-agenda-priority 'up))
4948
4949 (defun org-agenda-priority-down ()
4950 "Decrease the priority of line at point, also in Org-mode file."
4951 (interactive)
4952 (org-agenda-priority 'down))
4953
4954 (defun org-agenda-priority (&optional force-direction)
4955 "Set the priority of line at point, also in Org-mode file.
4956 This changes the line at point, all other lines in the agenda referring to
4957 the same tree node, and the headline of the tree node in the Org-mode file."
4958 (interactive)
4959 (org-agenda-check-no-diary)
4960 (let* ((marker (or (get-text-property (point) 'org-marker)
4961 (org-agenda-error)))
4962 (buffer (marker-buffer marker))
4963 (pos (marker-position marker))
4964 (hdmarker (get-text-property (point) 'org-hd-marker))
4965 (buffer-read-only nil)
4966 newhead)
4967 (with-current-buffer buffer
4968 (widen)
4969 (goto-char pos)
4970 (org-show-hidden-entry)
4971 (save-excursion
4972 (and (outline-next-heading)
4973 (org-flag-heading nil))) ; show the next heading
4974 (funcall 'org-priority force-direction)
4975 (end-of-line 1)
4976 (setq newhead (org-get-heading)))
4977 (org-agenda-change-all-lines newhead hdmarker)
4978 (beginning-of-line 1)))
4979
4980 (defun org-agenda-date-later (arg &optional what)
4981 "Change the date of this item to one day later."
4982 (interactive "p")
4983 (org-agenda-check-no-diary)
4984 (let* ((marker (or (get-text-property (point) 'org-marker)
4985 (org-agenda-error)))
4986 (buffer (marker-buffer marker))
4987 (pos (marker-position marker)))
4988 (with-current-buffer buffer
4989 (widen)
4990 (goto-char pos)
4991 (if (not (org-at-timestamp-p))
4992 (error "Cannot find time stamp"))
4993 (org-timestamp-change arg (or what 'day))
4994 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4995
4996 (defun org-agenda-date-earlier (arg &optional what)
4997 "Change the date of this item to one day earlier."
4998 (interactive "p")
4999 (org-agenda-date-later (- arg) what))
5000
5001 (defun org-agenda-date-prompt (arg)
5002 "Change the date of this item. Date is prompted for, with default today.
5003 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5004 be used to request time specification in the time stamp."
5005 (interactive "P")
5006 (org-agenda-check-no-diary)
5007 (let* ((marker (or (get-text-property (point) 'org-marker)
5008 (org-agenda-error)))
5009 (buffer (marker-buffer marker))
5010 (pos (marker-position marker)))
5011 (with-current-buffer buffer
5012 (widen)
5013 (goto-char pos)
5014 (if (not (org-at-timestamp-p))
5015 (error "Cannot find time stamp"))
5016 (org-time-stamp arg)
5017 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5018
5019 (defun org-get-heading ()
5020 "Return the heading of the current entry, without the stars."
5021 (save-excursion
5022 (if (and (re-search-backward "[\r\n]\\*" nil t)
5023 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5024 (match-string 1)
5025 "")))
5026
5027 (defun org-agenda-diary-entry ()
5028 "Make a diary entry, like the `i' command from the calendar.
5029 All the standard commands work: block, weekly etc"
5030 (interactive)
5031 (require 'diary-lib)
5032 (let* ((char (progn
5033 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5034 (read-char-exclusive)))
5035 (cmd (cdr (assoc char
5036 '((?d . insert-diary-entry)
5037 (?w . insert-weekly-diary-entry)
5038 (?m . insert-monthly-diary-entry)
5039 (?y . insert-yearly-diary-entry)
5040 (?a . insert-anniversary-diary-entry)
5041 (?b . insert-block-diary-entry)
5042 (?c . insert-cyclic-diary-entry)))))
5043 (oldf (symbol-function 'calendar-cursor-to-date))
5044 (point (point))
5045 (mark (or (mark t) (point))))
5046 (unless cmd
5047 (error "No command associated with <%c>" char))
5048 (unless (and (get-text-property point 'day)
5049 (or (not (equal ?b char))
5050 (get-text-property mark 'day)))
5051 (error "Don't know which date to use for diary entry"))
5052 ;; We implement this by hacking the `calendar-cursor-to-date' function
5053 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5054 (let ((calendar-mark-ring
5055 (list (calendar-gregorian-from-absolute
5056 (or (get-text-property mark 'day)
5057 (get-text-property point 'day))))))
5058 (unwind-protect
5059 (progn
5060 (fset 'calendar-cursor-to-date
5061 (lambda (&optional error)
5062 (calendar-gregorian-from-absolute
5063 (get-text-property point 'day))))
5064 (call-interactively cmd))
5065 (fset 'calendar-cursor-to-date oldf)))))
5066
5067
5068 (defun org-agenda-execute-calendar-command (cmd)
5069 "Execute a calendar command from the agenda, with the date associated to
5070 the cursor position."
5071 (require 'diary-lib)
5072 (unless (get-text-property (point) 'day)
5073 (error "Don't know which date to use for calendar command"))
5074 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5075 (point (point))
5076 (date (calendar-gregorian-from-absolute
5077 (get-text-property point 'day)))
5078 (displayed-day (extract-calendar-day date))
5079 (displayed-month (extract-calendar-month date))
5080 (displayed-year (extract-calendar-year date)))
5081 (unwind-protect
5082 (progn
5083 (fset 'calendar-cursor-to-date
5084 (lambda (&optional error)
5085 (calendar-gregorian-from-absolute
5086 (get-text-property point 'day))))
5087 (call-interactively cmd))
5088 (fset 'calendar-cursor-to-date oldf))))
5089
5090 (defun org-agenda-phases-of-moon ()
5091 "Display the phases of the moon for the 3 months around the cursor date."
5092 (interactive)
5093 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5094
5095 (defun org-agenda-holidays ()
5096 "Display the holidays for the 3 months around the cursor date."
5097 (interactive)
5098 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5099
5100 (defun org-agenda-sunrise-sunset (arg)
5101 "Display sunrise and sunset for the cursor date.
5102 Latitude and longitude can be specified with the variables
5103 `calendar-latitude' and `calendar-longitude'. When called with prefix
5104 argument, latitude and longitude will be prompted for."
5105 (interactive "P")
5106 (let ((calendar-longitude (if arg nil calendar-longitude))
5107 (calendar-latitude (if arg nil calendar-latitude))
5108 (calendar-location-name
5109 (if arg "the given coordinates" calendar-location-name)))
5110 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5111
5112 (defun org-agenda-goto-calendar ()
5113 "Open the Emacs calendar with the date at the cursor."
5114 (interactive)
5115 (let* ((day (or (get-text-property (point) 'day)
5116 (error "Don't know which date to open in calendar")))
5117 (date (calendar-gregorian-from-absolute day)))
5118 (calendar)
5119 (calendar-goto-date date)))
5120
5121 (defun org-calendar-goto-agenda ()
5122 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5123 This is a command that has to be installed in `calendar-mode-map'."
5124 (interactive)
5125 (org-agenda nil (calendar-absolute-from-gregorian
5126 (calendar-cursor-to-date))))
5127
5128 (defun org-agenda-convert-date ()
5129 (interactive)
5130 (let ((day (get-text-property (point) 'day))
5131 date s)
5132 (unless day
5133 (error "Don't know which date to convert"))
5134 (setq date (calendar-gregorian-from-absolute day))
5135 (setq s (concat
5136 "Gregorian: " (calendar-date-string date) "\n"
5137 "ISO: " (calendar-iso-date-string date) "\n"
5138 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5139 "Julian: " (calendar-julian-date-string date) "\n"
5140 "Astron. JD: " (calendar-astro-date-string date)
5141 " (Julian date number at noon UTC)\n"
5142 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5143 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5144 "French: " (calendar-french-date-string date) "\n"
5145 "Mayan: " (calendar-mayan-date-string date) "\n"
5146 "Coptic: " (calendar-coptic-date-string date) "\n"
5147 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5148 "Persian: " (calendar-persian-date-string date) "\n"
5149 "Chinese: " (calendar-chinese-date-string date) "\n"))
5150 (with-output-to-temp-buffer "*Dates*"
5151 (princ s))
5152 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5153
5154 ;;; Link Stuff
5155
5156 (defun org-find-file-at-mouse (ev)
5157 "Open file link or URL at mouse."
5158 (interactive "e")
5159 (mouse-set-point ev)
5160 (org-open-at-point 'in-emacs))
5161
5162 (defun org-open-at-mouse (ev)
5163 "Open file link or URL at mouse."
5164 (interactive "e")
5165 (mouse-set-point ev)
5166 (org-open-at-point))
5167
5168 (defun org-open-at-point (&optional in-emacs)
5169 "Open link at or after point.
5170 If there is no link at point, this function will search forward up to
5171 the end of the current subtree.
5172 Normally, files will be opened by an appropriate application. If the
5173 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5174 (interactive "P")
5175 (if (org-at-timestamp-p)
5176 (org-agenda nil (time-to-days (org-time-string-to-time
5177 (substring (match-string 1) 0 10)))
5178 1)
5179 (let (type path line (pos (point)))
5180 (save-excursion
5181 (skip-chars-backward
5182 (concat (if org-allow-space-in-links "^" "^ ")
5183 org-non-link-chars))
5184 (if (re-search-forward
5185 org-link-regexp
5186 (save-excursion
5187 (condition-case nil
5188 (progn (outline-end-of-subtree) (max pos (point)))
5189 (error (end-of-line 1) (point))))
5190 t)
5191 (setq type (match-string 1)
5192 path (match-string 2)))
5193 (unless path
5194 (error "No link found"))
5195 ;; Remove any trailing spaces in path
5196 (if (string-match " +\\'" path)
5197 (setq path (replace-match "" t t path)))
5198
5199 (cond
5200
5201 ((string= type "file")
5202 (if (string-match ":\\([0-9]+\\)\\'" path)
5203 (setq line (string-to-number (match-string 1 path))
5204 path (substring path 0 (match-beginning 0))))
5205 (org-open-file path in-emacs line))
5206
5207 ((string= type "news")
5208 (org-follow-gnus-link path))
5209
5210 ((string= type "bbdb")
5211 (org-follow-bbdb-link path))
5212
5213 ((string= type "gnus")
5214 (let (group article)
5215 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5216 (error "Error in Gnus link"))
5217 (setq group (match-string 1 path)
5218 article (match-string 3 path))
5219 (org-follow-gnus-link group article)))
5220
5221 ((string= type "vm")
5222 (let (folder article)
5223 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5224 (error "Error in VM link"))
5225 (setq folder (match-string 1 path)
5226 article (match-string 3 path))
5227 ;; in-emacs is the prefix arg, will be interpreted as read-only
5228 (org-follow-vm-link folder article in-emacs)))
5229
5230 ((string= type "wl")
5231 (let (folder article)
5232 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5233 (error "Error in Wanderlust link"))
5234 (setq folder (match-string 1 path)
5235 article (match-string 3 path))
5236 (org-follow-wl-link folder article)))
5237
5238 ((string= type "rmail")
5239 (let (folder article)
5240 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5241 (error "Error in RMAIL link"))
5242 (setq folder (match-string 1 path)
5243 article (match-string 3 path))
5244 (org-follow-rmail-link folder article)))
5245
5246 ((string= type "shell")
5247 (let ((cmd path))
5248 (while (string-match "@{" cmd)
5249 (setq cmd (replace-match "<" t t cmd)))
5250 (while (string-match "@}" cmd)
5251 (setq cmd (replace-match ">" t t cmd)))
5252 (if (or (not org-confirm-shell-links)
5253 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5254 (shell-command cmd)
5255 (error "Abort"))))
5256
5257 (t
5258 (browse-url-at-point)))))))
5259
5260 (defun org-follow-bbdb-link (name)
5261 "Follow a BBDB link to NAME."
5262 (require 'bbdb)
5263 (let ((inhibit-redisplay t))
5264 (catch 'exit
5265 ;; Exact match on name
5266 (bbdb-name (concat "\\`" name "\\'") nil)
5267 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5268 ;; Exact match on name
5269 (bbdb-company (concat "\\`" name "\\'") nil)
5270 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5271 ;; Partial match on name
5272 (bbdb-name name nil)
5273 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5274 ;; Partial match on company
5275 (bbdb-company name nil)
5276 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5277 ;; General match including network address and notes
5278 (bbdb name nil)
5279 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5280 (delete-window (get-buffer-window "*BBDB*"))
5281 (error "No matching BBDB record")))))
5282
5283 (defun org-follow-gnus-link (&optional group article)
5284 "Follow a Gnus link to GROUP and ARTICLE."
5285 (require 'gnus)
5286 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5287 (if group (gnus-fetch-group group))
5288 (if article
5289 (or (gnus-summary-goto-article article nil 'force)
5290 (if (fboundp 'gnus-summary-insert-cached-articles)
5291 (progn
5292 (gnus-summary-insert-cached-articles)
5293 (gnus-summary-goto-article article nil 'force))
5294 (message "Message could not be found.")))))
5295
5296 (defun org-follow-vm-link (&optional folder article readonly)
5297 "Follow a VM link to FOLDER and ARTICLE."
5298 (require 'vm)
5299 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5300 ;; ange-ftp or efs or tramp access
5301 (let ((user (or (match-string 1 folder) (user-login-name)))
5302 (host (match-string 2 folder))
5303 (file (match-string 3 folder)))
5304 (cond
5305 ((featurep 'tramp)
5306 ;; use tramp to access the file
5307 (if org-xemacs-p
5308 (setq folder (format "[%s@%s]%s" user host file))
5309 (setq folder (format "/%s@%s:%s" user host file))))
5310 (t
5311 ;; use ange-ftp or efs
5312 (require (if org-xemacs-p 'efs 'ange-ftp))
5313 (setq folder (format "/%s@%s:%s" user host file))))))
5314 (when folder
5315 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5316 (sit-for 0.1)
5317 (when article
5318 (vm-select-folder-buffer)
5319 (widen)
5320 (let ((case-fold-search t))
5321 (goto-char (point-min))
5322 (if (not (re-search-forward
5323 (concat "^" "message-id: *" (regexp-quote article))))
5324 (error "Could not find the specified message in this folder"))
5325 (vm-isearch-update)
5326 (vm-isearch-narrow)
5327 (vm-beginning-of-message)
5328 (vm-summarize)))))
5329
5330 (defun org-follow-wl-link (folder article)
5331 "Follow a Wanderlust link to FOLDER and ARTICLE."
5332 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5333 (if article (wl-summary-jump-to-msg-by-message-id article))
5334 (wl-summary-redisplay))
5335
5336 (defun org-follow-rmail-link (folder article)
5337 "Follow an RMAIL link to FOLDER and ARTICLE."
5338 (let (message-number)
5339 (save-excursion
5340 (save-window-excursion
5341 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5342 (setq message-number
5343 (save-restriction
5344 (widen)
5345 (goto-char (point-max))
5346 (if (re-search-backward
5347 (concat "^Message-ID:\\s-+" (regexp-quote
5348 (or article "")))
5349 nil t)
5350 (rmail-what-message))))))
5351 (if message-number
5352 (progn
5353 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5354 (rmail-show-message message-number)
5355 message-number)
5356 (error "Message not found"))))
5357
5358 (defun org-open-file (path &optional in-emacs line)
5359 "Open the file at PATH.
5360 First, this expands any special file name abbreviations. Then the
5361 configuration variable `org-file-apps' is checked if it contains an
5362 entry for this file type, and if yes, the corresponding command is launched.
5363 If no application is found, Emacs simply visits the file.
5364 With optional argument IN-EMACS, Emacs will visit the file.
5365 If the file does not exist, an error is thrown."
5366 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5367 (dfile (downcase file))
5368 ext cmd apps)
5369 (if (and (not (file-exists-p file))
5370 (not org-open-non-existing-files))
5371 (error "No such file: %s" file))
5372 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5373 (setq ext (match-string 1 dfile))
5374 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5375 (setq ext (match-string 1 dfile))))
5376 (setq apps (append org-file-apps (org-default-apps)))
5377 (if in-emacs
5378 (setq cmd 'emacs)
5379 (setq cmd (or (cdr (assoc ext apps))
5380 (cdr (assoc t apps)))))
5381 (cond
5382 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5383 (setq cmd (format cmd (concat "\"" file "\"")))
5384 (save-window-excursion
5385 (shell-command (concat cmd " & &"))))
5386 ((or (stringp cmd)
5387 (eq cmd 'emacs))
5388 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5389 (if line (goto-line line)))
5390 ((consp cmd)
5391 (eval cmd))
5392 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5393
5394 (defun org-default-apps ()
5395 "Return the default applications for this operating system."
5396 (cond
5397 ((eq system-type 'darwin)
5398 org-file-apps-defaults-macosx)
5399 ((eq system-type 'windows-nt)
5400 org-file-apps-defaults-windowsnt)
5401 (t org-file-apps-defaults-gnu)))
5402
5403 (defun org-expand-file-name (path)
5404 "Replace special path abbreviations and expand the file name."
5405 (expand-file-name path))
5406
5407
5408 (defvar org-insert-link-history nil
5409 "Minibuffer history for links inserted with `org-insert-link'.")
5410
5411 (defvar org-stored-links nil
5412 "Contains the links stored with `org-store-link'.")
5413
5414 ;;;###autoload
5415 (defun org-store-link (arg)
5416 "\\<org-mode-map>Store an org-link to the current location.
5417 This link can later be inserted into an org-buffer with
5418 \\[org-insert-link].
5419 For some link types, a prefix arg is interpreted:
5420 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5421 For file links, arg negates `org-line-numbers-in-file-links'."
5422 (interactive "P")
5423 (let (link cpltxt)
5424 (cond
5425
5426 ((eq major-mode 'bbdb-mode)
5427 (setq cpltxt (concat
5428 "bbdb:"
5429 (or (bbdb-record-name (bbdb-current-record))
5430 (bbdb-record-company (bbdb-current-record))))
5431 link (org-make-link cpltxt)))
5432
5433 ((eq major-mode 'calendar-mode)
5434 (let ((cd (calendar-cursor-to-date)))
5435 (setq link
5436 (format-time-string
5437 (car org-time-stamp-formats)
5438 (apply 'encode-time
5439 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5440 nil nil nil))))))
5441
5442 ((or (eq major-mode 'vm-summary-mode)
5443 (eq major-mode 'vm-presentation-mode))
5444 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5445 (vm-follow-summary-cursor)
5446 (save-excursion
5447 (vm-select-folder-buffer)
5448 (let* ((message (car vm-message-pointer))
5449 (folder (buffer-file-name))
5450 (subject (vm-su-subject message))
5451 (author (vm-su-full-name message))
5452 (message-id (vm-su-message-id message)))
5453 (setq folder (abbreviate-file-name folder))
5454 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5455 folder)
5456 (setq folder (replace-match "" t t folder)))
5457 (setq cpltxt (concat author " on: " subject))
5458 (setq link (concat cpltxt "\n "
5459 (org-make-link
5460 "vm:" folder "#" message-id))))))
5461
5462 ((eq major-mode 'wl-summary-mode)
5463 (let* ((msgnum (wl-summary-message-number))
5464 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5465 msgnum 'message-id))
5466 (wl-message-entity (elmo-msgdb-overview-get-entity
5467 msgnum (wl-summary-buffer-msgdb)))
5468 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5469 (subject "???")) ; FIXME: How to get subject of email?
5470 (setq cpltxt (concat author " on: " subject))
5471 (setq link (concat cpltxt "\n "
5472 (org-make-link
5473 "wl:" wl-summary-buffer-folder-name
5474 "#" message-id)))))
5475
5476 ((eq major-mode 'rmail-mode)
5477 (save-excursion
5478 (save-restriction
5479 (rmail-narrow-to-non-pruned-header)
5480 (let ((folder (buffer-file-name))
5481 (message-id (mail-fetch-field "message-id"))
5482 (author (mail-fetch-field "from"))
5483 (subject (mail-fetch-field "subject")))
5484 (setq cpltxt (concat author " on: " subject))
5485 (setq link (concat cpltxt "\n "
5486 (org-make-link
5487 "rmail:" folder "#" message-id)))))))
5488
5489 ((eq major-mode 'gnus-group-mode)
5490 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5491 (gnus-group-group-name)) ; version
5492 ((fboundp 'gnus-group-name)
5493 (gnus-group-name))
5494 (t "???"))))
5495 (setq cpltxt (concat
5496 (if (org-xor arg org-usenet-links-prefer-google)
5497 "http://groups.google.com/groups?group="
5498 "gnus:")
5499 group)
5500 link (org-make-link cpltxt))))
5501
5502 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5503 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5504 (gnus-summary-beginning-of-article)
5505 (let* ((group (car gnus-article-current))
5506 (article (cdr gnus-article-current))
5507 (header (gnus-summary-article-header article))
5508 (author (mail-header-from header))
5509 (message-id (mail-header-id header))
5510 (date (mail-header-date header))
5511 (subject (gnus-summary-subject-string)))
5512 (setq cpltxt (concat author " on: " subject))
5513 (if (org-xor arg org-usenet-links-prefer-google)
5514 (setq link
5515 (concat
5516 cpltxt "\n "
5517 (format "http://groups.google.com/groups?as_umsgid=%s"
5518 (org-fixup-message-id-for-http message-id))))
5519 (setq link (concat cpltxt "\n"
5520 (org-make-link
5521 "gnus:" group
5522 "#" (number-to-string article)))))))
5523
5524 ((eq major-mode 'w3-mode)
5525 (setq cpltxt (url-view-url t)
5526 link (org-make-link cpltxt)))
5527 ((eq major-mode 'w3m-mode)
5528 (setq cpltxt w3m-current-url
5529 link (org-make-link cpltxt)))
5530
5531 ((buffer-file-name)
5532 ;; Just link to this file here.
5533 (setq cpltxt (concat "file:"
5534 (abbreviate-file-name (buffer-file-name))))
5535 ;; Add the line number?
5536 (if (org-xor org-line-numbers-in-file-links arg)
5537 (setq cpltxt
5538 (concat cpltxt
5539 ":" (int-to-string
5540 (+ (if (bolp) 1 0) (count-lines
5541 (point-min) (point)))))))
5542 (setq link (org-make-link cpltxt)))
5543
5544 ((interactive-p)
5545 (error "Cannot link to a buffer which is not visiting a file"))
5546
5547 (t (setq link nil)))
5548
5549 (if (and (interactive-p) link)
5550 (progn
5551 (setq org-stored-links
5552 (cons (cons (or cpltxt link) link) org-stored-links))
5553 (message "Stored: %s" (or cpltxt link)))
5554 link)))
5555
5556 (defun org-make-link (&rest strings)
5557 "Concatenate STRINGS, format resulting string with `org-link-format'."
5558 (format org-link-format (apply 'concat strings)))
5559
5560 (defun org-xor (a b)
5561 "Exclusive or."
5562 (if a (not b) b))
5563
5564 (defun org-get-header (header)
5565 "Find a header field in the current buffer."
5566 (save-excursion
5567 (goto-char (point-min))
5568 (let ((case-fold-search t) s)
5569 (cond
5570 ((eq header 'from)
5571 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5572 (setq s (match-string 1)))
5573 (while (string-match "\"" s)
5574 (setq s (replace-match "" t t s)))
5575 (if (string-match "[<(].*" s)
5576 (setq s (replace-match "" t t s))))
5577 ((eq header 'message-id)
5578 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5579 (setq s (match-string 1))))
5580 ((eq header 'subject)
5581 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5582 (setq s (match-string 1)))))
5583 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5584 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5585 s)))
5586
5587
5588 (defun org-fixup-message-id-for-http (s)
5589 "Replace special characters in a message id, so it can be used in an http query."
5590 (while (string-match "<" s)
5591 (setq s (replace-match "%3C" t t s)))
5592 (while (string-match ">" s)
5593 (setq s (replace-match "%3E" t t s)))
5594 (while (string-match "@" s)
5595 (setq s (replace-match "%40" t t s)))
5596 s)
5597
5598 (defun org-insert-link (&optional complete-file)
5599 "Insert a link. At the prompt, enter the link.
5600
5601 Completion can be used to select a link previously stored with
5602 `org-store-link'. When the empty string is entered (i.e. if you just
5603 press RET at the prompt), the link defaults to the most recently
5604 stored link. As SPC triggers completion in the minibuffer, you need to
5605 use M-SPC or C-q SPC to force the insertion of a space character.
5606
5607 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5608 selected using completion. The path to the file will be relative to
5609 the current directory if the file is in the current directory or a
5610 subdirectory. Otherwise, the link will be the absolute path as
5611 completed in the minibuffer (i.e. normally ~/path/to/file).
5612
5613 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5614 is in the current directory or below."
5615 (interactive "P")
5616 (let ((link (if complete-file
5617 (read-file-name "File: ")
5618 (completing-read
5619 "Link: " org-stored-links nil nil nil
5620 org-insert-link-history
5621 (or (car (car org-stored-links))))))
5622 linktxt matched)
5623 (if (or (not link) (equal link ""))
5624 (error "No links available"))
5625 (if complete-file
5626 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5627 (cond
5628 ((equal complete-file '(16))
5629 (insert
5630 (org-make-link
5631 "file:" (abbreviate-file-name (expand-file-name link)))))
5632 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5633 (expand-file-name link))
5634 (insert
5635 (org-make-link
5636 "file:" (match-string 1 (expand-file-name link)))))
5637 (t (insert (org-make-link "file:" link)))))
5638 (setq linktxt (cdr (assoc link org-stored-links)))
5639 (if (not org-keep-stored-link-after-insertion)
5640 (setq org-stored-links (delq (assoc link org-stored-links)
5641 org-stored-links)))
5642 (if (not linktxt) (setq link (org-make-link link)))
5643 (let ((lines (org-split-string (or linktxt link) "\n")))
5644 (insert (car lines))
5645 (setq matched (string-match org-link-regexp (car lines)))
5646 (setq lines (cdr lines))
5647 (while lines
5648 (insert "\n")
5649 (if (save-excursion
5650 (beginning-of-line 0)
5651 (looking-at "[ \t]+\\S-"))
5652 (indent-relative))
5653 (setq matched (or matched
5654 (string-match org-link-regexp (car lines))))
5655 (insert (car lines))
5656 (setq lines (cdr lines))))
5657 (unless matched
5658 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5659
5660 ;;; Hooks for remember.el
5661 ;;;###autoload
5662 (defun org-remember-annotation ()
5663 "Return a link to the current location as an annotation for remember.el.
5664 If you are using Org-mode files as target for data storage with
5665 remember.el, then the annotations should include a link compatible with the
5666 conventions in Org-mode. This function returns such a link."
5667 (org-store-link nil))
5668
5669 (defconst org-remember-help
5670 "Select a destination location for the note.
5671 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5672 RET at beg-of-buf -> Append to file as level 2 headline
5673 RET on headline -> Store as sublevel entry to current headline
5674 <left>/<right> -> before/after current headline, same headings level")
5675
5676 ;;;###autoload
5677 (defun org-remember-handler ()
5678 "Store stuff from remember.el into an org file.
5679 First prompts for an org file. If the user just presses return, the value
5680 of `org-default-notes-file' is used.
5681 Then the command offers the headings tree of the selected file in order to
5682 file the text at a specific location.
5683 You can either immediately press RET to get the note appended to the
5684 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5685 find a better place. Then press RET or <left> or <right> in insert the note.
5686
5687 Key Cursor position Note gets inserted
5688 -----------------------------------------------------------------------------
5689 RET buffer-start as level 2 heading at end of file
5690 RET on headline as sublevel of the heading at cursor
5691 RET no heading at cursor position, level taken from context.
5692 Or use prefix arg to specify level manually.
5693 <left> on headline as same level, before current heading
5694 <right> on headline as same level, after current heading
5695
5696 So the fastest way to store the note is to press RET RET to append it to
5697 the default file. This way your current train of thought is not
5698 interrupted, in accordance with the principles of remember.el. But with
5699 little extra effort, you can push it directly to the correct location.
5700
5701 Before being stored away, the function ensures that the text has a
5702 headline, i.e. a first line that starts with a \"*\". If not, a headline
5703 is constructed from the current date and some additional data.
5704
5705 If the variable `org-adapt-indentation' is non-nil, the entire text is
5706 also indented so that it starts in the same column as the headline
5707 \(i.e. after the stars).
5708
5709 See also the variable `org-reverse-note-order'."
5710 (catch 'quit
5711 (let* ((txt (buffer-substring (point-min) (point-max)))
5712 (fastp current-prefix-arg)
5713 (file (if fastp org-default-notes-file (org-get-org-file)))
5714 (visiting (find-buffer-visiting file))
5715 (org-startup-with-deadline-check nil)
5716 (org-startup-folded nil)
5717 spos level indent reversed)
5718 ;; Modify text so that it becomes a nice subtree which can be inserted
5719 ;; into an org tree.
5720 (let* ((lines (split-string txt "\n"))
5721 (first (car lines))
5722 (lines (cdr lines)))
5723 (if (string-match "^\\*+" first)
5724 ;; Is already a headline
5725 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5726 -1) ?\ ))
5727 ;; We need to add a headline: Use time and first buffer line
5728 (setq lines (cons first lines)
5729 first (concat "* " (current-time-string)
5730 " (" (remember-buffer-desc) ")")
5731 indent " "))
5732 (if org-adapt-indentation
5733 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5734 (setq txt (concat first "\n"
5735 (mapconcat 'identity lines "\n"))))
5736 ;; Find the file
5737 (if (not visiting)
5738 (find-file-noselect file))
5739 (with-current-buffer (get-file-buffer file)
5740 (setq reversed (org-notes-order-reversed-p))
5741 (save-excursion
5742 (save-restriction
5743 (widen)
5744 ;; Ask the User for a location
5745 (setq spos (if fastp 1 (org-get-location
5746 (current-buffer)
5747 org-remember-help)))
5748 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5749 ; not handle this note
5750 (goto-char spos)
5751 (cond ((bobp)
5752 ;; Put it at the start or end, as level 2
5753 (save-restriction
5754 (widen)
5755 (goto-char (if reversed (point-min) (point-max)))
5756 (if (not (bolp)) (newline))
5757 (org-paste-subtree (or current-prefix-arg 2) txt)))
5758 ((and (org-on-heading-p nil) (not current-prefix-arg))
5759 ;; Put it below this entry, at the beg/end of the subtree
5760 (org-back-to-heading)
5761 (setq level (outline-level))
5762 (if reversed
5763 (outline-end-of-heading)
5764 (outline-end-of-subtree))
5765 (if (not (bolp)) (newline))
5766 (beginning-of-line 1)
5767 (org-paste-subtree (1+ level) txt))
5768 (t
5769 ;; Put it right there, with automatic level determined by
5770 ;; org-paste-subtree or from prefix arg
5771 (org-paste-subtree current-prefix-arg txt)))
5772 (when remember-save-after-remembering
5773 (save-buffer)
5774 (if (not visiting) (kill-buffer (current-buffer)))))))))
5775 t) ;; return t to indicate that we took care of this note.
5776
5777 (defun org-get-org-file ()
5778 "Read a filename, with default directory `org-directory'."
5779 (let ((default (or org-default-notes-file remember-data-file)))
5780 (read-file-name (format "File name [%s]: " default)
5781 (file-name-as-directory org-directory)
5782 default)))
5783
5784 (defun org-notes-order-reversed-p ()
5785 "Check if the current file should receive notes in reversed order."
5786 (cond
5787 ((not org-reverse-note-order) nil)
5788 ((eq t org-reverse-note-order) t)
5789 ((not (listp org-reverse-note-order)) nil)
5790 (t (catch 'exit
5791 (let ((all org-reverse-note-order)
5792 entry)
5793 (while (setq entry (pop all))
5794 (if (string-match (car entry) (buffer-file-name))
5795 (throw 'exit (cdr entry))))
5796 nil)))))
5797
5798 ;;; Tables
5799
5800 ;; Watch out: Here we are talking about two different kind of tables.
5801 ;; Most of the code is for the tables created with the Org-mode table editor.
5802 ;; Sometimes, we talk about tables created and edited with the table.el
5803 ;; Emacs package. We call the former org-type tables, and the latter
5804 ;; table.el-type tables.
5805
5806
5807 (defun org-before-change-function (beg end)
5808 "Every change indicates that a table might need an update."
5809 (setq org-table-may-need-update t))
5810
5811 (defconst org-table-line-regexp "^[ \t]*|"
5812 "Detects an org-type table line.")
5813 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5814 "Detects an org-type table line.")
5815 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5816 "Detects a table line marked for automatic recalculation.")
5817 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5818 "Detects a table line marked for automatic recalculation.")
5819 (defconst org-table-hline-regexp "^[ \t]*|-"
5820 "Detects an org-type table hline.")
5821 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5822 "Detects a table-type table hline.")
5823 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5824 "Detects an org-type or table-type table.")
5825 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5826 "Searching from within a table (any type) this finds the first line
5827 outside the table.")
5828 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5829 "Searching from within a table (any type) this finds the first line
5830 outside the table.")
5831
5832 (defun org-table-create-with-table.el ()
5833 "Use the table.el package to insert a new table.
5834 If there is already a table at point, convert between Org-mode tables
5835 and table.el tables."
5836 (interactive)
5837 (require 'table)
5838 (cond
5839 ((org-at-table.el-p)
5840 (if (y-or-n-p "Convert table to Org-mode table? ")
5841 (org-table-convert)))
5842 ((org-at-table-p)
5843 (if (y-or-n-p "Convert table to table.el table? ")
5844 (org-table-convert)))
5845 (t (call-interactively 'table-insert))))
5846
5847 (defun org-table-create (&optional size)
5848 "Query for a size and insert a table skeleton.
5849 SIZE is a string Columns x Rows like for example \"3x2\"."
5850 (interactive "P")
5851 (unless size
5852 (setq size (read-string
5853 (concat "Table size Columns x Rows [e.g. "
5854 org-table-default-size "]: ")
5855 "" nil org-table-default-size)))
5856
5857 (let* ((pos (point))
5858 (indent (make-string (current-column) ?\ ))
5859 (split (org-split-string size " *x *"))
5860 (rows (string-to-number (nth 1 split)))
5861 (columns (string-to-number (car split)))
5862 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5863 "\n")))
5864 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5865 (point-at-bol) (point)))
5866 (beginning-of-line 1)
5867 (newline))
5868 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5869 (dotimes (i rows) (insert line))
5870 (goto-char pos)
5871 (if (> rows 1)
5872 ;; Insert a hline after the first row.
5873 (progn
5874 (end-of-line 1)
5875 (insert "\n|-")
5876 (goto-char pos)))
5877 (org-table-align)))
5878
5879 (defun org-table-convert-region (beg0 end0 nspace)
5880 "Convert region to a table.
5881 The region goes from BEG0 to END0, but these borders will be moved
5882 slightly, to make sure a beginning of line in the first line is included.
5883 When NSPACE is non-nil, it indicates the minimum number of spaces that
5884 separate columns (default: just one space)"
5885 (let* ((beg (min beg0 end0))
5886 (end (max beg0 end0))
5887 (tabsep t)
5888 re)
5889 (goto-char beg)
5890 (beginning-of-line 1)
5891 (setq beg (move-marker (make-marker) (point)))
5892 (goto-char end)
5893 (if (bolp) (backward-char 1) (end-of-line 1))
5894 (setq end (move-marker (make-marker) (point)))
5895 ;; Lets see if this is tab-separated material. If every nonempty line
5896 ;; contains a tab, we will assume that it is tab-separated material
5897 (if nspace
5898 (setq tabsep nil)
5899 (goto-char beg)
5900 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5901 (if nspace (setq tabsep nil))
5902 (if tabsep
5903 (setq re "^\\|\t")
5904 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5905 (max 1 (prefix-numeric-value nspace)))))
5906 (goto-char beg)
5907 (while (re-search-forward re end t)
5908 (replace-match "|" t t))
5909 (goto-char beg)
5910 (insert " ")
5911 (org-table-align)))
5912
5913 (defun org-table-import (file arg)
5914 "Import FILE as a table.
5915 The file is assumed to be tab-separated. Such files can be produced by most
5916 spreadsheet and database applications. If no tabs (at least one per line)
5917 are found, lines will be split on whitespace into fields."
5918 (interactive "f\nP")
5919 (or (bolp) (newline))
5920 (let ((beg (point))
5921 (pm (point-max)))
5922 (insert-file-contents file)
5923 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5924
5925 (defun org-table-export ()
5926 "Export table as a tab-separated file.
5927 Such a file can be imported into a spreadsheet program like Excel."
5928 (interactive)
5929 (let* ((beg (org-table-begin))
5930 (end (org-table-end))
5931 (table (buffer-substring beg end))
5932 (file (read-file-name "Export table to: "))
5933 buf)
5934 (unless (or (not (file-exists-p file))
5935 (y-or-n-p (format "Overwrite file %s? " file)))
5936 (error "Abort"))
5937 (with-current-buffer (find-file-noselect file)
5938 (setq buf (current-buffer))
5939 (erase-buffer)
5940 (fundamental-mode)
5941 (insert table)
5942 (goto-char (point-min))
5943 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5944 (replace-match "" t t)
5945 (end-of-line 1))
5946 (goto-char (point-min))
5947 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5948 (replace-match "" t t)
5949 (goto-char (min (1+ (point)) (point-max))))
5950 (goto-char (point-min))
5951 (while (re-search-forward "^-[-+]*$" nil t)
5952 (replace-match "")
5953 (if (looking-at "\n")
5954 (delete-char 1)))
5955 (goto-char (point-min))
5956 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5957 (replace-match "\t" t t))
5958 (save-buffer))
5959 (kill-buffer buf)))
5960
5961 (defvar org-table-aligned-begin-marker (make-marker)
5962 "Marker at the beginning of the table last aligned.
5963 Used to check if cursor still is in that table, to minimize realignment.")
5964 (defvar org-table-aligned-end-marker (make-marker)
5965 "Marker at the end of the table last aligned.
5966 Used to check if cursor still is in that table, to minimize realignment.")
5967 (defvar org-table-last-alignment nil
5968 "List of flags for flushright alignment, from the last re-alignment.
5969 This is being used to correctly align a single field after TAB or RET.")
5970 ;; FIXME: The following is currently not used.
5971 (defvar org-table-last-column-widths nil
5972 "List of max width of fields in each column.
5973 This is being used to correctly align a single field after TAB or RET.")
5974
5975 (defvar org-last-recalc-line nil)
5976
5977 (defun org-table-align ()
5978 "Align the table at point by aligning all vertical bars."
5979 (interactive)
5980 ;; (message "align") (sit-for 2)
5981 (let* (
5982 ;; Limits of table
5983 (beg (org-table-begin))
5984 (end (org-table-end))
5985 ;; Current cursor position
5986 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5987 (colpos (org-table-current-column))
5988 (winstart (window-start))
5989 text lines (new "") lengths l typenums ty fields maxfields i
5990 column
5991 (indent "") cnt frac
5992 rfmt hfmt
5993 (spaces (if (org-in-invisibility-spec-p '(org-table))
5994 org-table-spaces-around-invisible-separators
5995 org-table-spaces-around-separators))
5996 (sp1 (car spaces))
5997 (sp2 (cdr spaces))
5998 (rfmt1 (concat
5999 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6000 (hfmt1 (concat
6001 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6002 emptystrings)
6003 (untabify beg end)
6004 ;; (message "Aligning table...")
6005 ;; Get the rows
6006 (setq lines (org-split-string
6007 (buffer-substring-no-properties beg end) "\n"))
6008 ;; Store the indentation of the first line
6009 (if (string-match "^ *" (car lines))
6010 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6011 ;; Mark the hlines
6012 (setq lines (mapcar (lambda (l)
6013 (if (string-match "^ *|-" l)
6014 nil
6015 (if (string-match "[ \t]+$" l)
6016 (substring l 0 (match-beginning 0))
6017 l)))
6018 lines))
6019 ;; Get the data fields
6020 (setq fields (mapcar
6021 (lambda (l)
6022 (org-split-string l " *| *"))
6023 (delq nil (copy-sequence lines))))
6024 ;; How many fields in the longest line?
6025 (condition-case nil
6026 (setq maxfields (apply 'max (mapcar 'length fields)))
6027 (error
6028 (kill-region beg end)
6029 (org-table-create org-table-default-size)
6030 (error "Empty table - created default table")))
6031 ;; A list of empty string to fill any short rows on output
6032 (setq emptystrings (make-list maxfields ""))
6033 ;; Get the maximum length of a field and the most common datatype
6034 ;; for each column
6035 (setq i -1)
6036 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6037 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6038 ;; maximum length
6039 (push (apply 'max 1 (mapcar 'length column)) lengths)
6040 ;; compute the fraction stepwise, ignoring empty fields
6041 (setq cnt 0 frac 0.0)
6042 (mapcar
6043 (lambda (x)
6044 (if (equal x "")
6045 nil
6046 (setq frac ( / (+ (* frac cnt)
6047 (if (string-match org-table-number-regexp x) 1 0))
6048 (setq cnt (1+ cnt))))))
6049 column)
6050 (push (>= frac org-table-number-fraction) typenums))
6051 (setq lengths (nreverse lengths)
6052 typenums (nreverse typenums))
6053 (setq org-table-last-alignment typenums
6054 org-table-last-column-widths lengths)
6055 ;; Compute the formats needed for output of the table
6056 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6057 (while (setq l (pop lengths))
6058 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6059 (setq rfmt (concat rfmt (format rfmt1 ty l))
6060 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6061 (setq rfmt (concat rfmt "\n")
6062 hfmt (concat (substring hfmt 0 -1) "|\n"))
6063 ;; Produce the new table
6064 ;;(while lines
6065 ;; (setq l (pop lines))
6066 ;; (if l
6067 ;; (setq new (concat new (apply 'format rfmt
6068 ;; (append (pop fields) emptystrings))))
6069 ;; (setq new (concat new hfmt))))
6070 (setq new (mapconcat
6071 (lambda (l)
6072 (if l (apply 'format rfmt
6073 (append (pop fields) emptystrings))
6074 hfmt))
6075 lines ""))
6076 ;; Replace the old one
6077 (delete-region beg end)
6078 (move-marker end nil)
6079 (move-marker org-table-aligned-begin-marker (point))
6080 (insert new)
6081 (move-marker org-table-aligned-end-marker (point))
6082 ;; Try to move to the old location (approximately)
6083 (goto-line linepos)
6084 (set-window-start (selected-window) winstart 'noforce)
6085 (org-table-goto-column colpos)
6086 (setq org-table-may-need-update nil)
6087 (if (org-in-invisibility-spec-p '(org-table))
6088 (org-table-add-invisible-to-vertical-lines))
6089 ))
6090
6091 (defun org-table-begin (&optional table-type)
6092 "Find the beginning of the table and return its position.
6093 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6094 (save-excursion
6095 (if (not (re-search-backward
6096 (if table-type org-table-any-border-regexp
6097 org-table-border-regexp)
6098 nil t))
6099 (error "Can't find beginning of table")
6100 (goto-char (match-beginning 0))
6101 (beginning-of-line 2)
6102 (point))))
6103
6104 (defun org-table-end (&optional table-type)
6105 "Find the end of the table and return its position.
6106 With argument TABLE-TYPE, go to the end of a table.el-type table."
6107 (save-excursion
6108 (if (not (re-search-forward
6109 (if table-type org-table-any-border-regexp
6110 org-table-border-regexp)
6111 nil t))
6112 (goto-char (point-max))
6113 (goto-char (match-beginning 0)))
6114 (point-marker)))
6115
6116 (defun org-table-justify-field-maybe (&optional new)
6117 "Justify the current field, text to left, number to right.
6118 Optional argument NEW may specify text to replace the current field content."
6119 (cond
6120 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6121 ((org-at-table-hline-p)
6122 ;; FIXME: I use to enforce realign here, but I think this is not needed.
6123 ;; (setq org-table-may-need-update t)
6124 )
6125 ((and (not new)
6126 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6127 (current-buffer)))
6128 (< (point) org-table-aligned-begin-marker)
6129 (>= (point) org-table-aligned-end-marker)))
6130 ;; This is not the same table, force a full re-align
6131 (setq org-table-may-need-update t))
6132 (t ;; realign the current field, based on previous full realign
6133 (let* ((pos (point)) s
6134 (col (org-table-current-column))
6135 (num (nth (1- col) org-table-last-alignment))
6136 l f n o upd)
6137 (when (> col 0)
6138 (skip-chars-backward "^|\n")
6139 (if (looking-at " *\\([^|\n]*?\\) *|")
6140 (progn
6141 (setq s (match-string 1)
6142 o (match-string 0)
6143 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
6144 (setq f (format (if num " %%%ds |" " %%-%ds |") l)
6145 n (format f s t t))
6146 (if new
6147 (if (<= (length new) l)
6148 (setq n (format f new t t)) ;; FIXME: why t t?????
6149 (setq n (concat new "|") org-table-may-need-update t)))
6150 (or (equal n o)
6151 (let (org-table-may-need-update)
6152 (replace-match n))))
6153 (setq org-table-may-need-update t))
6154 (goto-char pos))))))
6155
6156 (defun org-table-next-field ()
6157 "Go to the next field in the current table.
6158 Before doing so, re-align the table if necessary."
6159 (interactive)
6160 (org-table-maybe-eval-formula)
6161 (org-table-maybe-recalculate-line)
6162 (if (and org-table-automatic-realign
6163 org-table-may-need-update)
6164 (org-table-align))
6165 (if (org-at-table-hline-p)
6166 (end-of-line 1))
6167 (condition-case nil
6168 (progn
6169 (re-search-forward "|" (org-table-end))
6170 (if (looking-at "[ \t]*$")
6171 (re-search-forward "|" (org-table-end)))
6172 (if (looking-at "-")
6173 (progn
6174 (beginning-of-line 0)
6175 (org-table-insert-row 'below))
6176 (if (looking-at " ") (forward-char 1))))
6177 (error
6178 (org-table-insert-row 'below))))
6179
6180 (defun org-table-previous-field ()
6181 "Go to the previous field in the table.
6182 Before doing so, re-align the table if necessary."
6183 (interactive)
6184 (org-table-justify-field-maybe)
6185 (org-table-maybe-recalculate-line)
6186 (if (and org-table-automatic-realign
6187 org-table-may-need-update)
6188 (org-table-align))
6189 (if (org-at-table-hline-p)
6190 (end-of-line 1))
6191 (re-search-backward "|" (org-table-begin))
6192 (re-search-backward "|" (org-table-begin))
6193 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6194 (re-search-backward "|" (org-table-begin)))
6195 (if (looking-at "| ?")
6196 (goto-char (match-end 0))))
6197
6198 (defun org-table-next-row ()
6199 "Go to the next row (same column) in the current table.
6200 Before doing so, re-align the table if necessary."
6201 (interactive)
6202 (org-table-maybe-eval-formula)
6203 (org-table-maybe-recalculate-line)
6204 (if (or (looking-at "[ \t]*$")
6205 (save-excursion (skip-chars-backward " \t") (bolp)))
6206 (newline)
6207 (if (and org-table-automatic-realign
6208 org-table-may-need-update)
6209 (org-table-align))
6210 (let ((col (org-table-current-column)))
6211 (beginning-of-line 2)
6212 (if (or (not (org-at-table-p))
6213 (org-at-table-hline-p))
6214 (progn
6215 (beginning-of-line 0)
6216 (org-table-insert-row 'below)))
6217 (org-table-goto-column col)
6218 (skip-chars-backward "^|\n\r")
6219 (if (looking-at " ") (forward-char 1)))))
6220
6221 (defun org-table-copy-down (n)
6222 "Copy a field down in the current column.
6223 If the field at the cursor is empty, copy into it the content of the nearest
6224 non-empty field above. With argument N, use the Nth non-empty field.
6225 If the current field is not empty, it is copied down to the next row, and
6226 the cursor is moved with it. Therefore, repeating this command causes the
6227 column to be filled row-by-row.
6228 If the variable `org-table-copy-increment' is non-nil and the field is an
6229 integer, it will be incremented while copying."
6230 (interactive "p")
6231 (let* ((colpos (org-table-current-column))
6232 (field (org-table-get-field))
6233 (non-empty (string-match "[^ \t]" field))
6234 (beg (org-table-begin))
6235 txt)
6236 (org-table-check-inside-data-field)
6237 (if non-empty
6238 (progn
6239 (setq txt (org-trim field))
6240 (org-table-next-row)
6241 (org-table-blank-field))
6242 (save-excursion
6243 (setq txt
6244 (catch 'exit
6245 (while (progn (beginning-of-line 1)
6246 (re-search-backward org-table-dataline-regexp
6247 beg t))
6248 (org-table-goto-column colpos t)
6249 (if (and (looking-at
6250 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6251 (= (setq n (1- n)) 0))
6252 (throw 'exit (match-string 1))))))))
6253 (if txt
6254 (progn
6255 (if (and org-table-copy-increment
6256 (string-match "^[0-9]+$" txt))
6257 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6258 (insert txt)
6259 (org-table-maybe-recalculate-line)
6260 (org-table-align))
6261 (error "No non-empty field found"))))
6262
6263 (defun org-table-check-inside-data-field ()
6264 "Is point inside a table data field?
6265 I.e. not on a hline or before the first or after the last column?"
6266 (if (or (not (org-at-table-p))
6267 (= (org-table-current-column) 0)
6268 (org-at-table-hline-p)
6269 (looking-at "[ \t]*$"))
6270 (error "Not in table data field")))
6271
6272 (defvar org-table-clip nil
6273 "Clipboard for table regions.")
6274
6275 (defun org-table-blank-field ()
6276 "Blank the current table field or active region."
6277 (interactive)
6278 (org-table-check-inside-data-field)
6279 (if (and (interactive-p) (org-region-active-p))
6280 (let (org-table-clip)
6281 (org-table-cut-region (region-beginning) (region-end)))
6282 (skip-chars-backward "^|")
6283 (backward-char 1)
6284 (if (looking-at "|[^|\n]+")
6285 (let* ((pos (match-beginning 0))
6286 (match (match-string 0))
6287 (len (length match)))
6288 (replace-match (concat "|" (make-string (1- len) ?\ )))
6289 (goto-char (+ 2 pos))
6290 (substring match 1)))))
6291
6292 (defun org-table-get-field (&optional n replace)
6293 "Return the value of the field in column N of current row.
6294 N defaults to current field.
6295 If REPLACE is a string, replace field with this value. The return value
6296 is always the old value."
6297 (and n (org-table-goto-column n))
6298 (skip-chars-backward "^|\n")
6299 (backward-char 1)
6300 (if (looking-at "|[^|\r\n]*")
6301 (let* ((pos (match-beginning 0))
6302 (val (buffer-substring (1+ pos) (match-end 0))))
6303 (if replace
6304 (replace-match (concat "|" replace)))
6305 (goto-char (min (point-at-eol) (+ 2 pos)))
6306 val)
6307 (forward-char 1) ""))
6308
6309 (defun org-table-current-column ()
6310 "Find out which column we are in.
6311 When called interactively, column is also displayed in echo area."
6312 (interactive)
6313 (if (interactive-p) (org-table-check-inside-data-field))
6314 (save-excursion
6315 (let ((cnt 0) (pos (point)))
6316 (beginning-of-line 1)
6317 (while (search-forward "|" pos t)
6318 (setq cnt (1+ cnt)))
6319 (if (interactive-p) (message "This is table column %d" cnt))
6320 cnt)))
6321
6322 (defun org-table-goto-column (n &optional on-delim force)
6323 "Move the cursor to the Nth column in the current table line.
6324 With optional argument ON-DELIM, stop with point before the left delimiter
6325 of the field.
6326 If there are less than N fields, just go to after the last delimiter.
6327 However, when FORCE is non-nil, create new columns if necessary."
6328 (let ((pos (point-at-eol)))
6329 (beginning-of-line 1)
6330 (when (> n 0)
6331 (while (and (> (setq n (1- n)) -1)
6332 (or (search-forward "|" pos t)
6333 (and force
6334 (progn (end-of-line 1)
6335 (skip-chars-backward "^|")
6336 (insert " | "))))))
6337 ; (backward-char 2) t)))))
6338 (when (and force (not (looking-at ".*|")))
6339 (save-excursion (end-of-line 1) (insert " | ")))
6340 (if on-delim
6341 (backward-char 1)
6342 (if (looking-at " ") (forward-char 1))))))
6343
6344 (defun org-at-table-p (&optional table-type)
6345 "Return t if the cursor is inside an org-type table.
6346 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6347 (if org-enable-table-editor
6348 (save-excursion
6349 (beginning-of-line 1)
6350 (looking-at (if table-type org-table-any-line-regexp
6351 org-table-line-regexp)))
6352 nil))
6353
6354 (defun org-table-recognize-table.el ()
6355 "If there is a table.el table nearby, recognize it and move into it."
6356 (if org-table-tab-recognizes-table.el
6357 (if (org-at-table.el-p)
6358 (progn
6359 (beginning-of-line 1)
6360 (if (looking-at org-table-dataline-regexp)
6361 nil
6362 (if (looking-at org-table1-hline-regexp)
6363 (progn
6364 (beginning-of-line 2)
6365 (if (looking-at org-table-any-border-regexp)
6366 (beginning-of-line -1)))))
6367 (if (re-search-forward "|" (org-table-end t) t)
6368 (progn
6369 (require 'table)
6370 (if (table--at-cell-p (point))
6371 t
6372 (message "recognizing table.el table...")
6373 (table-recognize-table)
6374 (message "recognizing table.el table...done")))
6375 (error "This should not happen..."))
6376 t)
6377 nil)
6378 nil))
6379
6380 (defun org-at-table.el-p ()
6381 "Return t if the cursor is inside a table.el-type table."
6382 (save-excursion
6383 (if (org-at-table-p 'any)
6384 (progn
6385 (goto-char (org-table-begin 'any))
6386 (looking-at org-table1-hline-regexp))
6387 nil)))
6388
6389 (defun org-at-table-hline-p ()
6390 "Return t if the cursor is inside a hline in a table."
6391 (if org-enable-table-editor
6392 (save-excursion
6393 (beginning-of-line 1)
6394 (looking-at org-table-hline-regexp))
6395 nil))
6396
6397 (defun org-table-insert-column ()
6398 "Insert a new column into the table."
6399 (interactive)
6400 (if (not (org-at-table-p))
6401 (error "Not at a table"))
6402 (org-table-find-dataline)
6403 (let* ((col (max 1 (org-table-current-column)))
6404 (beg (org-table-begin))
6405 (end (org-table-end))
6406 ;; Current cursor position
6407 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6408 (colpos col))
6409 (goto-char beg)
6410 (while (< (point) end)
6411 (if (org-at-table-hline-p)
6412 nil
6413 (org-table-goto-column col t)
6414 (insert "| "))
6415 (beginning-of-line 2))
6416 (move-marker end nil)
6417 (goto-line linepos)
6418 (org-table-goto-column colpos)
6419 (org-table-align)
6420 (org-table-modify-formulas 'insert col)))
6421
6422 (defun org-table-find-dataline ()
6423 "Find a dataline in the current table, which is needed for column commands."
6424 (if (and (org-at-table-p)
6425 (not (org-at-table-hline-p)))
6426 t
6427 (let ((col (current-column))
6428 (end (org-table-end)))
6429 (move-to-column col)
6430 (while (and (< (point) end)
6431 (or (not (= (current-column) col))
6432 (org-at-table-hline-p)))
6433 (beginning-of-line 2)
6434 (move-to-column col))
6435 (if (and (org-at-table-p)
6436 (not (org-at-table-hline-p)))
6437 t
6438 (error
6439 "Please position cursor in a data line for column operations")))))
6440
6441 (defun org-table-delete-column ()
6442 "Delete a column into the table."
6443 (interactive)
6444 (if (not (org-at-table-p))
6445 (error "Not at a table"))
6446 (org-table-find-dataline)
6447 (org-table-check-inside-data-field)
6448 (let* ((col (org-table-current-column))
6449 (beg (org-table-begin))
6450 (end (org-table-end))
6451 ;; Current cursor position
6452 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6453 (colpos col))
6454 (goto-char beg)
6455 (while (< (point) end)
6456 (if (org-at-table-hline-p)
6457 nil
6458 (org-table-goto-column col t)
6459 (and (looking-at "|[^|\n]+|")
6460 (replace-match "|")))
6461 (beginning-of-line 2))
6462 (move-marker end nil)
6463 (goto-line linepos)
6464 (org-table-goto-column colpos)
6465 (org-table-align)
6466 (org-table-modify-formulas 'remove col)))
6467
6468 (defun org-table-move-column-right ()
6469 "Move column to the right."
6470 (interactive)
6471 (org-table-move-column nil))
6472 (defun org-table-move-column-left ()
6473 "Move column to the left."
6474 (interactive)
6475 (org-table-move-column 'left))
6476
6477 (defun org-table-move-column (&optional left)
6478 "Move the current column to the right. With arg LEFT, move to the left."
6479 (interactive "P")
6480 (if (not (org-at-table-p))
6481 (error "Not at a table"))
6482 (org-table-find-dataline)
6483 (org-table-check-inside-data-field)
6484 (let* ((col (org-table-current-column))
6485 (col1 (if left (1- col) col))
6486 (beg (org-table-begin))
6487 (end (org-table-end))
6488 ;; Current cursor position
6489 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6490 (colpos (if left (1- col) (1+ col))))
6491 (if (and left (= col 1))
6492 (error "Cannot move column further left"))
6493 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6494 (error "Cannot move column further right"))
6495 (goto-char beg)
6496 (while (< (point) end)
6497 (if (org-at-table-hline-p)
6498 nil
6499 (org-table-goto-column col1 t)
6500 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6501 (replace-match "|\\2|\\1|")))
6502 (beginning-of-line 2))
6503 (move-marker end nil)
6504 (goto-line linepos)
6505 (org-table-goto-column colpos)
6506 (org-table-align)
6507 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6508
6509 (defun org-table-move-row-down ()
6510 "move table row down."
6511 (interactive)
6512 (org-table-move-row nil))
6513 (defun org-table-move-row-up ()
6514 "move table row up."
6515 (interactive)
6516 (org-table-move-row 'up))
6517
6518 (defun org-table-move-row (&optional up)
6519 "Move the current table line down. With arg UP, move it up."
6520 (interactive "P")
6521 (let ((col (current-column))
6522 (pos (point))
6523 (tonew (if up 0 2))
6524 txt)
6525 (beginning-of-line tonew)
6526 (if (not (org-at-table-p))
6527 (progn
6528 (goto-char pos)
6529 (error "Cannot move row further")))
6530 (goto-char pos)
6531 (beginning-of-line 1)
6532 (setq pos (point))
6533 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6534 (delete-region (point) (1+ (point-at-eol)))
6535 (beginning-of-line tonew)
6536 (insert txt)
6537 (beginning-of-line 0)
6538 (move-to-column col)))
6539
6540 (defun org-table-insert-row (&optional arg)
6541 "Insert a new row above the current line into the table.
6542 With prefix ARG, insert below the current line."
6543 (interactive "P")
6544 (if (not (org-at-table-p))
6545 (error "Not at a table"))
6546 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6547 new)
6548 (if (string-match "^[ \t]*|-" line)
6549 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6550 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6551 ;; Fix the first field if necessary
6552 (setq new (concat new))
6553 (if (string-match "^[ \t]*| *[#$] *|" line)
6554 (setq new (replace-match (match-string 0 line) t t new)))
6555 (beginning-of-line (if arg 2 1))
6556 (let (org-table-may-need-update)
6557 (insert-before-markers new)
6558 (insert-before-markers "\n"))
6559 (beginning-of-line 0)
6560 (re-search-forward "| ?" (point-at-eol) t)
6561 (and org-table-may-need-update (org-table-align))))
6562
6563 (defun org-table-insert-hline (&optional arg)
6564 "Insert a horizontal-line below the current line into the table.
6565 With prefix ARG, insert above the current line."
6566 (interactive "P")
6567 (if (not (org-at-table-p))
6568 (error "Not at a table"))
6569 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6570 (col (current-column))
6571 start)
6572 (if (string-match "^[ \t]*|-" line)
6573 (setq line
6574 (mapcar (lambda (x) (if (member x '(?| ?+))
6575 (prog1 (if start ?+ ?|) (setq start t))
6576 (if start ?- ?\ )))
6577 line))
6578 (setq line
6579 (mapcar (lambda (x) (if (equal x ?|)
6580 (prog1 (if start ?+ ?|) (setq start t))
6581 (if start ?- ?\ )))
6582 line)))
6583 (beginning-of-line (if arg 1 2))
6584 (apply 'insert line)
6585 (if (equal (char-before (point)) ?+)
6586 (progn (backward-delete-char 1) (insert "|")))
6587 (insert "\n")
6588 (beginning-of-line 0)
6589 (move-to-column col)))
6590
6591 (defun org-table-kill-row ()
6592 "Delete the current row or horizontal line from the table."
6593 (interactive)
6594 (if (not (org-at-table-p))
6595 (error "Not at a table"))
6596 (let ((col (current-column)))
6597 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6598 (if (not (org-at-table-p)) (beginning-of-line 0))
6599 (move-to-column col)))
6600
6601
6602 (defun org-table-cut-region (beg end)
6603 "Copy region in table to the clipboard and blank all relevant fields."
6604 (interactive "r")
6605 (org-table-copy-region beg end 'cut))
6606
6607 (defun org-table-copy-region (beg end &optional cut)
6608 "Copy rectangular region in table to clipboard.
6609 A special clipboard is used which can only be accessed
6610 with `org-table-paste-rectangle'"
6611 (interactive "rP")
6612 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6613 region cols
6614 (rpl (if cut " " nil)))
6615 (goto-char beg)
6616 (org-table-check-inside-data-field)
6617 (setq l01 (count-lines (point-min) (point))
6618 c01 (org-table-current-column))
6619 (goto-char end)
6620 (org-table-check-inside-data-field)
6621 (setq l02 (count-lines (point-min) (point))
6622 c02 (org-table-current-column))
6623 (setq l1 (min l01 l02) l2 (max l01 l02)
6624 c1 (min c01 c02) c2 (max c01 c02))
6625 (catch 'exit
6626 (while t
6627 (catch 'nextline
6628 (if (> l1 l2) (throw 'exit t))
6629 (goto-line l1)
6630 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6631 (setq cols nil ic1 c1 ic2 c2)
6632 (while (< ic1 (1+ ic2))
6633 (push (org-table-get-field ic1 rpl) cols)
6634 (setq ic1 (1+ ic1)))
6635 (push (nreverse cols) region)
6636 (setq l1 (1+ l1)))))
6637 (setq org-table-clip (nreverse region))
6638 (if cut (org-table-align))
6639 org-table-clip))
6640
6641 (defun org-table-paste-rectangle ()
6642 "Paste a rectangular region into a table.
6643 The upper right corner ends up in the current field. All involved fields
6644 will be overwritten. If the rectangle does not fit into the present table,
6645 the table is enlarged as needed. The process ignores horizontal separator
6646 lines."
6647 (interactive)
6648 (unless (and org-table-clip (listp org-table-clip))
6649 (error "First cut/copy a region to paste!"))
6650 (org-table-check-inside-data-field)
6651 (let* ((clip org-table-clip)
6652 (line (count-lines (point-min) (point)))
6653 (col (org-table-current-column))
6654 (org-enable-table-editor t)
6655 (org-table-automatic-realign nil)
6656 c cols field)
6657 (while (setq cols (pop clip))
6658 (while (org-at-table-hline-p) (beginning-of-line 2))
6659 (if (not (org-at-table-p))
6660 (progn (end-of-line 0) (org-table-next-field)))
6661 (setq c col)
6662 (while (setq field (pop cols))
6663 (org-table-goto-column c nil 'force)
6664 (org-table-get-field nil field)
6665 (setq c (1+ c)))
6666 (beginning-of-line 2))
6667 (goto-line line)
6668 (org-table-goto-column col)
6669 (org-table-align)))
6670
6671 (defun org-table-convert ()
6672 "Convert from `org-mode' table to table.el and back.
6673 Obviously, this only works within limits. When an Org-mode table is
6674 converted to table.el, all horizontal separator lines get lost, because
6675 table.el uses these as cell boundaries and has no notion of horizontal lines.
6676 A table.el table can be converted to an Org-mode table only if it does not
6677 do row or column spanning. Multiline cells will become multiple cells.
6678 Beware, Org-mode does not test if the table can be successfully converted - it
6679 blindly applies a recipe that works for simple tables."
6680 (interactive)
6681 (require 'table)
6682 (if (org-at-table.el-p)
6683 ;; convert to Org-mode table
6684 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6685 (end (move-marker (make-marker) (org-table-end t))))
6686 (table-unrecognize-region beg end)
6687 (goto-char beg)
6688 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6689 (replace-match ""))
6690 (goto-char beg))
6691 (if (org-at-table-p)
6692 ;; convert to table.el table
6693 (let ((beg (move-marker (make-marker) (org-table-begin)))
6694 (end (move-marker (make-marker) (org-table-end))))
6695 ;; first, get rid of all horizontal lines
6696 (goto-char beg)
6697 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6698 (replace-match ""))
6699 ;; insert a hline before first
6700 (goto-char beg)
6701 (org-table-insert-hline 'above)
6702 ;; insert a hline after each line
6703 (while (progn (beginning-of-line 2) (< (point) end))
6704 (org-table-insert-hline))
6705 (goto-char beg)
6706 (setq end (move-marker end (org-table-end)))
6707 ;; replace "+" at beginning and ending of hlines
6708 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6709 (replace-match "\\1+-"))
6710 (goto-char beg)
6711 (while (re-search-forward "-|[ \t]*$" end t)
6712 (replace-match "-+"))
6713 (goto-char beg)))))
6714
6715 (defun org-table-wrap-region (arg)
6716 "Wrap several fields in a column like a paragraph.
6717 This is useful if you'd like to spread the contents of a field over several
6718 lines, in order to keep the table compact.
6719
6720 If there is an active region, and both point and mark are in the same column,
6721 the text in the column is wrapped to minimum width for the given number of
6722 lines. Generally, this makes the table more compact. A prefix ARG may be
6723 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6724 formats the selected text to two lines. If the region was longer than 2
6725 lines, the remaining lines remain empty. A negative prefix argument reduces
6726 the current number of lines by that amount. The wrapped text is pasted back
6727 into the table. If you formatted it to more lines than it was before, fields
6728 further down in the table get overwritten - so you might need to make space in
6729 the table first.
6730
6731 If there is no region, the current field is split at the cursor position and
6732 the text fragment to the right of the cursor is prepended to the field one
6733 line down.
6734
6735 If there is no region, but you specify a prefix ARG, the current field gets
6736 blank, and the content is appended to the field above."
6737 (interactive "P")
6738 (org-table-check-inside-data-field)
6739 (if (org-region-active-p)
6740 ;; There is a region: fill as a paragraph
6741 (let ((beg (region-beginning))
6742 nlines)
6743 (org-table-cut-region (region-beginning) (region-end))
6744 (if (> (length (car org-table-clip)) 1)
6745 (error "Region must be limited to single column"))
6746 (setq nlines (if arg
6747 (if (< arg 1)
6748 (+ (length org-table-clip) arg)
6749 arg)
6750 (length org-table-clip)))
6751 (setq org-table-clip
6752 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6753 nil nlines)))
6754 (goto-char beg)
6755 (org-table-paste-rectangle))
6756 ;; No region, split the current field at point
6757 (if arg
6758 ;; combine with field above
6759 (let ((s (org-table-blank-field))
6760 (col (org-table-current-column)))
6761 (beginning-of-line 0)
6762 (while (org-at-table-hline-p) (beginning-of-line 0))
6763 (org-table-goto-column col)
6764 (skip-chars-forward "^|")
6765 (skip-chars-backward " ")
6766 (insert " " (org-trim s))
6767 (org-table-align))
6768 ;; split field
6769 (when (looking-at "\\([^|]+\\)+|")
6770 (let ((s (match-string 1)))
6771 (replace-match " |")
6772 (goto-char (match-beginning 0))
6773 (org-table-next-row)
6774 (insert (org-trim s) " ")
6775 (org-table-align))))))
6776
6777 (defun org-trim (s)
6778 "Remove whitespace at beginning and end of string."
6779 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6780 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6781 s)
6782
6783 (defun org-wrap (string &optional width lines)
6784 "Wrap string to either a number of lines, or a width in characters.
6785 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6786 that costs. If there is a word longer than WIDTH, the text is actually
6787 wrapped to the length of that word.
6788 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6789 many lines, whatever width that takes.
6790 The return value is a list of lines, without newlines at the end."
6791 (let* ((words (org-split-string string "[ \t\n]+"))
6792 (maxword (apply 'max (mapcar 'length words)))
6793 w ll)
6794 (cond (width
6795 (org-do-wrap words (max maxword width)))
6796 (lines
6797 (setq w maxword)
6798 (setq ll (org-do-wrap words maxword))
6799 (if (<= (length ll) lines)
6800 ll
6801 (setq ll words)
6802 (while (> (length ll) lines)
6803 (setq w (1+ w))
6804 (setq ll (org-do-wrap words w)))
6805 ll))
6806 (t (error "Cannot wrap this")))))
6807
6808
6809 (defun org-do-wrap (words width)
6810 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6811 (let (lines line)
6812 (while words
6813 (setq line (pop words))
6814 (while (and words (< (+ (length line) (length (car words))) width))
6815 (setq line (concat line " " (pop words))))
6816 (setq lines (push line lines)))
6817 (nreverse lines)))
6818
6819 ;; FIXME: I think I can make this more efficient
6820 (defun org-split-string (string &optional separators)
6821 "Splits STRING into substrings at SEPARATORS.
6822 No empty strings are returned if there are matches at the beginning
6823 and end of string."
6824 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6825 (start 0)
6826 notfirst
6827 (list nil))
6828 (while (and (string-match rexp string
6829 (if (and notfirst
6830 (= start (match-beginning 0))
6831 (< start (length string)))
6832 (1+ start) start))
6833 (< (match-beginning 0) (length string)))
6834 (setq notfirst t)
6835 (or (eq (match-beginning 0) 0)
6836 (and (eq (match-beginning 0) (match-end 0))
6837 (eq (match-beginning 0) start))
6838 (setq list
6839 (cons (substring string start (match-beginning 0))
6840 list)))
6841 (setq start (match-end 0)))
6842 (or (eq start (length string))
6843 (setq list
6844 (cons (substring string start)
6845 list)))
6846 (nreverse list)))
6847
6848 (defun org-table-add-invisible-to-vertical-lines ()
6849 "Add an `invisible' property to vertical lines of current table."
6850 (interactive)
6851 (let* ((beg (org-table-begin))
6852 (end (org-table-end))
6853 (end1))
6854 (save-excursion
6855 (goto-char beg)
6856 (while (< (point) end)
6857 (setq end1 (point-at-eol))
6858 (if (looking-at org-table-dataline-regexp)
6859 (while (re-search-forward "|" end1 t)
6860 (add-text-properties (1- (point)) (point)
6861 '(invisible org-table)))
6862 (while (re-search-forward "[+|]" end1 t)
6863 (add-text-properties (1- (point)) (point)
6864 '(invisible org-table))))
6865 (beginning-of-line 2)))))
6866
6867 (defun org-table-toggle-vline-visibility (&optional arg)
6868 "Toggle the visibility of table vertical lines.
6869 The effect is immediate and on all tables in the file.
6870 With prefix ARG, make lines invisible when ARG is positive, make lines
6871 visible when ARG is not positive"
6872 (interactive "P")
6873 (let ((action (cond
6874 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6875 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6876 (t (if (org-in-invisibility-spec-p '(org-table))
6877 'off
6878 'on)))))
6879 (if (eq action 'off)
6880 (progn
6881 (org-remove-from-invisibility-spec '(org-table))
6882 (org-table-map-tables 'org-table-align)
6883 (message "Vertical table lines visible")
6884 (if (org-at-table-p)
6885 (org-table-align)))
6886 (org-add-to-invisibility-spec '(org-table))
6887 (org-table-map-tables 'org-table-align)
6888 (message "Vertical table lines invisible"))
6889 (redraw-frame (selected-frame))))
6890
6891 (defun org-table-map-tables (function)
6892 "Apply FUNCTION to the start of all tables in the buffer."
6893 (save-excursion
6894 (save-restriction
6895 (widen)
6896 (goto-char (point-min))
6897 (while (re-search-forward org-table-any-line-regexp nil t)
6898 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6899 (beginning-of-line 1)
6900 (if (looking-at org-table-line-regexp)
6901 (save-excursion (funcall function)))
6902 (re-search-forward org-table-any-border-regexp nil 1)))))
6903
6904 (defun org-table-sum (&optional beg end nlast)
6905 "Sum numbers in region of current table column.
6906 The result will be displayed in the echo area, and will be available
6907 as kill to be inserted with \\[yank].
6908
6909 If there is an active region, it is interpreted as a rectangle and all
6910 numbers in that rectangle will be summed. If there is no active
6911 region and point is located in a table column, sum all numbers in that
6912 column.
6913
6914 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6915 numbers are assumed to be times as well (in decimal hours) and the
6916 numbers are added as such.
6917
6918 If NLAST is a number, only the NLAST fields will actually be summed."
6919 (interactive)
6920 (save-excursion
6921 (let (col (timecnt 0) diff h m s org-table-clip)
6922 (cond
6923 ((and beg end)) ; beg and end given explicitly
6924 ((org-region-active-p)
6925 (setq beg (region-beginning) end (region-end)))
6926 (t
6927 (setq col (org-table-current-column))
6928 (goto-char (org-table-begin))
6929 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6930 (error "No table data"))
6931 (org-table-goto-column col)
6932 ;not needed? (skip-chars-backward "^|")
6933 (setq beg (point))
6934 (goto-char (org-table-end))
6935 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6936 (error "No table data"))
6937 (org-table-goto-column col)
6938 ;not needed? (skip-chars-forward "^|")
6939 (setq end (point))))
6940 (let* ((items (apply 'append (org-table-copy-region beg end)))
6941 (items1 (cond ((not nlast) items)
6942 ((>= nlast (length items)) items)
6943 (t (setq items (reverse items))
6944 (setcdr (nthcdr (1- nlast) items) nil)
6945 (nreverse items))))
6946 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6947 items1)))
6948 (res (apply '+ numbers))
6949 (sres (if (= timecnt 0)
6950 (format "%g" res)
6951 (setq diff (* 3600 res)
6952 h (floor (/ diff 3600)) diff (mod diff 3600)
6953 m (floor (/ diff 60)) diff (mod diff 60)
6954 s diff)
6955 (format "%d:%02d:%02d" h m s))))
6956 (kill-new sres)
6957 (if (interactive-p)
6958 (message (substitute-command-keys
6959 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6960 (length numbers) sres))))
6961 sres))))
6962
6963 (defun org-table-get-number-for-summing (s)
6964 (let (n)
6965 (if (string-match "^ *|? *" s)
6966 (setq s (replace-match "" nil nil s)))
6967 (if (string-match " *|? *$" s)
6968 (setq s (replace-match "" nil nil s)))
6969 (setq n (string-to-number s))
6970 (cond
6971 ((and (string-match "0" s)
6972 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6973 ((string-match "\\`[ \t]+\\'" s) nil)
6974 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6975 (let ((h (string-to-number (or (match-string 1 s) "0")))
6976 (m (string-to-number (or (match-string 2 s) "0")))
6977 (s (string-to-number (or (match-string 4 s) "0"))))
6978 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6979 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6980 ((equal n 0) nil)
6981 (t n))))
6982
6983 (defvar org-table-formula-history nil)
6984
6985 (defun org-table-get-formula (&optional equation)
6986 "Read a formula from the minibuffer, offer stored formula as default."
6987 (let* ((col (org-table-current-column))
6988 (org-table-may-need-update nil)
6989 (stored-list (org-table-get-stored-formulas))
6990 (stored (cdr (assoc col stored-list)))
6991 (eq (cond
6992 ((and stored equation (string-match "^ *= *$" equation))
6993 stored)
6994 ((stringp equation)
6995 equation)
6996 (t (read-string
6997 "Formula: " (or stored "") 'org-table-formula-history
6998 stored)))))
6999 (if (not (string-match "\\S-" eq))
7000 (error "Empty formula"))
7001 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7002 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7003 (if stored
7004 (setcdr (assoc col stored-list) eq)
7005 (setq stored-list (cons (cons col eq) stored-list)))
7006 (if (not (equal stored eq))
7007 (org-table-store-formulas stored-list))
7008 eq))
7009
7010 (defun org-table-store-formulas (alist)
7011 "Store the list of formulas below the current table."
7012 (setq alist (sort alist (lambda (a b) (< (car a) (car b)))))
7013 (save-excursion
7014 (goto-char (org-table-end))
7015 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7016 (delete-region (point) (match-end 0)))
7017 (insert "#+TBLFM: "
7018 (mapconcat (lambda (x)
7019 (concat "$" (int-to-string (car x)) "=" (cdr x)))
7020 alist "::")
7021 "\n")))
7022
7023 (defun org-table-get-stored-formulas ()
7024 "Return an alist withh the t=stored formulas directly after current table."
7025 (interactive)
7026 (let (col eq eq-alist strings string)
7027 (save-excursion
7028 (goto-char (org-table-end))
7029 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7030 (setq strings (org-split-string (match-string 2) " *:: *"))
7031 (while (setq string (pop strings))
7032 (if (string-match "\\$\\([0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7033 (setq col (string-to-number (match-string 1 string))
7034 eq (match-string 2 string)
7035 eq-alist (cons (cons col eq) eq-alist))))))
7036 eq-alist))
7037
7038 (defun org-table-modify-formulas (action &rest columns)
7039 "Modify the formulas stored below the current table.
7040 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7041 expected, for the other action only a single column number is needed."
7042 (let ((list (org-table-get-stored-formulas))
7043 (nmax (length (org-split-string (buffer-substring (point-at-bol) (point-at-eol))
7044 "|")))
7045 col col1 col2)
7046 (cond
7047 ((null list)) ; No action needed if there are no stored formulas
7048 ((eq action 'remove)
7049 (setq col (car columns))
7050 (org-table-replace-in-formulas list col "INVALID")
7051 (if (assoc col list) (setq list (delq (assoc col list) list)))
7052 (loop for i from (1+ col) upto nmax by 1 do
7053 (org-table-replace-in-formulas list i (1- i))
7054 (if (assoc i list) (setcar (assoc i list) (1- i)))))
7055 ((eq action 'insert)
7056 (setq col (car columns))
7057 (loop for i from nmax downto col by 1 do
7058 (org-table-replace-in-formulas list i (1+ i))
7059 (if (assoc i list) (setcar (assoc i list) (1+ i)))))
7060 ((eq action 'swap)
7061 (setq col1 (car columns) col2 (nth 1 columns))
7062 (org-table-replace-in-formulas list col1 "Z")
7063 (org-table-replace-in-formulas list col2 col1)
7064 (org-table-replace-in-formulas list "Z" col2)
7065 (if (assoc col1 list) (setcar (assoc col1 list) "Z"))
7066 (if (assoc col2 list) (setcar (assoc col2 list) col1))
7067 (if (assoc "Z" list) (setcar (assoc "Z" list) col2)))
7068 (t (error "Invalid action in `org-table-modify-formulas'")))
7069 (if list (org-table-store-formulas list))))
7070
7071 (defun org-table-replace-in-formulas (list s1 s2)
7072 (let (elt re s)
7073 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7074 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7075 re (concat (regexp-quote s1) "\\>"))
7076 (while (setq elt (pop list))
7077 (setq s (cdr elt))
7078 (while (string-match re s)
7079 (setq s (replace-match s2 t t s)))
7080 (setcdr elt s))))
7081
7082 (defvar org-table-column-names nil
7083 "Alist with column names, derived from the `!' line.")
7084 (defvar org-table-column-name-regexp nil
7085 "Regular expression matching the current column names.")
7086 (defvar org-table-local-parameters nil
7087 "Alist with parameter names, derived from the `$' line.")
7088
7089 (defun org-table-get-specials ()
7090 "Get the column nmaes and local parameters for this table."
7091 (save-excursion
7092 (let ((beg (org-table-begin)) (end (org-table-end))
7093 names name fields fields1 field cnt c v)
7094 (setq org-table-column-names nil
7095 org-table-local-parameters nil)
7096 (goto-char beg)
7097 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7098 (setq names (org-split-string (match-string 1) " *| *")
7099 cnt 1)
7100 (while (setq name (pop names))
7101 (setq cnt (1+ cnt))
7102 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7103 (push (cons name (int-to-string cnt)) org-table-column-names))))
7104 (setq org-table-column-names (nreverse org-table-column-names))
7105 (setq org-table-column-name-regexp
7106 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7107 (goto-char beg)
7108 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7109 (setq fields (org-split-string (match-string 1) " *| *"))
7110 (while (setq field (pop fields))
7111 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7112 (push (cons (match-string 1 field) (match-string 2 field))
7113 org-table-local-parameters))))
7114 (goto-char beg)
7115 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7116 (setq c (match-string 1)
7117 fields (org-split-string (match-string 2) " *| *"))
7118 (save-excursion
7119 (beginning-of-line (if (equal c "_") 2 0))
7120 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7121 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7122 (while (setq field (pop fields))
7123 (setq v (pop fields1))
7124 (if (and (stringp field) (stringp v)
7125 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7126 (push (cons field v) org-table-local-parameters)))))))
7127
7128 (defun org-this-word ()
7129 ;; Get the current word
7130 (save-excursion
7131 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7132 (end (progn (skip-chars-forward "^ \t\n") (point))))
7133 (buffer-substring-no-properties beg end))))
7134
7135 (defun org-table-maybe-eval-formula ()
7136 "Check if the current field starts with \"=\" and evaluate the formula."
7137 ;; We already know we are in a table. Get field will only return a formula
7138 ;; when appropriate. It might return a separator line, but no problem.
7139 (when org-table-formula-evaluate-inline
7140 (let* ((field (org-trim (or (org-table-get-field) "")))
7141 (dfield (downcase field))
7142 col bolpos nlast)
7143 (when (equal (string-to-char field) ?=)
7144 (if (string-match "^\\(=sum[vh]?\\)\\([0-9]+\\)$" dfield)
7145 (setq nlast (1+ (string-to-number (match-string 2 dfield)))
7146 dfield (match-string 1 dfield)))
7147 (cond
7148 ((equal dfield "=sumh")
7149 (org-table-get-field
7150 nil (org-table-sum
7151 (save-excursion (org-table-goto-column 1) (point))
7152 (point) nlast)))
7153 ((member dfield '("=sum" "=sumv"))
7154 (setq col (org-table-current-column)
7155 bolpos (point-at-bol))
7156 (org-table-get-field
7157 nil (org-table-sum
7158 (save-excursion
7159 (goto-char (org-table-begin))
7160 (if (re-search-forward org-table-dataline-regexp bolpos t)
7161 (progn
7162 (goto-char (match-beginning 0))
7163 (org-table-goto-column col)
7164 (point))
7165 (error "No datalines above current")))
7166 (point) nlast)))
7167 ((and (string-match "^ *=" field)
7168 (fboundp 'calc-eval))
7169 (org-table-eval-formula nil field)))))))
7170
7171 (defvar org-last-recalc-undo-list nil)
7172 (defcustom org-table-allow-line-recalculation t
7173 "FIXME:"
7174 :group 'org-table
7175 :type 'boolean)
7176
7177 (defvar org-recalc-commands nil
7178 "List of commands triggering the reccalculation of a line.
7179 Will be filled automatically during use.")
7180
7181 (defvar org-recalc-marks
7182 '((" " . "Unmarked: no special line, no automatic recalculation")
7183 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7184 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7185 ("!" . "Column name definition line. Reference in formula as $name.")
7186 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7187 ("_" . "Names for values in row below this one.")
7188 ("^" . "Names for values in row above this one.")))
7189
7190 (defun org-table-rotate-recalc-marks (&optional newchar)
7191 "Rotate the recalculation mark in the first column.
7192 If in any row, the first field is not consistent with a mark,
7193 insert a new column for the makers.
7194 When there is an active region, change all the lines in the region,
7195 after prompting for the marking character.
7196 After each change, a message will be displayed indication the meaning
7197 of the new mark."
7198 (interactive)
7199 (unless (org-at-table-p) (error "Not at a table"))
7200 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7201 (beg (org-table-begin))
7202 (end (org-table-end))
7203 (l (org-current-line))
7204 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7205 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7206 (have-col
7207 (save-excursion
7208 (goto-char beg)
7209 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7210 (col (org-table-current-column))
7211 (forcenew (car (assoc newchar org-recalc-marks)))
7212 epos new)
7213 (if l1 (setq newchar (char-to-string (read-char-exclusive "Change region to what mark? Type # * ! $ or SPC: "))
7214 forcenew (car (assoc newchar org-recalc-marks))))
7215 (if (and newchar (not forcenew))
7216 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7217 newchar))
7218 (if l1 (goto-line l1))
7219 (save-excursion
7220 (beginning-of-line 1)
7221 (unless (looking-at org-table-dataline-regexp)
7222 (error "Not at a table data line")))
7223 (unless have-col
7224 (org-table-goto-column 1)
7225 (org-table-insert-column)
7226 (org-table-goto-column (1+ col)))
7227 (setq epos (point-at-eol))
7228 (save-excursion
7229 (beginning-of-line 1)
7230 (org-table-get-field
7231 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7232 (concat " "
7233 (setq new (or forcenew
7234 (cadr (member (match-string 1) marks))))
7235 " ")
7236 " # ")))
7237 (if (and l1 l2)
7238 (progn
7239 (goto-line l1)
7240 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7241 (and (looking-at org-table-dataline-regexp)
7242 (org-table-get-field 1 (concat " " new " "))))
7243 (goto-line l1)))
7244 (if (not (= epos (point-at-eol))) (org-table-align))
7245 (goto-line l)
7246 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7247
7248 (defun org-table-maybe-recalculate-line ()
7249 "Recompute the current line if marked for it, and if we haven't just done it."
7250 (interactive)
7251 (and org-table-allow-line-recalculation
7252 (not (and (memq last-command org-recalc-commands)
7253 (equal org-last-recalc-line (org-current-line))))
7254 (save-excursion (beginning-of-line 1)
7255 (looking-at org-table-auto-recalculate-regexp))
7256 (fboundp 'calc-eval)
7257 (org-table-recalculate) t))
7258
7259 (defvar org-table-formula-debug nil
7260 "Non-nil means, debug table formulas.
7261 When nil, simply write \"#ERROR\" in corrupted fields.")
7262
7263 (defvar modes)
7264 (defsubst org-set-calc-mode (var &optional value)
7265 (if (stringp var)
7266 (setq var (assoc var '(("D" calc-angle-mode deg)
7267 ("R" calc-angle-mode rad)
7268 ("F" calc-prefer-frac t)
7269 ("S" calc-symbolic-mode t)))
7270 value (nth 2 var) var (nth 1 var)))
7271 (if (memq var modes)
7272 (setcar (cdr (memq var modes)) value)
7273 (cons var (cons value modes)))
7274 modes)
7275
7276 (defun org-table-eval-formula (&optional ndown equation
7277 suppress-align suppress-const
7278 suppress-store)
7279 "Replace the table field value at the cursor by the result of a calculation.
7280
7281 This function makes use of Dave Gillespie's calc package, in my view the
7282 most exciting program ever written for GNU Emacs. So you need to have calc
7283 installed in order to use this function.
7284
7285 In a table, this command replaces the value in the current field with the
7286 result of a formula. While nowhere near the computation options of a
7287 spreadsheet program, this is still very useful. There is no automatic
7288 updating of a calculated field, but the table will remember the last
7289 formula for each column. The command needs to be applied again after
7290 changing input fields.
7291
7292 When called, the command first prompts for a formula, which is read in the
7293 minibuffer. Previously entered formulas are available through the history
7294 list, and the last used formula for each column is offered as a default.
7295 These stored formulas are adapted correctly when moving, inserting, or
7296 deleting columns with the corresponding commands.
7297
7298 The formula can be any algebraic expression understood by the calc package.
7299 Before evaluation, variable substitution takes place: \"$\" is replaced by
7300 the field the cursor is currently in, and $1..$n reference the fields in
7301 the current row. Values from a *different* row can *not* be referenced
7302 here, so the command supports only horizontal computing. The formula can
7303 contain an optional printf format specifier after a semicolon, to reformat
7304 the result.
7305
7306 A few examples for formulas:
7307 $1+$2 Sum of first and second field
7308 $1+$2;%.2f Same, and format result to two digits after dec.point
7309 exp($2)+exp($1) Math functions can be used
7310 $;%.1f Reformat current cell to 1 digit after dec.point
7311 ($3-32)*5/9 degrees F -> C conversion
7312
7313 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
7314 field, and to the same same column in all following rows, until reaching a
7315 horizontal line or the end of the table. When the command is called with a
7316 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
7317 to the current row, and to the following n-1 rows (but not beyond a
7318 separator line).
7319
7320 This function can also be called from Lisp programs and offers two additional
7321 Arguments: EQUATION can be the formula to apply. If this argument is given,
7322 the user will not be prompted. SUPPRESS-ALIGN is used to speed-up
7323 recursive calls by by-passing unnecessary aligns. SUPPRESS-CONST suppresses
7324 the interpretation of constants in the formula. SUPPRESS-STORE means the
7325 formula should not be stored, either because it is already stored, or because
7326 it is a modified equation that should not overwrite the stored one."
7327 (interactive "P")
7328 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
7329 (require 'calc)
7330 (org-table-check-inside-data-field)
7331 (org-table-get-specials)
7332 (let* (fields
7333 (org-table-automatic-realign nil)
7334 (case-fold-search nil)
7335 (down (> ndown 1))
7336 (formula (if (and equation suppress-store)
7337 equation
7338 (org-table-get-formula equation)))
7339 (n0 (org-table-current-column))
7340 (modes (copy-sequence org-calc-default-modes))
7341 n form fmt x ev orig c)
7342 ;; Parse the format string. Since we have a lot of modes, this is
7343 ;; a lot of work.
7344 (if (string-match ";" formula)
7345 (let ((tmp (org-split-string formula ";")))
7346 (setq formula (car tmp)
7347 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7348 (nth 1 tmp)))
7349 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7350 (setq c (string-to-char (match-string 1 fmt))
7351 n (string-to-number (or (match-string 1 fmt) "")))
7352 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7353 (setq modes (org-set-calc-mode
7354 'calc-float-format
7355 (list (cdr (assoc c '((?n. float) (?f. fix)
7356 (?s. sci) (?e. eng))))
7357 n))))
7358 (setq fmt (replace-match "" t t fmt)))
7359 (while (string-match "[DRFS]" fmt)
7360 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7361 (setq fmt (replace-match "" t t fmt)))
7362 (unless (string-match "\\S-" fmt)
7363 (setq fmt nil))))
7364 (if (and (not suppress-const) org-table-formula-use-constants)
7365 (setq formula (org-table-formula-substitute-names formula)))
7366 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7367 (while (> ndown 0)
7368 (setq fields (org-split-string
7369 (buffer-substring
7370 (point-at-bol) (point-at-eol)) " *| *"))
7371 (if org-table-formula-numbers-only
7372 (setq fields (mapcar
7373 (lambda (x) (number-to-string (string-to-number x)))
7374 fields)))
7375 (setq ndown (1- ndown))
7376 (setq form (copy-sequence formula))
7377 (while (string-match "\\$\\([0-9]+\\)?" form)
7378 (setq n (if (match-beginning 1)
7379 (string-to-int (match-string 1 form))
7380 n0)
7381 x (nth (1- n) fields))
7382 (unless x (error "Invalid field specifier \"%s\""
7383 (match-string 0 form)))
7384 (if (equal x "") (setq x "0"))
7385 (setq form (replace-match (concat "(" x ")") t t form)))
7386 (setq ev (calc-eval (cons form modes)
7387 (if org-table-formula-numbers-only 'num)))
7388
7389 (when org-table-formula-debug
7390 (with-output-to-temp-buffer "*Help*"
7391 (princ (format "Substitution history of formula
7392 Orig: %s
7393 $xyz-> %s
7394 $1-> %s\n" orig formula form))
7395 (if (listp ev)
7396 (princ (format " %s^\nError: %s"
7397 (make-string (car ev) ?\-) (nth 1 ev)))
7398 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7399 ev (or fmt "NONE")
7400 (if fmt (format fmt (string-to-number ev)) ev)))))
7401 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7402 (unless (and (interactive-p) (not ndown))
7403 (unless (let (inhibit-redisplay)
7404 (y-or-n-p "Debugging Formula. Continue to next? "))
7405 (org-table-align)
7406 (error "Abort"))
7407 (delete-window (get-buffer-window "*Help*"))
7408 (message "")))
7409 (if (listp ev) (setq fmt nil ev "#ERROR"))
7410 (org-table-justify-field-maybe
7411 (if fmt (format fmt (string-to-number ev)) ev))
7412 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7413 (call-interactively 'org-return)
7414 (setq ndown 0)))
7415 (and down (org-table-maybe-recalculate-line))
7416 (or suppress-align (and org-table-may-need-update
7417 (org-table-align)))))
7418
7419 (defun org-table-recalculate (&optional all noalign)
7420 "Recalculate the current table line by applying all stored formulas."
7421 (interactive "P")
7422 (or (memq this-command org-recalc-commands)
7423 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7424 (unless (org-at-table-p) (error "Not at a table"))
7425 (org-table-get-specials)
7426 (let* ((eqlist (sort (org-table-get-stored-formulas)
7427 (lambda (a b) (< (car a) (car b)))))
7428 (inhibit-redisplay t)
7429 (line-re org-table-dataline-regexp)
7430 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7431 (thiscol (org-table-current-column))
7432 beg end entry eql (cnt 0))
7433 ;; Insert constants in all formulas
7434 (setq eqlist
7435 (mapcar (lambda (x)
7436 (setcdr x (org-table-formula-substitute-names (cdr x)))
7437 x)
7438 eqlist))
7439 (if all
7440 (progn
7441 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7442 (goto-char (setq beg (org-table-begin)))
7443 (if (re-search-forward org-table-recalculate-regexp end t)
7444 (setq line-re org-table-recalculate-regexp)
7445 (if (and (re-search-forward org-table-dataline-regexp end t)
7446 (re-search-forward org-table-hline-regexp end t)
7447 (re-search-forward org-table-dataline-regexp end t))
7448 (setq beg (match-beginning 0))
7449 nil))) ;; just leave beg where it is
7450 (setq beg (point-at-bol)
7451 end (move-marker (make-marker) (1+ (point-at-eol)))))
7452 (goto-char beg)
7453 (and all (message "Re-applying formulas to full table..."))
7454 (while (re-search-forward line-re end t)
7455 (unless (string-match "^ *[!$] *$" (org-table-get-field 1))
7456 ;; Unprotected line, recalculate
7457 (and all (message "Re-applying formulas to full table...(line %d)"
7458 (setq cnt (1+ cnt))))
7459 (setq org-last-recalc-line (org-current-line))
7460 (setq eql eqlist)
7461 (while (setq entry (pop eql))
7462 (goto-line org-last-recalc-line)
7463 (org-table-goto-column (car entry) nil 'force)
7464 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7465 (goto-line thisline)
7466 (org-table-goto-column thiscol)
7467 (or noalign (and org-table-may-need-update (org-table-align))
7468 (and all (message "Re-applying formulas to %d lines...done" cnt)))))
7469
7470 (defun org-table-formula-substitute-names (f)
7471 "Replace $const with values in stirng F."
7472 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7473 ;; First, check for column names
7474 (while (setq start (string-match org-table-column-name-regexp f start))
7475 (setq start (1+ start))
7476 (setq a (assoc (match-string 1 f) org-table-column-names))
7477 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7478 ;; Expand ranges to vectors
7479 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7480 (setq n1 (string-to-number (match-string 1 f))
7481 n2 (string-to-number (match-string 2 f))
7482 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7483 s (concat "[($" (number-to-string (1- nn1)) ")"))
7484 (loop for i from nn1 upto nn2 do
7485 (setq s (concat s ",($" (int-to-string i) ")")))
7486 (setq s (concat s "]"))
7487 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7488 (setq f (replace-match s t t f)))
7489 ;; Parameters and constants
7490 (setq start 0)
7491 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7492 (setq start (1+ start))
7493 (if (setq a (save-match-data
7494 (org-table-get-constant (match-string 1 f))))
7495 (setq f (replace-match (concat "(" a ")") t t f))))
7496 (if org-table-formula-debug
7497 (put-text-property 0 (length f) :orig-formula f1 f))
7498 f))
7499
7500 (defun org-table-get-constant (const)
7501 "Find the value for a parameter or constant in a formula.
7502 Parameters get priority."
7503 (or (cdr (assoc const org-table-local-parameters))
7504 (cdr (assoc const org-table-formula-constants))
7505 (and (fboundp 'constants-get) (constants-get const))
7506 "#UNDEFINED_NAME"))
7507
7508 ;;; The orgtbl minor mode
7509
7510 ;; Define a minor mode which can be used in other modes in order to
7511 ;; integrate the org-mode table editor.
7512
7513 ;; This is really a hack, because the org-mode table editor uses several
7514 ;; keys which normally belong to the major mode, for example the TAB and
7515 ;; RET keys. Here is how it works: The minor mode defines all the keys
7516 ;; necessary to operate the table editor, but wraps the commands into a
7517 ;; function which tests if the cursor is currently inside a table. If that
7518 ;; is the case, the table editor command is executed. However, when any of
7519 ;; those keys is used outside a table, the function uses `key-binding' to
7520 ;; look up if the key has an associated command in another currently active
7521 ;; keymap (minor modes, major mode, global), and executes that command.
7522 ;; There might be problems if any of the keys used by the table editor is
7523 ;; otherwise used as a prefix key.
7524
7525 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7526 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7527 ;; addresses this by checking explicitly for both bindings.
7528
7529 ;; The optimized version (see variable `orgtbl-optimized') takes over
7530 ;; all keys which are bound to `self-insert-command' in the *global map*.
7531 ;; Some modes bind other commands to simple characters, for example
7532 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7533 ;; active, this binding is ignored inside tables and replaced with a
7534 ;; modified self-insert.
7535
7536 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7537 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7538 In the optimized version, the table editor takes over all simple keys that
7539 normally just insert a character. In tables, the characters are inserted
7540 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7541 for empty fields). Outside tables, the correct binding of the keys is
7542 restored.
7543
7544 The default for this option is t if the optimized version is also used in
7545 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7546 this variable requires a restart of Emacs to become effective."
7547 :group 'org-table
7548 :type 'boolean)
7549
7550 (defvar orgtbl-mode nil
7551 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7552 table editor in arbitrary modes.")
7553 (make-variable-buffer-local 'orgtbl-mode)
7554
7555 (defvar orgtbl-mode-map (make-sparse-keymap)
7556 "Keymap for `orgtbl-mode'.")
7557
7558 ;;;###autoload
7559 (defun turn-on-orgtbl ()
7560 "Unconditionally turn on `orgtbl-mode'."
7561 (orgtbl-mode 1))
7562
7563 ;;;###autoload
7564 (defun orgtbl-mode (&optional arg)
7565 "The `org-mode' table editor as a minor mode for use in other modes."
7566 (interactive)
7567 (if (eq major-mode 'org-mode)
7568 ;; Exit without error, in case some hook functions calls this
7569 ;; by accident in org-mode.
7570 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7571 (setq orgtbl-mode
7572 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7573 (if orgtbl-mode
7574 (progn
7575 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7576 ;; Make sure we are first in minor-mode-map-alist
7577 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7578 (and c (setq minor-mode-map-alist
7579 (cons c (delq c minor-mode-map-alist)))))
7580 (set (make-local-variable (quote org-table-may-need-update)) t)
7581 (make-local-hook (quote before-change-functions))
7582 (add-hook 'before-change-functions 'org-before-change-function
7583 nil 'local)
7584 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7585 auto-fill-inhibit-regexp)
7586 (set (make-local-variable 'auto-fill-inhibit-regexp)
7587 (if auto-fill-inhibit-regexp
7588 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7589 "[ \t]*|"))
7590 (easy-menu-add orgtbl-mode-menu)
7591 (run-hooks 'orgtbl-mode-hook))
7592 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7593 (remove-hook 'before-change-functions 'org-before-change-function t)
7594 (easy-menu-remove orgtbl-mode-menu)
7595 (force-mode-line-update 'all))))
7596
7597 ;; Install it as a minor mode.
7598 (put 'orgtbl-mode :included t)
7599 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7600 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7601
7602 (defun orgtbl-make-binding (fun n &rest keys)
7603 "Create a function for binding in the table minor mode.
7604 FUN is the command to call inside a table. N is used to create a unique
7605 command name. KEYS are keys that should be checked in for a command
7606 to execute outside of tables."
7607 (eval
7608 (list 'defun
7609 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7610 '(arg)
7611 (concat "In tables, run `" (symbol-name fun) "'.\n"
7612 "Outside of tables, run the binding of `"
7613 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7614 "'.")
7615 '(interactive "p")
7616 (list 'if
7617 '(org-at-table-p)
7618 (list 'call-interactively (list 'quote fun))
7619 (list 'let '(orgtbl-mode)
7620 (list 'call-interactively
7621 (append '(or)
7622 (mapcar (lambda (k)
7623 (list 'key-binding k))
7624 keys)
7625 '('orgtbl-error))))))))
7626
7627 (defun orgtbl-error ()
7628 "Error when there is no default binding for a table key."
7629 (interactive)
7630 (error "This key is has no function outside tables"))
7631
7632 (defun orgtbl-setup ()
7633 "Setup orgtbl keymaps."
7634 (let ((nfunc 0)
7635 (bindings
7636 (list
7637 '([(meta shift left)] org-table-delete-column)
7638 '([(meta left)] org-table-move-column-left)
7639 '([(meta right)] org-table-move-column-right)
7640 '([(meta shift right)] org-table-insert-column)
7641 '([(meta shift up)] org-table-kill-row)
7642 '([(meta shift down)] org-table-insert-row)
7643 '([(meta up)] org-table-move-row-up)
7644 '([(meta down)] org-table-move-row-down)
7645 '("\C-c\C-w" org-table-cut-region)
7646 '("\C-c\M-w" org-table-copy-region)
7647 '("\C-c\C-y" org-table-paste-rectangle)
7648 '("\C-c-" org-table-insert-hline)
7649 '([(shift tab)] org-table-previous-field)
7650 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7651 '("\C-m" org-table-next-row)
7652 (list (org-key 'S-return) 'org-table-copy-down)
7653 '([(meta return)] org-table-wrap-region)
7654 '("\C-c\C-q" org-table-wrap-region)
7655 '("\C-c?" org-table-current-column)
7656 '("\C-c " org-table-blank-field)
7657 '("\C-c+" org-table-sum)
7658 '("\C-c|" org-table-toggle-vline-visibility)
7659 '("\C-c=" org-table-eval-formula)
7660 '("\C-c*" org-table-recalculate)
7661 '([(control ?#)] org-table-rotate-recalc-marks)))
7662 elt key fun cmd)
7663 (while (setq elt (pop bindings))
7664 (setq nfunc (1+ nfunc))
7665 (setq key (car elt)
7666 fun (nth 1 elt)
7667 cmd (orgtbl-make-binding fun nfunc key))
7668 (define-key orgtbl-mode-map key cmd))
7669 ;; Special treatment needed for TAB and RET
7670 (define-key orgtbl-mode-map [(return)]
7671 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7672 (define-key orgtbl-mode-map "\C-m"
7673 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7674 (define-key orgtbl-mode-map [(tab)]
7675 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7676 (define-key orgtbl-mode-map "\C-i"
7677 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7678 (when orgtbl-optimized
7679 ;; If the user wants maximum table support, we need to hijack
7680 ;; some standard editing functions
7681 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7682 orgtbl-mode-map global-map)
7683 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7684 orgtbl-mode-map global-map)
7685 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7686 orgtbl-mode-map global-map)
7687 (define-key org-mode-map "|" 'self-insert-command))
7688 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7689 '("OrgTbl"
7690 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7691 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7692 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7693 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7694 "--"
7695 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7696 ["Copy Field from Above"
7697 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7698 "--"
7699 ("Column"
7700 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7701 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7702 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7703 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7704 ("Row"
7705 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7706 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7707 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7708 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7709 "--"
7710 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7711 ("Rectangle"
7712 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7713 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7714 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7715 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7716 "--"
7717 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7718 ["Eval Formula Down " (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7719 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7720 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7721 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7722 ["Sum Column/Rectangle" org-table-sum
7723 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7724 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7725 ["Debug Formulas"
7726 (setq org-table-formula-debug (not org-table-formula-debug))
7727 :style toggle :selected org-table-formula-debug]
7728 ))
7729 t)
7730
7731 (defun orgtbl-tab ()
7732 "Justification and field motion for `orgtbl-mode'."
7733 (interactive)
7734 (org-table-justify-field-maybe)
7735 (org-table-next-field))
7736
7737 (defun orgtbl-ret ()
7738 "Justification and field motion for `orgtbl-mode'."
7739 (interactive)
7740 (org-table-justify-field-maybe)
7741 (org-table-next-row))
7742
7743 (defun orgtbl-self-insert-command (N)
7744 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7745 If the cursor is in a table looking at whitespace, the whitespace is
7746 overwritten, and the table is not marked as requiring realignment."
7747 (interactive "p")
7748 (if (and (org-at-table-p)
7749 (eq N 1)
7750 (looking-at "[^|\n]* +|"))
7751 (let (org-table-may-need-update)
7752 (goto-char (1- (match-end 0)))
7753 (delete-backward-char 1)
7754 (goto-char (match-beginning 0))
7755 (self-insert-command N))
7756 (setq org-table-may-need-update t)
7757 (let (orgtbl-mode)
7758 (call-interactively (key-binding (vector last-input-event))))))
7759
7760 (defun orgtbl-delete-backward-char (N)
7761 "Like `delete-backward-char', insert whitespace at field end in tables.
7762 When deleting backwards, in tables this function will insert whitespace in
7763 front of the next \"|\" separator, to keep the table aligned. The table will
7764 still be marked for re-alignment, because a narrow field may lead to a
7765 reduced column width."
7766 (interactive "p")
7767 (if (and (org-at-table-p)
7768 (eq N 1)
7769 (string-match "|" (buffer-substring (point-at-bol) (point)))
7770 (looking-at ".*?|"))
7771 (let ((pos (point)))
7772 (backward-delete-char N)
7773 (skip-chars-forward "^|")
7774 (insert " ")
7775 (goto-char (1- pos)))
7776 (delete-backward-char N)))
7777
7778 (defun orgtbl-delete-char (N)
7779 "Like `delete-char', but insert whitespace at field end in tables.
7780 When deleting characters, in tables this function will insert whitespace in
7781 front of the next \"|\" separator, to keep the table aligned. The table
7782 will still be marked for re-alignment, because a narrow field may lead to
7783 a reduced column width."
7784 (interactive "p")
7785 (if (and (org-at-table-p)
7786 (not (bolp))
7787 (not (= (char-after) ?|))
7788 (eq N 1))
7789 (if (looking-at ".*?|")
7790 (let ((pos (point)))
7791 (replace-match (concat
7792 (substring (match-string 0) 1 -1)
7793 " |"))
7794 (goto-char pos)))
7795 (delete-char N)))
7796
7797 ;;; Exporting
7798
7799 (defconst org-level-max 20)
7800
7801 (defun org-export-find-first-heading-line (list)
7802 "Remove all lines from LIST which are before the first headline."
7803 (let ((orig-list list)
7804 (re (concat "^" outline-regexp)))
7805 (while (and list
7806 (not (string-match re (car list))))
7807 (pop list))
7808 (or list orig-list)))
7809
7810 (defun org-skip-comments (lines)
7811 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
7812 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
7813 (re2 "^\\(\\*+\\)[ \t\n\r]")
7814 rtn line level)
7815 (while (setq line (pop lines))
7816 (cond
7817 ((and (string-match re1 line)
7818 (setq level (- (match-end 1) (match-beginning 1))))
7819 ;; Beginning of a COMMENT subtree. Skip it.
7820 (while (and (setq line (pop lines))
7821 (or (not (string-match re2 line))
7822 (> (- (match-end 1) (match-beginning 1)) level))))
7823 (setq lines (cons line lines)))
7824 ((string-match "^#" line)
7825 ;; an ordinary comment line
7826 )
7827 (t (setq rtn (cons line rtn)))))
7828 (nreverse rtn)))
7829
7830 ;; ASCII
7831
7832 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
7833 "Characters for underlining headings in ASCII export.")
7834
7835 (defconst org-html-entities
7836 '(("nbsp")
7837 ("iexcl")
7838 ("cent")
7839 ("pound")
7840 ("curren")
7841 ("yen")
7842 ("brvbar")
7843 ("sect")
7844 ("uml")
7845 ("copy")
7846 ("ordf")
7847 ("laquo")
7848 ("not")
7849 ("shy")
7850 ("reg")
7851 ("macr")
7852 ("deg")
7853 ("plusmn")
7854 ("sup2")
7855 ("sup3")
7856 ("acute")
7857 ("micro")
7858 ("para")
7859 ("middot")
7860 ("odot"."o")
7861 ("star"."*")
7862 ("cedil")
7863 ("sup1")
7864 ("ordm")
7865 ("raquo")
7866 ("frac14")
7867 ("frac12")
7868 ("frac34")
7869 ("iquest")
7870 ("Agrave")
7871 ("Aacute")
7872 ("Acirc")
7873 ("Atilde")
7874 ("Auml")
7875 ("Aring") ("AA"."&Aring;")
7876 ("AElig")
7877 ("Ccedil")
7878 ("Egrave")
7879 ("Eacute")
7880 ("Ecirc")
7881 ("Euml")
7882 ("Igrave")
7883 ("Iacute")
7884 ("Icirc")
7885 ("Iuml")
7886 ("ETH")
7887 ("Ntilde")
7888 ("Ograve")
7889 ("Oacute")
7890 ("Ocirc")
7891 ("Otilde")
7892 ("Ouml")
7893 ("times")
7894 ("Oslash")
7895 ("Ugrave")
7896 ("Uacute")
7897 ("Ucirc")
7898 ("Uuml")
7899 ("Yacute")
7900 ("THORN")
7901 ("szlig")
7902 ("agrave")
7903 ("aacute")
7904 ("acirc")
7905 ("atilde")
7906 ("auml")
7907 ("aring")
7908 ("aelig")
7909 ("ccedil")
7910 ("egrave")
7911 ("eacute")
7912 ("ecirc")
7913 ("euml")
7914 ("igrave")
7915 ("iacute")
7916 ("icirc")
7917 ("iuml")
7918 ("eth")
7919 ("ntilde")
7920 ("ograve")
7921 ("oacute")
7922 ("ocirc")
7923 ("otilde")
7924 ("ouml")
7925 ("divide")
7926 ("oslash")
7927 ("ugrave")
7928 ("uacute")
7929 ("ucirc")
7930 ("uuml")
7931 ("yacute")
7932 ("thorn")
7933 ("yuml")
7934 ("fnof")
7935 ("Alpha")
7936 ("Beta")
7937 ("Gamma")
7938 ("Delta")
7939 ("Epsilon")
7940 ("Zeta")
7941 ("Eta")
7942 ("Theta")
7943 ("Iota")
7944 ("Kappa")
7945 ("Lambda")
7946 ("Mu")
7947 ("Nu")
7948 ("Xi")
7949 ("Omicron")
7950 ("Pi")
7951 ("Rho")
7952 ("Sigma")
7953 ("Tau")
7954 ("Upsilon")
7955 ("Phi")
7956 ("Chi")
7957 ("Psi")
7958 ("Omega")
7959 ("alpha")
7960 ("beta")
7961 ("gamma")
7962 ("delta")
7963 ("epsilon")
7964 ("varepsilon"."&epsilon;")
7965 ("zeta")
7966 ("eta")
7967 ("theta")
7968 ("iota")
7969 ("kappa")
7970 ("lambda")
7971 ("mu")
7972 ("nu")
7973 ("xi")
7974 ("omicron")
7975 ("pi")
7976 ("rho")
7977 ("sigmaf") ("varsigma"."&sigmaf;")
7978 ("sigma")
7979 ("tau")
7980 ("upsilon")
7981 ("phi")
7982 ("chi")
7983 ("psi")
7984 ("omega")
7985 ("thetasym") ("vartheta"."&thetasym;")
7986 ("upsih")
7987 ("piv")
7988 ("bull") ("bullet"."&bull;")
7989 ("hellip") ("dots"."&hellip;")
7990 ("prime")
7991 ("Prime")
7992 ("oline")
7993 ("frasl")
7994 ("weierp")
7995 ("image")
7996 ("real")
7997 ("trade")
7998 ("alefsym")
7999 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8000 ("uarr") ("uparrow"."&uarr;")
8001 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8002 ("darr")("downarrow"."&darr;")
8003 ("harr") ("leftrightarrow"."&harr;")
8004 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8005 ("lArr") ("Leftarrow"."&lArr;")
8006 ("uArr") ("Uparrow"."&uArr;")
8007 ("rArr") ("Rightarrow"."&rArr;")
8008 ("dArr") ("Downarrow"."&dArr;")
8009 ("hArr") ("Leftrightarrow"."&hArr;")
8010 ("forall")
8011 ("part") ("partial"."&part;")
8012 ("exist") ("exists"."&exist;")
8013 ("empty") ("emptyset"."&empty;")
8014 ("nabla")
8015 ("isin") ("in"."&isin;")
8016 ("notin")
8017 ("ni")
8018 ("prod")
8019 ("sum")
8020 ("minus")
8021 ("lowast") ("ast"."&lowast;")
8022 ("radic")
8023 ("prop") ("proptp"."&prop;")
8024 ("infin") ("infty"."&infin;")
8025 ("ang") ("angle"."&ang;")
8026 ("and") ("vee"."&and;")
8027 ("or") ("wedge"."&or;")
8028 ("cap")
8029 ("cup")
8030 ("int")
8031 ("there4")
8032 ("sim")
8033 ("cong") ("simeq"."&cong;")
8034 ("asymp")("approx"."&asymp;")
8035 ("ne") ("neq"."&ne;")
8036 ("equiv")
8037 ("le")
8038 ("ge")
8039 ("sub") ("subset"."&sub;")
8040 ("sup") ("supset"."&sup;")
8041 ("nsub")
8042 ("sube")
8043 ("supe")
8044 ("oplus")
8045 ("otimes")
8046 ("perp")
8047 ("sdot") ("cdot"."&sdot;")
8048 ("lceil")
8049 ("rceil")
8050 ("lfloor")
8051 ("rfloor")
8052 ("lang")
8053 ("rang")
8054 ("loz") ("Diamond"."&loz;")
8055 ("spades") ("spadesuit"."&spades;")
8056 ("clubs") ("clubsuit"."&clubs;")
8057 ("hearts") ("diamondsuit"."&hearts;")
8058 ("diams") ("diamondsuit"."&diams;")
8059 ("quot")
8060 ("amp")
8061 ("lt")
8062 ("gt")
8063 ("OElig")
8064 ("oelig")
8065 ("Scaron")
8066 ("scaron")
8067 ("Yuml")
8068 ("circ")
8069 ("tilde")
8070 ("ensp")
8071 ("emsp")
8072 ("thinsp")
8073 ("zwnj")
8074 ("zwj")
8075 ("lrm")
8076 ("rlm")
8077 ("ndash")
8078 ("mdash")
8079 ("lsquo")
8080 ("rsquo")
8081 ("sbquo")
8082 ("ldquo")
8083 ("rdquo")
8084 ("bdquo")
8085 ("dagger")
8086 ("Dagger")
8087 ("permil")
8088 ("lsaquo")
8089 ("rsaquo")
8090 ("euro")
8091
8092 ("arccos"."arccos")
8093 ("arcsin"."arcsin")
8094 ("arctan"."arctan")
8095 ("arg"."arg")
8096 ("cos"."cos")
8097 ("cosh"."cosh")
8098 ("cot"."cot")
8099 ("coth"."coth")
8100 ("csc"."csc")
8101 ("deg"."deg")
8102 ("det"."det")
8103 ("dim"."dim")
8104 ("exp"."exp")
8105 ("gcd"."gcd")
8106 ("hom"."hom")
8107 ("inf"."inf")
8108 ("ker"."ker")
8109 ("lg"."lg")
8110 ("lim"."lim")
8111 ("liminf"."liminf")
8112 ("limsup"."limsup")
8113 ("ln"."ln")
8114 ("log"."log")
8115 ("max"."max")
8116 ("min"."min")
8117 ("Pr"."Pr")
8118 ("sec"."sec")
8119 ("sin"."sin")
8120 ("sinh"."sinh")
8121 ("sup"."sup")
8122 ("tan"."tan")
8123 ("tanh"."tanh")
8124 )
8125 "Entities for TeX->HTML translation.
8126 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8127 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8128 In that case, \"\\ent\" will be translated to \"&other;\".
8129 The list contains HTML entities for Latin-1, Greek and other symbols.
8130 It is supplemented by a number of commonly used TeX macros with appropriate
8131 translations. There is currently no way for users to extend this.")
8132
8133 (defvar org-last-level nil) ; dynamically scoped variable
8134
8135 (defun org-export-as-ascii (arg)
8136 "Export the outline as a pretty ASCII file.
8137 If there is an active region, export only the region.
8138 The prefix ARG specifies how many levels of the outline should become
8139 underlined headlines. The default is 3."
8140 (interactive "P")
8141 (setq-default org-todo-line-regexp org-todo-line-regexp)
8142 (let* ((region
8143 (buffer-substring
8144 (if (org-region-active-p) (region-beginning) (point-min))
8145 (if (org-region-active-p) (region-end) (point-max))))
8146 (lines (org-export-find-first-heading-line
8147 (org-skip-comments (org-split-string region "[\r\n]"))))
8148 (org-startup-with-deadline-check nil)
8149 (level 0) line txt
8150 (umax nil)
8151 (case-fold-search nil)
8152 (filename (concat (file-name-sans-extension (buffer-file-name))
8153 ".txt"))
8154 (buffer (find-file-noselect filename))
8155 (levels-open (make-vector org-level-max nil))
8156 (date (format-time-string "%Y/%m/%d" (current-time)))
8157 (time (format-time-string "%X" (current-time)))
8158 (author user-full-name)
8159 (title (buffer-name))
8160 (options nil)
8161 (email user-mail-address)
8162 (language org-export-default-language)
8163 (text nil)
8164 (todo nil)
8165 (lang-words nil))
8166
8167 (setq org-last-level 1)
8168 (org-init-section-numbers)
8169
8170 (find-file-noselect filename)
8171
8172 ;; Search for the export key lines
8173 (org-parse-key-lines)
8174
8175 (setq lang-words (or (assoc language org-export-language-setup)
8176 (assoc "en" org-export-language-setup)))
8177 (if org-export-ascii-show-new-buffer
8178 (switch-to-buffer-other-window buffer)
8179 (set-buffer buffer))
8180 (erase-buffer)
8181 (fundamental-mode)
8182 (if options (org-parse-export-options options))
8183 (setq umax (if arg (prefix-numeric-value arg)
8184 org-export-headline-levels))
8185
8186 ;; File header
8187 (if title (org-insert-centered title ?=))
8188 (insert "\n")
8189 (if (or author email)
8190 (insert (concat (nth 1 lang-words) ": " (or author "")
8191 (if email (concat " <" email ">") "")
8192 "\n")))
8193 (if (and date time)
8194 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8195 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8196
8197 (insert "\n\n")
8198
8199 (if org-export-with-toc
8200 (progn
8201 (insert (nth 3 lang-words) "\n"
8202 (make-string (length (nth 3 lang-words)) ?=) "\n")
8203 (mapcar '(lambda (line)
8204 (if (string-match org-todo-line-regexp
8205 line)
8206 ;; This is a headline
8207 (progn
8208 (setq level (- (match-end 1) (match-beginning 1))
8209 txt (match-string 3 line)
8210 todo
8211 (or (and (match-beginning 2)
8212 (not (equal (match-string 2 line)
8213 org-done-string)))
8214 ; TODO, not DONE
8215 (and (= level umax)
8216 (org-search-todo-below
8217 line lines level))))
8218 (setq txt (org-html-expand-for-ascii txt))
8219
8220 (if org-export-with-section-numbers
8221 (setq txt (concat (org-section-number level)
8222 " " txt)))
8223 (if (<= level umax)
8224 (progn
8225 (insert
8226 (make-string (* (1- level) 4) ?\ )
8227 (format (if todo "%s (*)\n" "%s\n") txt))
8228 (setq org-last-level level))
8229 ))))
8230 lines)))
8231
8232 (org-init-section-numbers)
8233 (while (setq line (pop lines))
8234 ;; Remove the quoted HTML tags.
8235 (setq line (org-html-expand-for-ascii line))
8236 (cond
8237 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8238 ;; a Headline
8239 (setq level (- (match-end 1) (match-beginning 1))
8240 txt (match-string 2 line))
8241 (org-ascii-level-start level txt umax))
8242 (t (insert line "\n"))))
8243 (normal-mode)
8244 (save-buffer)
8245 (goto-char (point-min))))
8246
8247 (defun org-search-todo-below (line lines level)
8248 "Search the subtree below LINE for any TODO entries."
8249 (let ((rest (cdr (memq line lines)))
8250 (re org-todo-line-regexp)
8251 line lv todo)
8252 (catch 'exit
8253 (while (setq line (pop rest))
8254 (if (string-match re line)
8255 (progn
8256 (setq lv (- (match-end 1) (match-beginning 1))
8257 todo (and (match-beginning 2)
8258 (not (equal (match-string 2 line)
8259 org-done-string))))
8260 ; TODO, not DONE
8261 (if (<= lv level) (throw 'exit nil))
8262 (if todo (throw 'exit t))))))))
8263
8264 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8265 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8266 (defun org-html-expand-for-ascii (line)
8267 "Handle quoted HTML for ASCII export."
8268 (if org-export-html-expand
8269 (while (string-match "@<[^<>\n]*>" line)
8270 ;; We just remove the tags for now.
8271 (setq line (replace-match "" nil nil line))))
8272 line)
8273
8274 (defun org-insert-centered (s &optional underline)
8275 "Insert the string S centered and underline it with character UNDERLINE."
8276 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8277 (insert (make-string ind ?\ ) s "\n")
8278 (if underline
8279 (insert (make-string ind ?\ )
8280 (make-string (length s) underline)
8281 "\n"))))
8282
8283 (defun org-ascii-level-start (level title umax)
8284 "Insert a new level in ASCII export."
8285 (let (char)
8286 (if (> level umax)
8287 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8288 (if (or (not (equal (char-before) ?\n))
8289 (not (equal (char-before (1- (point))) ?\n)))
8290 (insert "\n"))
8291 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8292 (if org-export-with-section-numbers
8293 (setq title (concat (org-section-number level) " " title)))
8294 (insert title "\n" (make-string (string-width title) char) "\n"))))
8295
8296 (defun org-export-copy-visible ()
8297 "Copy the visible part of the buffer to another buffer, for printing.
8298 Also removes the first line of the buffer if it specifies a mode,
8299 and all options lines."
8300 (interactive)
8301 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8302 ".txt"))
8303 (buffer (find-file-noselect filename))
8304 (ore (concat
8305 (org-make-options-regexp
8306 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8307 "STARTUP" "ARCHIVE"
8308 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8309 (if org-noutline-p "\\(\n\\|$\\)" "")))
8310 s e)
8311 (with-current-buffer buffer
8312 (erase-buffer)
8313 (text-mode))
8314 (save-excursion
8315 (setq s (goto-char (point-min)))
8316 (while (not (= (point) (point-max)))
8317 (goto-char (org-find-invisible))
8318 (append-to-buffer buffer s (point))
8319 (setq s (goto-char (org-find-visible)))))
8320 (switch-to-buffer-other-window buffer)
8321 (newline)
8322 (goto-char (point-min))
8323 (if (looking-at ".*-\\*- mode:.*\n")
8324 (replace-match ""))
8325 (while (re-search-forward ore nil t)
8326 (replace-match ""))
8327 (goto-char (point-min))))
8328
8329 (defun org-find-visible ()
8330 (if (featurep 'noutline)
8331 (let ((s (point)))
8332 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8333 (get-char-property s 'invisible)))
8334 s)
8335 (skip-chars-forward "^\n")
8336 (point)))
8337 (defun org-find-invisible ()
8338 (if (featurep 'noutline)
8339 (let ((s (point)))
8340 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8341 (not (get-char-property s 'invisible))))
8342 s)
8343 (skip-chars-forward "^\r")
8344 (point)))
8345
8346 ;; HTML
8347
8348 (defun org-get-current-options ()
8349 "Return a string with current options as keyword options.
8350 Does include HTML export options as well as TODO and CATEGORY stuff."
8351 (format
8352 "#+TITLE: %s
8353 #+AUTHOR: %s
8354 #+EMAIL: %s
8355 #+LANGUAGE: %s
8356 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8357 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8358 #+CATEGORY: %s
8359 #+SEQ_TODO: %s
8360 #+TYP_TODO: %s
8361 #+STARTUP: %s %s
8362 #+ARCHIVE: %s
8363 "
8364 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8365 org-export-headline-levels
8366 org-export-with-section-numbers
8367 org-export-with-toc
8368 org-export-preserve-breaks
8369 org-export-html-expand
8370 org-export-with-fixed-width
8371 org-export-with-tables
8372 org-export-with-sub-superscripts
8373 org-export-with-emphasize
8374 org-export-with-TeX-macros
8375 (file-name-nondirectory (buffer-file-name))
8376 (if (equal org-todo-interpretation 'sequence)
8377 (mapconcat 'identity org-todo-keywords " ")
8378 "TODO FEEDBACK VERIFY DONE")
8379 (if (equal org-todo-interpretation 'type)
8380 (mapconcat 'identity org-todo-keywords " ")
8381 "Me Jason Marie DONE")
8382 (cdr (assoc org-startup-folded
8383 '((nil . "nofold")(t . "fold")(content . "content"))))
8384 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8385 org-archive-location
8386 ))
8387
8388 (defun org-insert-export-options-template ()
8389 "Insert into the buffer a template with information for exporting."
8390 (interactive)
8391 (if (not (bolp)) (newline))
8392 (let ((s (org-get-current-options)))
8393 (and (string-match "#\\+CATEGORY" s)
8394 (setq s (substring s 0 (match-beginning 0))))
8395 (insert s)))
8396
8397 (defun org-toggle-fixed-width-section (arg)
8398 "Toggle the fixed-width indicator at the beginning of lines in the region.
8399 If there is no active region, only acts on the current line.
8400 If the first non-white character in the first line of the region is a
8401 vertical bar \"|\", then the command removes the bar from all lines in
8402 the region. If the first character is not a bar, the command adds a
8403 bar to all lines, in the column given by the beginning of the region.
8404
8405 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8406 (interactive "P")
8407 (let* ((cc 0)
8408 (regionp (org-region-active-p))
8409 (beg (if regionp (region-beginning) (point)))
8410 (end (if regionp (region-end)))
8411 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8412 (re "[ \t]*\\(:\\)")
8413 off)
8414 (save-excursion
8415 (goto-char beg)
8416 (setq cc (current-column))
8417 (beginning-of-line 1)
8418 (setq off (looking-at re))
8419 (while (> nlines 0)
8420 (setq nlines (1- nlines))
8421 (beginning-of-line 1)
8422 (cond
8423 (arg
8424 (move-to-column cc t)
8425 (insert ":\n")
8426 (forward-line -1))
8427 ((and off (looking-at re))
8428 (replace-match "" t t nil 1))
8429 ((not off) (move-to-column cc t) (insert ":")))
8430 (forward-line 1)))))
8431
8432 (defun org-export-as-html-and-open (arg)
8433 "Export the outline as HTML and immediately open it with a browser.
8434 If there is an active region, export only the region.
8435 The prefix ARG specifies how many levels of the outline should become
8436 headlines. The default is 3. Lower levels will become bulleted lists."
8437 (interactive "P")
8438 (org-export-as-html arg 'hidden)
8439 (org-open-file (buffer-file-name)))
8440
8441 (defun org-export-as-html-batch ()
8442 "Call `org-export-as-html', may be used in batch processing as
8443 emacs --batch
8444 --load=$HOME/lib/emacs/org.el
8445 --eval \"(setq org-export-headline-levels 2)\"
8446 --visit=MyFile --funcall org-export-as-html-batch"
8447 (org-export-as-html org-export-headline-levels 'hidden))
8448
8449 (defun org-export-as-html (arg &optional hidden)
8450 "Export the outline as a pretty HTML file.
8451 If there is an active region, export only the region.
8452 The prefix ARG specifies how many levels of the outline should become
8453 headlines. The default is 3. Lower levels will become bulleted lists."
8454 (interactive "P")
8455 (setq-default org-todo-line-regexp org-todo-line-regexp)
8456 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8457 (setq-default org-done-string org-done-string)
8458 (let* ((region-p (org-region-active-p))
8459 (region
8460 (buffer-substring
8461 (if region-p (region-beginning) (point-min))
8462 (if region-p (region-end) (point-max))))
8463 (all_lines
8464 (org-skip-comments (org-split-string region "[\r\n]")))
8465 (lines (org-export-find-first-heading-line all_lines))
8466 (level 0) (line "") (origline "") txt todo
8467 (umax nil)
8468 (filename (concat (file-name-sans-extension (buffer-file-name))
8469 ".html"))
8470 (buffer (find-file-noselect filename))
8471 (levels-open (make-vector org-level-max nil))
8472 (date (format-time-string "%Y/%m/%d" (current-time)))
8473 (time (format-time-string "%X" (current-time)))
8474 (author user-full-name)
8475 (title (buffer-name))
8476 (options nil)
8477 (email user-mail-address)
8478 (language org-export-default-language)
8479 (text nil)
8480 (lang-words nil)
8481 (head-count 0) cnt
8482 (start 0)
8483 table-open type
8484 table-buffer table-orig-buffer
8485 )
8486 (message "Exporting...")
8487
8488 (setq org-last-level 1)
8489 (org-init-section-numbers)
8490
8491 ;; Search for the export key lines
8492 (org-parse-key-lines)
8493 (setq lang-words (or (assoc language org-export-language-setup)
8494 (assoc "en" org-export-language-setup)))
8495
8496 ;; Switch to the output buffer
8497 (if (or hidden (not org-export-html-show-new-buffer))
8498 (set-buffer buffer)
8499 (switch-to-buffer-other-window buffer))
8500 (erase-buffer)
8501 (fundamental-mode)
8502 (let ((case-fold-search nil))
8503 (if options (org-parse-export-options options))
8504 (setq umax (if arg (prefix-numeric-value arg)
8505 org-export-headline-levels))
8506
8507 ;; File header
8508 (insert (format
8509 "<html lang=\"%s\"><head>
8510 <title>%s</title>
8511 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8512 <meta name=generator content=\"Org-mode\">
8513 <meta name=generated content=\"%s %s\">
8514 <meta name=author content=\"%s\">
8515 </head><body>
8516 "
8517 language (org-html-expand title) date time author))
8518 (if title (insert (concat "<H1 align=\"center\">"
8519 (org-html-expand title) "</H1>\n")))
8520 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8521 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8522 email "&gt;</a>\n")))
8523 (if (or author email) (insert "<br>\n"))
8524 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8525 date " " time "<br>\n")))
8526 (if text (insert (concat "<p>\n" (org-html-expand text))))
8527 (if org-export-with-toc
8528 (progn
8529 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8530 (insert "<ul>\n")
8531 (mapcar '(lambda (line)
8532 (if (string-match org-todo-line-regexp line)
8533 ;; This is a headline
8534 (progn
8535 (setq level (- (match-end 1) (match-beginning 1))
8536 txt (save-match-data
8537 (org-html-expand
8538 (match-string 3 line)))
8539 todo
8540 (or (and (match-beginning 2)
8541 (not (equal (match-string 2 line)
8542 org-done-string)))
8543 ; TODO, not DONE
8544 (and (= level umax)
8545 (org-search-todo-below
8546 line lines level))))
8547 (if org-export-with-section-numbers
8548 (setq txt (concat (org-section-number level)
8549 " " txt)))
8550 (if (<= level umax)
8551 (progn
8552 (setq head-count (+ head-count 1))
8553 (if (> level org-last-level)
8554 (progn
8555 (setq cnt (- level org-last-level))
8556 (while (>= (setq cnt (1- cnt)) 0)
8557 (insert "<ul>"))
8558 (insert "\n")))
8559 (if (< level org-last-level)
8560 (progn
8561 (setq cnt (- org-last-level level))
8562 (while (>= (setq cnt (1- cnt)) 0)
8563 (insert "</ul>"))
8564 (insert "\n")))
8565 (insert
8566 (format
8567 (if todo
8568 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8569 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8570 head-count txt))
8571 (setq org-last-level level))
8572 ))))
8573 lines)
8574 (while (> org-last-level 0)
8575 (setq org-last-level (1- org-last-level))
8576 (insert "</ul>\n"))
8577 ))
8578 (setq head-count 0)
8579 (org-init-section-numbers)
8580 (while (setq line (pop lines) origline line)
8581 ;; Protect the links
8582 (setq start 0)
8583 (while (string-match org-link-maybe-angles-regexp line start)
8584 (setq start (match-end 0))
8585 (setq line (replace-match
8586 (concat "\000" (match-string 1 line) "\000")
8587 t t line)))
8588
8589 ;; replace "<" and ">" by "&lt;" and "&gt;"
8590 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8591 (setq line (org-html-expand line))
8592
8593 ;; Verbatim lines
8594 (if (and org-export-with-fixed-width
8595 (string-match "^[ \t]*:\\(.*\\)" line))
8596 (progn
8597 (let ((l (match-string 1 line)))
8598 (while (string-match " " l)
8599 (setq l (replace-match "&nbsp;" t t l)))
8600 (insert "\n<span style='font-family:Courier'>"
8601 l "</span>"
8602 (if (and lines
8603 (not (string-match "^[ \t]+\\(:.*\\)"
8604 (car lines))))
8605 "<br>\n" "\n"))))
8606 (setq start 0)
8607 (while (string-match org-protected-link-regexp line start)
8608 (setq start (- (match-end 0) 2))
8609 (setq type (match-string 1 line))
8610 (cond
8611 ((member type '("http" "https" "ftp" "mailto" "news"))
8612 ;; standard URL
8613 (setq line (replace-match
8614 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8615 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8616 nil nil line)))
8617 ((string= type "file")
8618 ;; FILE link
8619 (let* ((filename (match-string 2 line))
8620 (abs-p (file-name-absolute-p filename))
8621 (thefile (if abs-p (expand-file-name filename) filename))
8622 (thefile (save-match-data
8623 (if (string-match ":[0-9]+$" thefile)
8624 (replace-match "" t t thefile)
8625 thefile)))
8626 (file-is-image-p
8627 (save-match-data
8628 (string-match (org-image-file-name-regexp) thefile))))
8629 (setq line (replace-match
8630 (if (and org-export-html-inline-images
8631 file-is-image-p)
8632 (concat "<img src=\"" thefile "\"/>")
8633 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8634 nil nil line))))
8635
8636 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8637 (setq line (replace-match
8638 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
8639
8640 ;; TODO items
8641 (if (and (string-match org-todo-line-regexp line)
8642 (match-beginning 2))
8643 (if (equal (match-string 2 line) org-done-string)
8644 (setq line (replace-match
8645 "<span style='color:green'>\\2</span>"
8646 nil nil line 2))
8647 (setq line (replace-match "<span style='color:red'>\\2</span>"
8648 nil nil line 2))))
8649
8650 ;; DEADLINES
8651 (if (string-match org-deadline-line-regexp line)
8652 (progn
8653 (if (save-match-data
8654 (string-match "<a href"
8655 (substring line 0 (match-beginning 0))))
8656 nil ; Don't do the replacement - it is inside a link
8657 (setq line (replace-match "<span style='color:red'>\\&</span>"
8658 nil nil line 1)))))
8659
8660 (cond
8661 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8662 ;; This is a headline
8663 (setq level (- (match-end 1) (match-beginning 1))
8664 txt (match-string 2 line))
8665 (if (<= level umax) (setq head-count (+ head-count 1)))
8666 (org-html-level-start level txt umax
8667 (and org-export-with-toc (<= level umax))
8668 head-count))
8669
8670 ((and org-export-with-tables
8671 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8672 (if (not table-open)
8673 ;; New table starts
8674 (setq table-open t table-buffer nil table-orig-buffer nil))
8675 ;; Accumulate lines
8676 (setq table-buffer (cons line table-buffer)
8677 table-orig-buffer (cons origline table-orig-buffer))
8678 (when (or (not lines)
8679 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8680 (car lines))))
8681 (setq table-open nil
8682 table-buffer (nreverse table-buffer)
8683 table-orig-buffer (nreverse table-orig-buffer))
8684 (insert (org-format-table-html table-buffer table-orig-buffer))))
8685 (t
8686 ;; Normal lines
8687 ;; Lines starting with "-", and empty lines make new paragraph.
8688 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8689 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8690 ))
8691 (if org-export-html-with-timestamp
8692 (insert org-export-html-html-helper-timestamp))
8693 (insert "</body>\n</html>\n")
8694 (normal-mode)
8695 (save-buffer)
8696 (goto-char (point-min)))))
8697
8698 (defun org-format-table-html (lines olines)
8699 "Find out which HTML converter to use and return the HTML code."
8700 (if (string-match "^[ \t]*|" (car lines))
8701 ;; A normal org table
8702 (org-format-org-table-html lines)
8703 ;; Table made by table.el - test for spanning
8704 (let* ((hlines (delq nil (mapcar
8705 (lambda (x)
8706 (if (string-match "^[ \t]*\\+-" x) x
8707 nil))
8708 lines)))
8709 (first (car hlines))
8710 (ll (and (string-match "\\S-+" first)
8711 (match-string 0 first)))
8712 (re (concat "^[ \t]*" (regexp-quote ll)))
8713 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8714 hlines))))
8715 (if (and (not spanning)
8716 (not org-export-prefer-native-exporter-for-tables))
8717 ;; We can use my own converter with HTML conversions
8718 (org-format-table-table-html lines)
8719 ;; Need to use the code generator in table.el, with the original text.
8720 (org-format-table-table-html-using-table-generate-source olines)))))
8721
8722 (defun org-format-org-table-html (lines)
8723 "Format a table into html."
8724 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8725 (setq lines (nreverse lines))
8726 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8727 (setq lines (nreverse lines))
8728 (let ((head (and org-export-highlight-first-table-line
8729 (delq nil (mapcar
8730 (lambda (x) (string-match "^[ \t]*|-" x))
8731 (cdr lines)))))
8732 line fields html)
8733 (setq html (concat org-export-html-table-tag "\n"))
8734 (while (setq line (pop lines))
8735 (catch 'next-line
8736 (if (string-match "^[ \t]*|-" line)
8737 (progn
8738 (setq head nil) ;; head ends here, first time around
8739 ;; ignore this line
8740 (throw 'next-line t)))
8741 ;; Break the line into fields
8742 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8743 (setq html (concat
8744 html
8745 "<tr>"
8746 (mapconcat (lambda (x)
8747 (if head
8748 (concat "<th>" x "</th>")
8749 (concat "<td valign=\"top\">" x "</td>")))
8750 fields "")
8751 "</tr>\n"))))
8752 (setq html (concat html "</table>\n"))
8753 html))
8754
8755 (defun org-fake-empty-table-line (line)
8756 "Replace everything except \"|\" with spaces."
8757 (let ((i (length line))
8758 (newstr (copy-sequence line)))
8759 (while (> i 0)
8760 (setq i (1- i))
8761 (if (not (eq (aref newstr i) ?|))
8762 (aset newstr i ?\ )))
8763 newstr))
8764
8765 (defun org-format-table-table-html (lines)
8766 "Format a table generated by table.el into html.
8767 This conversion does *not* use `table-generate-source' from table.el.
8768 This has the advantage that Org-mode's HTML conversions can be used.
8769 But it has the disadvantage, that no cell- or row-spanning is allowed."
8770 (let (line field-buffer
8771 (head org-export-highlight-first-table-line)
8772 fields html empty)
8773 (setq html (concat org-export-html-table-tag "\n"))
8774 (while (setq line (pop lines))
8775 (setq empty "&nbsp")
8776 (catch 'next-line
8777 (if (string-match "^[ \t]*\\+-" line)
8778 (progn
8779 (if field-buffer
8780 (progn
8781 (setq html (concat
8782 html
8783 "<tr>"
8784 (mapconcat
8785 (lambda (x)
8786 (if (equal x "") (setq x empty))
8787 (if head
8788 (concat "<th valign=\"top\">" x
8789 "</th>\n")
8790 (concat "<td valign=\"top\">" x
8791 "</td>\n")))
8792 field-buffer "\n")
8793 "</tr>\n"))
8794 (setq head nil)
8795 (setq field-buffer nil)))
8796 ;; Ignore this line
8797 (throw 'next-line t)))
8798 ;; Break the line into fields and store the fields
8799 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8800 (if field-buffer
8801 (setq field-buffer (mapcar
8802 (lambda (x)
8803 (concat x "<br>" (pop fields)))
8804 field-buffer))
8805 (setq field-buffer fields))))
8806 (setq html (concat html "</table>\n"))
8807 html))
8808
8809 (defun org-format-table-table-html-using-table-generate-source (lines)
8810 "Format a table into html, using `table-generate-source' from table.el.
8811 This has the advantage that cell- or row-spanning is allowed.
8812 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
8813 (require 'table)
8814 (with-current-buffer (get-buffer-create " org-tmp1 ")
8815 (erase-buffer)
8816 (insert (mapconcat 'identity lines "\n"))
8817 (goto-char (point-min))
8818 (if (not (re-search-forward "|[^+]" nil t))
8819 (error "Error processing table"))
8820 (table-recognize-table)
8821 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
8822 (table-generate-source 'html " org-tmp2 ")
8823 (set-buffer " org-tmp2 ")
8824 (buffer-substring (point-min) (point-max))))
8825
8826 (defun org-html-expand (string)
8827 "Prepare STRING for HTML export. Applies all active conversions."
8828 ;; First check if there is a link in the line - if yes, apply conversions
8829 ;; only before the start of the link.
8830 (let* ((m (string-match org-link-regexp string))
8831 (s (if m (substring string 0 m) string))
8832 (r (if m (substring string m) "")))
8833 ;; convert < to &lt; and > to &gt;
8834 (while (string-match "<" s)
8835 (setq s (replace-match "&lt;" t t s)))
8836 (while (string-match ">" s)
8837 (setq s (replace-match "&gt;" t t s)))
8838 (if org-export-html-expand
8839 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
8840 (setq s (replace-match "<\\1>" nil nil s))))
8841 (if org-export-with-emphasize
8842 (setq s (org-export-html-convert-emphasize s)))
8843 (if org-export-with-sub-superscripts
8844 (setq s (org-export-html-convert-sub-super s)))
8845 (if org-export-with-TeX-macros
8846 (let ((start 0) wd ass)
8847 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
8848 (setq wd (match-string 1 s))
8849 (if (setq ass (assoc wd org-html-entities))
8850 (setq s (replace-match (or (cdr ass)
8851 (concat "&" (car ass) ";"))
8852 t t s))
8853 (setq start (+ start (length wd)))))))
8854 (concat s r)))
8855
8856 (defun org-create-multibrace-regexp (left right n)
8857 "Create a regular expression which will match a balanced sexp.
8858 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
8859 as single character strings.
8860 The regexp returned will match the entire expression including the
8861 delimiters. It will also define a single group which contains the
8862 match except for the outermost delimiters. The maximum depth of
8863 stacked delimiters is N. Escaping delimiters is not possible."
8864 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
8865 (or "\\|")
8866 (re nothing)
8867 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
8868 (while (> n 1)
8869 (setq n (1- n)
8870 re (concat re or next)
8871 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
8872 (concat left "\\(" re "\\)" right)))
8873
8874 (defvar org-match-substring-regexp
8875 (concat
8876 "\\([^\\]\\)\\([_^]\\)\\("
8877 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
8878 "\\|"
8879 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
8880 "\\|"
8881 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
8882 "The regular expression matching a sub- or superscript.")
8883
8884 (defun org-export-html-convert-sub-super (string)
8885 "Convert sub- and superscripts in STRING to HTML."
8886 (let (key c)
8887 (while (string-match org-match-substring-regexp string)
8888 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
8889 (setq c (or (match-string 8 string)
8890 (match-string 6 string)
8891 (match-string 5 string)))
8892 (setq string (replace-match
8893 (concat (match-string 1 string)
8894 "<" key ">" c "</" key ">")
8895 t t string)))
8896 (while (string-match "\\\\\\([_^]\\)" string)
8897 (setq string (replace-match (match-string 1 string) t t string))))
8898 string)
8899
8900 (defun org-export-html-convert-emphasize (string)
8901 (while (string-match
8902 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
8903 string)
8904 (setq string (replace-match
8905 (concat "<b>" (match-string 3 string) "</b>")
8906 t t string 2)))
8907 (while (string-match
8908 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
8909 string)
8910 (setq string (replace-match
8911 (concat "<i>" (match-string 3 string) "</i>")
8912 t t string 2)))
8913 (while (string-match
8914 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
8915 string)
8916 (setq string (replace-match
8917 (concat "<u>" (match-string 3 string) "</u>")
8918 t t string 2)))
8919 string)
8920
8921 (defun org-parse-key-lines ()
8922 "Find the special key lines with the information for exporters."
8923 (save-excursion
8924 (goto-char 0)
8925 (let ((re (org-make-options-regexp
8926 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
8927 key)
8928 (while (re-search-forward re nil t)
8929 (setq key (match-string 1))
8930 (cond ((string-equal key "TITLE")
8931 (setq title (match-string 2)))
8932 ((string-equal key "AUTHOR")
8933 (setq author (match-string 2)))
8934 ((string-equal key "EMAIL")
8935 (setq email (match-string 2)))
8936 ((string-equal key "LANGUAGE")
8937 (setq language (match-string 2)))
8938 ((string-equal key "TEXT")
8939 (setq text (concat text "\n" (match-string 2))))
8940 ((string-equal key "OPTIONS")
8941 (setq options (match-string 2))))))))
8942
8943 (defun org-parse-export-options (s)
8944 "Parse the export options line."
8945 (let ((op '(("H" . org-export-headline-levels)
8946 ("num" . org-export-with-section-numbers)
8947 ("toc" . org-export-with-toc)
8948 ("\\n" . org-export-preserve-breaks)
8949 ("@" . org-export-html-expand)
8950 (":" . org-export-with-fixed-width)
8951 ("|" . org-export-with-tables)
8952 ("^" . org-export-with-sub-superscripts)
8953 ("*" . org-export-with-emphasize)
8954 ("TeX" . org-export-with-TeX-macros)))
8955 o)
8956 (while (setq o (pop op))
8957 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
8958 s)
8959 (set (make-local-variable (cdr o))
8960 (car (read-from-string (match-string 1 s))))))))
8961
8962 (defun org-html-level-start (level title umax with-toc head-count)
8963 "Insert a new level in HTML export."
8964 (let ((l (1+ (max level umax))))
8965 (while (<= l org-level-max)
8966 (if (aref levels-open (1- l))
8967 (progn
8968 (org-html-level-close l)
8969 (aset levels-open (1- l) nil)))
8970 (setq l (1+ l)))
8971 (if (> level umax)
8972 (progn
8973 (if (aref levels-open (1- level))
8974 (insert "<li>" title "<p>\n")
8975 (aset levels-open (1- level) t)
8976 (insert "<ul><li>" title "<p>\n")))
8977 (if org-export-with-section-numbers
8978 (setq title (concat (org-section-number level) " " title)))
8979 (setq level (+ level 1))
8980 (if with-toc
8981 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
8982 level head-count title level))
8983 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
8984
8985 (defun org-html-level-close (&rest args)
8986 "Terminate one level in HTML export."
8987 (insert "</ul>"))
8988
8989
8990 ;; Variable holding the vector with section numbers
8991 (defvar org-section-numbers (make-vector org-level-max 0))
8992
8993 (defun org-init-section-numbers ()
8994 "Initialize the vector for the section numbers."
8995 (let* ((level -1)
8996 (numbers (nreverse (org-split-string "" "\\.")))
8997 (depth (1- (length org-section-numbers)))
8998 (i depth) number-string)
8999 (while (>= i 0)
9000 (if (> i level)
9001 (aset org-section-numbers i 0)
9002 (setq number-string (or (car numbers) "0"))
9003 (if (string-match "\\`[A-Z]\\'" number-string)
9004 (aset org-section-numbers i
9005 (- (string-to-char number-string) ?A -1))
9006 (aset org-section-numbers i (string-to-int number-string)))
9007 (pop numbers))
9008 (setq i (1- i)))))
9009
9010 (defun org-section-number (&optional level)
9011 "Return a string with the current section number.
9012 When LEVEL is non-nil, increase section numbers on that level."
9013 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9014 (when level
9015 (when (> level -1)
9016 (aset org-section-numbers
9017 level (1+ (aref org-section-numbers level))))
9018 (setq idx (1+ level))
9019 (while (<= idx depth)
9020 (if (not (= idx 1))
9021 (aset org-section-numbers idx 0))
9022 (setq idx (1+ idx))))
9023 (setq idx 0)
9024 (while (<= idx depth)
9025 (setq n (aref org-section-numbers idx))
9026 (setq string (concat string (if (not (string= string "")) "." "")
9027 (int-to-string n)))
9028 (setq idx (1+ idx)))
9029 (save-match-data
9030 (if (string-match "\\`\\([@0]\\.\\)+" string)
9031 (setq string (replace-match "" nil nil string)))
9032 (if (string-match "\\(\\.0\\)+\\'" string)
9033 (setq string (replace-match "" nil nil string))))
9034 string))
9035
9036
9037 ;;; Key bindings
9038
9039 ;; - Bindings in Org-mode map are currently
9040 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9041 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9042 ;; e (?) useful from outline-mode
9043 ;; i k @ expendable from outline-mode
9044 ;; 0123456789 ! %^& ()_{} " `' free
9045
9046 (define-key org-mode-map "\C-i" 'org-cycle)
9047 (define-key org-mode-map [(meta tab)] 'org-complete)
9048 (define-key org-mode-map "\M-\C-i" 'org-complete)
9049 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9050 (define-key org-mode-map [(meta left)] 'org-metaleft)
9051 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9052 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9053 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9054 (define-key org-mode-map [(meta right)] 'org-metaright)
9055 (define-key org-mode-map [(meta up)] 'org-metaup)
9056 (define-key org-mode-map [(meta down)] 'org-metadown)
9057 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9058 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9059 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9060 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9061 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9062 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9063 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9064 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9065 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9066 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9067 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9068 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9069 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9070 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9071 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9072 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9073 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9074 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9075 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9076 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9077 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9078 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9079 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9080 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9081 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9082 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9083 (define-key org-mode-map "\C-c[" 'org-add-file)
9084 (define-key org-mode-map "\C-c]" 'org-remove-file)
9085 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9086 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9087 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9088 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9089 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9090 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9091 ;; The following line is necessary for German keyboards under Suse GNU/Linux
9092 (unless org-xemacs-p
9093 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9094 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9095 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9096 (define-key org-mode-map "\C-m" 'org-return)
9097 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9098 (define-key org-mode-map [(meta return)] 'org-meta-return)
9099 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9100 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9101 (define-key org-mode-map "\C-c+" 'org-table-sum)
9102 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9103 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9104 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9105 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9106 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9107 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9108 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9109 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9110 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9111 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9112 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9113 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9114 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9115 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9116 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9117 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9118
9119 (defsubst org-table-p () (org-at-table-p))
9120
9121 (defun org-self-insert-command (N)
9122 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9123 If the cursor is in a table looking at whitespace, the whitespace is
9124 overwritten, and the table is not marked as requiring realignment."
9125 (interactive "p")
9126 (if (and (org-table-p)
9127 (eq N 1)
9128 (looking-at "[^|\n]* +|"))
9129 (let (org-table-may-need-update)
9130 (goto-char (1- (match-end 0)))
9131 (delete-backward-char 1)
9132 (goto-char (match-beginning 0))
9133 (self-insert-command N))
9134 (setq org-table-may-need-update t)
9135 (self-insert-command N)))
9136
9137 ;; FIXME:
9138 ;; The following two functions might still be optimized to trigger
9139 ;; re-alignment less frequently.
9140
9141 (defun org-delete-backward-char (N)
9142 "Like `delete-backward-char', insert whitespace at field end in tables.
9143 When deleting backwards, in tables this function will insert whitespace in
9144 front of the next \"|\" separator, to keep the table aligned. The table will
9145 still be marked for re-alignment, because a narrow field may lead to a
9146 reduced column width."
9147 (interactive "p")
9148 (if (and (org-table-p)
9149 (eq N 1)
9150 (string-match "|" (buffer-substring (point-at-bol) (point)))
9151 (looking-at ".*?|"))
9152 (let ((pos (point)))
9153 (backward-delete-char N)
9154 (skip-chars-forward "^|")
9155 (insert " ")
9156 (goto-char (1- pos)))
9157 (backward-delete-char N)))
9158
9159 (defun org-delete-char (N)
9160 "Like `delete-char', but insert whitespace at field end in tables.
9161 When deleting characters, in tables this function will insert whitespace in
9162 front of the next \"|\" separator, to keep the table aligned. The table
9163 will still be marked for re-alignment, because a narrow field may lead to
9164 a reduced column width."
9165 (interactive "p")
9166 (if (and (org-table-p)
9167 (not (bolp))
9168 (not (= (char-after) ?|))
9169 (eq N 1))
9170 (if (looking-at ".*?|")
9171 (let ((pos (point)))
9172 (replace-match (concat
9173 (substring (match-string 0) 1 -1)
9174 " |"))
9175 (goto-char pos)))
9176 (delete-char N)))
9177
9178 ;; How to do this: Measure non-white length of current string
9179 ;; If equal to column width, we should realign.
9180
9181 (when (eq org-enable-table-editor 'optimized)
9182 ;; If the user wants maximum table support, we need to hijack
9183 ;; some standard editing functions
9184 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9185 org-mode-map global-map)
9186 (substitute-key-definition 'delete-char 'org-delete-char
9187 org-mode-map global-map)
9188 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9189 org-mode-map global-map)
9190 (define-key org-mode-map "|" 'self-insert-command))
9191
9192 (defun org-shiftcursor-error ()
9193 "Throw an error because Shift-Cursor command was applied in wrong context."
9194 (error "This command is only active in tables and on headlines"))
9195
9196 (defun org-shifttab ()
9197 "Call `(org-cycle t)' or `org-table-previous-field'."
9198 (interactive)
9199 (cond
9200 ((org-at-table-p) (org-table-previous-field))
9201 (t (org-cycle '(4)))))
9202
9203 (defun org-shiftmetaleft ()
9204 "Call `org-promote-subtree' or `org-table-delete-column'."
9205 (interactive)
9206 (cond
9207 ((org-at-table-p) (org-table-delete-column))
9208 ((org-on-heading-p) (org-promote-subtree))
9209 (t (org-shiftcursor-error))))
9210
9211 (defun org-shiftmetaright ()
9212 "Call `org-demote-subtree' or `org-table-insert-column'."
9213 (interactive)
9214 (cond
9215 ((org-at-table-p) (org-table-insert-column))
9216 ((org-on-heading-p) (org-demote-subtree))
9217 (t (org-shiftcursor-error))))
9218
9219 (defun org-shiftmetaup (&optional arg)
9220 "Call `org-move-subtree-up' or `org-table-kill-row'."
9221 (interactive "P")
9222 (cond
9223 ((org-at-table-p) (org-table-kill-row))
9224 ((org-on-heading-p) (org-move-subtree-up arg))
9225 (t (org-shiftcursor-error))))
9226 (defun org-shiftmetadown (&optional arg)
9227 "Call `org-move-subtree-down' or `org-table-insert-row'."
9228 (interactive "P")
9229 (cond
9230 ((org-at-table-p) (org-table-insert-row arg))
9231 ((org-on-heading-p) (org-move-subtree-down arg))
9232 (t (org-shiftcursor-error))))
9233
9234 (defun org-metaleft (&optional arg)
9235 "Call `org-do-promote' or `org-table-move-column' to left."
9236 (interactive "P")
9237 (cond
9238 ((org-at-table-p) (org-table-move-column 'left))
9239 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9240 (t (backward-word (prefix-numeric-value arg)))))
9241
9242 (defun org-metaright (&optional arg)
9243 "Call `org-do-demote' or `org-table-move-column' to right."
9244 (interactive "P")
9245 (cond
9246 ((org-at-table-p) (org-table-move-column nil))
9247 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9248 (t (forward-word (prefix-numeric-value arg)))))
9249
9250 (defun org-metaup (&optional arg)
9251 "Call `org-move-subtree-up' or `org-table-move-row' up."
9252 (interactive "P")
9253 (cond
9254 ((org-at-table-p) (org-table-move-row 'up))
9255 ((org-on-heading-p) (org-move-subtree-up arg))
9256 (t (org-shiftcursor-error))))
9257
9258 (defun org-metadown (&optional arg)
9259 "Call `org-move-subtree-down' or `org-table-move-row' down."
9260 (interactive "P")
9261 (cond
9262 ((org-at-table-p) (org-table-move-row nil))
9263 ((org-on-heading-p) (org-move-subtree-down arg))
9264 (t (org-shiftcursor-error))))
9265
9266 (defun org-shiftup (&optional arg)
9267 "Call `org-timestamp-up' or `org-priority-up'."
9268 (interactive "P")
9269 (cond
9270 ((org-at-timestamp-p) (org-timestamp-up arg))
9271 (t (org-priority-up))))
9272
9273 (defun org-shiftdown (&optional arg)
9274 "Call `org-timestamp-down' or `org-priority-down'."
9275 (interactive "P")
9276 (cond
9277 ((org-at-timestamp-p) (org-timestamp-down arg))
9278 (t (org-priority-down))))
9279
9280 (defun org-copy-special ()
9281 "Call either `org-table-copy' or `org-copy-subtree'."
9282 (interactive)
9283 (call-interactively
9284 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9285
9286 (defun org-cut-special ()
9287 "Call either `org-table-copy' or `org-cut-subtree'."
9288 (interactive)
9289 (call-interactively
9290 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9291
9292 (defun org-paste-special (arg)
9293 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9294 (interactive "P")
9295 (if (org-at-table-p)
9296 (org-table-paste-rectangle)
9297 (org-paste-subtree arg)))
9298
9299 (defun org-ctrl-c-ctrl-c (&optional arg)
9300 "Call realign table, or recognize a table.el table, or update keywords.
9301 When the cursor is inside a table created by the table.el package,
9302 activate that table. Otherwise, if the cursor is at a normal table
9303 created with org.el, re-align that table. This command works even if
9304 the automatic table editor has been turned off.
9305 If the cursor is in one of the special #+KEYWORD lines, this triggers
9306 scanning the buffer for these lines and updating the information."
9307 (interactive "P")
9308 (let ((org-enable-table-editor t))
9309 (cond
9310 ((org-at-table.el-p)
9311 (require 'table)
9312 (beginning-of-line 1)
9313 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9314 (table-recognize-table))
9315 ((org-at-table-p)
9316 (org-table-maybe-eval-formula)
9317 (if arg
9318 (org-table-recalculate t)
9319 (org-table-maybe-recalculate-line))
9320 (org-table-align))
9321 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9322 (cond
9323 ((equal (match-string 1) "TBLFM")
9324 ;; Recalculate the table before this line
9325 (save-excursion
9326 (beginning-of-line 1)
9327 (skip-chars-backward " \r\n\t")
9328 (if (org-at-table-p) (org-table-recalculate t))))
9329 (t
9330 (let ((org-inhibit-startup t)) (org-mode)))))
9331 ((org-region-active-p)
9332 (org-table-convert-region (region-beginning) (region-end) arg))
9333 ((and (region-beginning) (region-end))
9334 (if (y-or-n-p "Convert inactive region to table? ")
9335 (org-table-convert-region (region-beginning) (region-end) arg)
9336 (error "Abort")))
9337 (t (error "No table at point, and no region to make one")))))
9338
9339 (defun org-return ()
9340 "Call `org-table-next-row' or `newline'."
9341 (interactive)
9342 (cond
9343 ((org-at-table-p)
9344 (org-table-justify-field-maybe)
9345 (org-table-next-row))
9346 (t (newline))))
9347
9348 (defun org-meta-return (&optional arg)
9349 "Call `org-insert-heading' or `org-table-wrap-region'."
9350 (interactive "P")
9351 (cond
9352 ((org-at-table-p)
9353 (org-table-wrap-region arg))
9354 (t (org-insert-heading))))
9355
9356 ;;; Menu entries
9357
9358 ;; Define the Org-mode menus
9359 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9360 '("Tbl"
9361 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9362 ["Next Field" org-cycle (org-at-table-p)]
9363 ["Previous Field" org-shifttab (org-at-table-p)]
9364 ["Next Row" org-return (org-at-table-p)]
9365 "--"
9366 ["Blank Field" org-table-blank-field (org-at-table-p)]
9367 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9368 "--"
9369 ("Column"
9370 ["Move Column Left" org-metaleft (org-at-table-p)]
9371 ["Move Column Right" org-metaright (org-at-table-p)]
9372 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9373 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9374 ("Row"
9375 ["Move Row Up" org-metaup (org-at-table-p)]
9376 ["Move Row Down" org-metadown (org-at-table-p)]
9377 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9378 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9379 "--"
9380 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9381 ("Rectangle"
9382 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9383 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9384 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9385 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9386 "--"
9387 ("Calculate"
9388 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
9389 ["Eval Formula Down" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9390 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9391 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9392 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9393 ["Sum Column/Rectangle" org-table-sum
9394 (or (org-at-table-p) (org-region-active-p))]
9395 ["Which Column?" org-table-current-column (org-at-table-p)])
9396 ["Debug Formulas"
9397 (setq org-table-formula-debug (not org-table-formula-debug))
9398 :style toggle :selected org-table-formula-debug]
9399 "--"
9400 ["Invisible Vlines" org-table-toggle-vline-visibility
9401 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9402 "--"
9403 ["Create" org-table-create (and (not (org-at-table-p))
9404 org-enable-table-editor)]
9405 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9406 ["Import from File" org-table-import (not (org-at-table-p))]
9407 ["Export to File" org-table-export (org-at-table-p)]
9408 "--"
9409 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9410
9411 (easy-menu-define org-org-menu org-mode-map "Org menu"
9412 '("Org"
9413 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9414 ["Sparse Tree" org-occur t]
9415 ["Show All" show-all t]
9416 "--"
9417 ["New Heading" org-insert-heading t]
9418 ("Navigate Headings"
9419 ["Up" outline-up-heading t]
9420 ["Next" outline-next-visible-heading t]
9421 ["Previous" outline-previous-visible-heading t]
9422 ["Next Same Level" outline-forward-same-level t]
9423 ["Previous Same Level" outline-backward-same-level t]
9424 "--"
9425 ["Jump" org-goto t])
9426 ("Edit Structure"
9427 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9428 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9429 "--"
9430 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9431 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9432 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9433 "--"
9434 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9435 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9436 ["Demote Heading" org-metaright (not (org-at-table-p))]
9437 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9438 "--"
9439 ["Archive Subtree" org-archive-subtree t])
9440 "--"
9441 ("TODO Lists"
9442 ["TODO/DONE/-" org-todo t]
9443 ["Show TODO Tree" org-show-todo-tree t]
9444 "--"
9445 ["Set Priority" org-priority t]
9446 ["Priority Up" org-shiftup t]
9447 ["Priority Down" org-shiftdown t])
9448 ("Dates and Scheduling"
9449 ["Timestamp" org-time-stamp t]
9450 ("Change Date"
9451 ["1 Day Later" org-timestamp-up-day t]
9452 ["1 Day Earlier" org-timestamp-down-day t]
9453 ["1 ... Later" org-shiftup t]
9454 ["1 ... Earlier" org-shiftdown t])
9455 ["Compute Time Range" org-evaluate-time-range t]
9456 ["Schedule Item" org-schedule t]
9457 ["Deadline" org-deadline t]
9458 "--"
9459 ["Goto Calendar" org-goto-calendar t]
9460 ["Date from Calendar" org-date-from-calendar t])
9461 "--"
9462 ("Timeline/Agenda"
9463 ["Show TODO Tree this File" org-show-todo-tree t]
9464 ["Check Deadlines this File" org-check-deadlines t]
9465 ["Timeline Current File" org-timeline t]
9466 "--"
9467 ["Agenda" org-agenda t])
9468 ("File List for Agenda")
9469 "--"
9470 ("Hyperlinks"
9471 ["Store Link (Global)" org-store-link t]
9472 ["Insert Link" org-insert-link t]
9473 ["Follow Link" org-open-at-point t])
9474 "--"
9475 ("Export"
9476 ["ASCII" org-export-as-ascii t]
9477 ["Extract Visible Text" org-export-copy-visible t]
9478 ["HTML" org-export-as-html t]
9479 ["HTML and Open" org-export-as-html-and-open t]
9480 ; ["OPML" org-export-as-opml nil]
9481 "--"
9482 ["Option Template" org-insert-export-options-template t]
9483 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9484 "--"
9485 ("Documentation"
9486 ["Show Version" org-version t]
9487 ["Info Documentation" org-info t])
9488 ("Customize"
9489 ["Browse Org Group" org-customize t]
9490 "--"
9491 ["Build Full Customize Menu" org-create-customize-menu
9492 (fboundp 'customize-menu-create)])
9493 ))
9494
9495 (defun org-info (&optional node)
9496 "Read documentation for Org-mode in the info system.
9497 With optional NODE, go directly to that node."
9498 (interactive)
9499 (require 'info)
9500 (Info-goto-node (format "(org)%s" (or node ""))))
9501
9502 (defun org-install-agenda-files-menu ()
9503 (easy-menu-change
9504 '("Org") "File List for Agenda"
9505 (append
9506 (list
9507 ["Edit File List" (customize-variable 'org-agenda-files) t]
9508 ["Add Current File to List" org-add-file t]
9509 ["Remove Current File from List" org-remove-file t]
9510 "--")
9511 (mapcar 'org-file-menu-entry org-agenda-files))))
9512
9513 ;;; Documentation
9514
9515 (defun org-customize ()
9516 "Call the customize function with org as argument."
9517 (interactive)
9518 (customize-browse 'org))
9519
9520 (defun org-create-customize-menu ()
9521 "Create a full customization menu for Org-mode, insert it into the menu."
9522 (interactive)
9523 (if (fboundp 'customize-menu-create)
9524 (progn
9525 (easy-menu-change
9526 '("Org") "Customize"
9527 `(["Browse Org group" org-customize t]
9528 "--"
9529 ,(customize-menu-create 'org)
9530 ["Set" Custom-set t]
9531 ["Save" Custom-save t]
9532 ["Reset to Current" Custom-reset-current t]
9533 ["Reset to Saved" Custom-reset-saved t]
9534 ["Reset to Standard Settings" Custom-reset-standard t]))
9535 (message "\"Org\"-menu now contains full customization menu"))
9536 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9537
9538 ;;; Miscellaneous stuff
9539
9540 (defun org-move-line-down (arg)
9541 "Move the current line down. With prefix argument, move it past ARG lines."
9542 (interactive "p")
9543 (let ((col (current-column))
9544 beg end pos)
9545 (beginning-of-line 1) (setq beg (point))
9546 (beginning-of-line 2) (setq end (point))
9547 (beginning-of-line (+ 1 arg))
9548 (setq pos (move-marker (make-marker) (point)))
9549 (insert (delete-and-extract-region beg end))
9550 (goto-char pos)
9551 (move-to-column col)))
9552
9553 (defun org-move-line-up (arg)
9554 "Move the current line up. With prefix argument, move it past ARG lines."
9555 (interactive "p")
9556 (let ((col (current-column))
9557 beg end pos)
9558 (beginning-of-line 1) (setq beg (point))
9559 (beginning-of-line 2) (setq end (point))
9560 (beginning-of-line (- arg))
9561 (setq pos (move-marker (make-marker) (point)))
9562 (insert (delete-and-extract-region beg end))
9563 (goto-char pos)
9564 (move-to-column col)))
9565
9566 ;; Functions needed for Emacs/XEmacs region compatibility
9567
9568 (defun org-region-active-p ()
9569 "Is `transient-mark-mode' on and the region active?
9570 Works on both Emacs and XEmacs."
9571 (if org-ignore-region
9572 nil
9573 (if org-xemacs-p
9574 (and zmacs-regions (region-active-p))
9575 (and transient-mark-mode mark-active))))
9576
9577 (defun org-add-to-invisibility-spec (arg)
9578 "Add elements to `buffer-invisibility-spec'.
9579 See documentation for `buffer-invisibility-spec' for the kind of elements
9580 that can be added."
9581 (cond
9582 ((fboundp 'add-to-invisibility-spec)
9583 (add-to-invisibility-spec arg))
9584 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9585 (setq buffer-invisibility-spec (list arg)))
9586 (t
9587 (setq buffer-invisibility-spec
9588 (cons arg buffer-invisibility-spec)))))
9589
9590 (defun org-remove-from-invisibility-spec (arg)
9591 "Remove elements from `buffer-invisibility-spec'."
9592 (if (fboundp 'remove-from-invisibility-spec)
9593 (remove-from-invisibility-spec arg)
9594 (if (consp buffer-invisibility-spec)
9595 (setq buffer-invisibility-spec
9596 (delete arg buffer-invisibility-spec)))))
9597
9598 (defun org-in-invisibility-spec-p (arg)
9599 "Is ARG a member of `buffer-invisibility-spec'?."
9600 (if (consp buffer-invisibility-spec)
9601 (member arg buffer-invisibility-spec)
9602 nil))
9603
9604 (defun org-image-file-name-regexp ()
9605 "Return regexp matching the file names of images."
9606 (if (fboundp 'image-file-name-regexp)
9607 (image-file-name-regexp)
9608 (let ((image-file-name-extensions
9609 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9610 "xbm" "xpm" "pbm" "pgm" "ppm")))
9611 (concat "\\."
9612 (regexp-opt (nconc (mapcar 'upcase
9613 image-file-name-extensions)
9614 image-file-name-extensions)
9615 t)
9616 "\\'"))))
9617
9618 ;; Functions needed for compatibility with old outline.el
9619
9620 ;; The following functions capture almost the entire compatibility code
9621 ;; between the different versions of outline-mode. The only other place
9622 ;; where this is important are the font-lock-keywords. Search for
9623 ;; `org-noutline-p' to find it.
9624
9625 ;; C-a should go to the beginning of a *visible* line, also in the
9626 ;; new outline.el. I guess this should be patched into Emacs?
9627 (defun org-beginning-of-line ()
9628 "Go to the beginning of the current line. If that is invisible, continue
9629 to a visible line beginning. This makes the function of C-a more intuitive."
9630 (interactive)
9631 (beginning-of-line 1)
9632 (if (bobp)
9633 nil
9634 (backward-char 1)
9635 (if (org-invisible-p)
9636 (while (and (not (bobp)) (org-invisible-p))
9637 (backward-char 1)
9638 (beginning-of-line 1))
9639 (forward-char 1))))
9640 (when org-noutline-p
9641 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9642
9643 (defun org-invisible-p ()
9644 "Check if point is at a character currently not visible."
9645 (if org-noutline-p
9646 ;; Early versions of noutline don't have `outline-invisible-p'.
9647 (if (fboundp 'outline-invisible-p)
9648 (outline-invisible-p)
9649 (get-char-property (point) 'invisible))
9650 (save-excursion
9651 (skip-chars-backward "^\r\n")
9652 (equal (char-before) ?\r))))
9653
9654 (defun org-back-to-heading (&optional invisible-ok)
9655 "Move to previous heading line, or beg of this line if it's a heading.
9656 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9657 (if org-noutline-p
9658 (outline-back-to-heading invisible-ok)
9659 (if (looking-at outline-regexp)
9660 t
9661 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9662 outline-regexp)
9663 nil t)
9664 (if invisible-ok
9665 (progn (goto-char (match-end 1))
9666 (looking-at outline-regexp)))
9667 (error "Before first heading")))))
9668
9669 (defun org-on-heading-p (&optional invisible-ok)
9670 "Return t if point is on a (visible) heading line.
9671 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9672 (if org-noutline-p
9673 (outline-on-heading-p 'invisible-ok)
9674 (save-excursion
9675 (skip-chars-backward "^\n\r")
9676 (and (looking-at outline-regexp)
9677 (or invisible-ok
9678 (bobp)
9679 (equal (char-before) ?\n))))))
9680
9681 (defun org-up-heading-all (arg)
9682 "Move to the heading line of which the present line is a subheading.
9683 This function considers both visible and invisible heading lines.
9684 With argument, move up ARG levels."
9685 (if org-noutline-p
9686 (if (fboundp 'outline-up-heading-all)
9687 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9688 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9689 (org-back-to-heading t)
9690 (looking-at outline-regexp)
9691 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9692 (error "Cannot move up %d levels" arg)
9693 (re-search-backward
9694 (concat "[\n\r]" (regexp-quote
9695 (make-string (- (match-end 0) (match-beginning 0) arg)
9696 ?*))
9697 "[^*]"))
9698 (forward-char 1))))
9699
9700 (defun org-show-hidden-entry ()
9701 "Show an entry where even the heading is hidden."
9702 (save-excursion
9703 (if (not org-noutline-p)
9704 (progn
9705 (org-back-to-heading t)
9706 (org-flag-heading nil)))
9707 (org-show-entry)))
9708
9709 (defun org-check-occur-regexp (regexp)
9710 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9711 Of course, only for the old outline mode."
9712 (if org-noutline-p
9713 regexp
9714 (if (string-match "^\\^" regexp)
9715 (concat "[\n\r]" (substring regexp 1))
9716 regexp)))
9717
9718 (defun org-flag-heading (flag &optional entry)
9719 "Flag the current heading. FLAG non-nil means make invisible.
9720 When ENTRY is non-nil, show the entire entry."
9721 (save-excursion
9722 (org-back-to-heading t)
9723 (if (not org-noutline-p)
9724 ;; Make the current headline visible
9725 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9726 ;; Check if we should show the entire entry
9727 (if entry
9728 (progn
9729 (org-show-entry)
9730 (save-excursion ;; FIXME: Is this the fix for points in the -|
9731 ;; middle of text? |
9732 (and (outline-next-heading) ;; |
9733 (org-flag-heading nil)))) ; show the next heading _|
9734 (outline-flag-region (max 1 (1- (point)))
9735 (save-excursion (outline-end-of-heading) (point))
9736 (if org-noutline-p
9737 flag
9738 (if flag ?\r ?\n))))))
9739
9740 (defun org-show-subtree ()
9741 "Show everything after this heading at deeper levels."
9742 (outline-flag-region
9743 (point)
9744 (save-excursion
9745 (outline-end-of-subtree) (outline-next-heading) (point))
9746 (if org-noutline-p nil ?\n)))
9747
9748 (defun org-show-entry ()
9749 "Show the body directly following this heading.
9750 Show the heading too, if it is currently invisible."
9751 (interactive)
9752 (save-excursion
9753 (org-back-to-heading t)
9754 (outline-flag-region
9755 (1- (point))
9756 (save-excursion
9757 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9758 (or (match-beginning 1) (point-max)))
9759 (if org-noutline-p nil ?\n))))
9760
9761
9762 (defun org-make-options-regexp (kwds)
9763 "Make a regular expression for keyword lines."
9764 (concat
9765 (if org-noutline-p "^" "[\n\r]")
9766 "#?[ \t]*\\+\\("
9767 (mapconcat 'regexp-quote kwds "\\|")
9768 "\\):[ \t]*"
9769 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
9770
9771 ;; Advise the bookmark-jump function to make jump position visible
9772 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
9773 (eval-after-load "bookmark"
9774 '(defadvice bookmark-jump (after org-make-visible activate)
9775 "Make the position visible."
9776 (and (eq major-mode 'org-mode)
9777 (org-invisible-p)
9778 (org-show-hierarchy-above))))
9779
9780 ;;; Finish up
9781
9782 (provide 'org)
9783
9784 (run-hooks 'org-load-hook)
9785
9786 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
9787 ;;; org.el ends here