]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-read-date, org-goto-calendar)
[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.19
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.19
84 ;; - Bug fixes
85 ;;
86 ;; Version 3.18
87 ;; - Export of calendar information in the standard iCalendar format.
88 ;; - Some bug fixes.
89 ;;
90 ;; Version 3.17
91 ;; - HTML export specifies character set depending on coding-system.
92 ;;
93 ;; Version 3.16
94 ;; - In tables, directly after the field motion commands like TAB and RET,
95 ;; typing a character will blank the field. Can be turned off with
96 ;; variable `org-table-auto-blank-field'.
97 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
98 ;; and are not linked to the calendar.
99 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
100 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
101 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
102 ;; standard meaning of C-h after a prefix key (show prefix bindings).
103 ;;
104 ;; Version 3.15
105 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
106 ;; of unmodified entry text. `C-c :' toggles this keyword.
107 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
108 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
109 ;; color, to reduce the amount of aggressive color in the buffer.
110 ;;
111 ;; Version 3.14
112 ;; - Formulas for individual fields in table.
113 ;; - Automatic recalculation in calculating tables.
114 ;; - Named fields and columns in tables.
115 ;; - Fixed bug with calling `org-archive' several times in a row.
116 ;;
117 ;; Version 3.13
118 ;; - Efficiency improvements: Fewer table re-alignments needed.
119 ;; - New special lines in tables, for defining names for individual cells.
120 ;;
121 ;; Version 3.12
122 ;; - Tables can store formulas (one per column) and compute fields.
123 ;; Not quite like a full spreadsheet, but very powerful.
124 ;; - table.el keybinding is now `C-c ~'.
125 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
126 ;; - Small changes to keys in agenda buffer. Affected keys:
127 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
128 ;; - Bug fixes.
129 ;;
130 ;; Version 3.11
131 ;; - Links inserted with C-c C-l are now by default enclosed in angle
132 ;; brackets. See the new variable `org-link-format'.
133 ;; - ">" terminates a link, this is a way to have several links in a line.
134 ;; Both "<" and ">" are no longer allowed as characters in a link.
135 ;; - Archiving of finished tasks.
136 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
137 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
138 ;; - Compatibility problems with viper-mode fixed.
139 ;; - Improved html export of tables.
140 ;; - Various clean-up changes.
141 ;;
142 ;; Version 3.10
143 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
144 ;;
145 ;; Version 3.09
146 ;; - Time-of-day specifications in agenda are extracted and placed
147 ;; into the prefix. Timed entries can be placed into a time grid for
148 ;; day.
149 ;;
150 ;; Version 3.08
151 ;; - "|" no longer allowed as part of a link, to allow links in tables.
152 ;; - The prefix of items in the agenda buffer can be configured.
153 ;; - Cleanup.
154 ;;
155 ;; Version 3.07
156 ;; - Some folding incinsistencies removed.
157 ;; - BBDB links to company-only entries.
158 ;; - Bug fixes and global cleanup.
159 ;;
160 ;; Version 3.06
161 ;; - M-S-RET inserts a new TODO heading.
162 ;; - New startup option `content'.
163 ;; - Better visual response when TODO items in agenda change status.
164 ;; - Window positioning after visibility state changes optimized and made
165 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
166 ;;
167 ;; Version 3.05
168 ;; - Agenda entries from the diary are linked to the diary file, so
169 ;; adding and editing diary entries can be done directly from the agenda.
170 ;; - Many calendar/diary commands available directly from agenda.
171 ;; - Field copying in tables with S-RET does increment.
172 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
173 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
174 ;;
175 ;; Version 3.04
176 ;; - Table editor optimized to need fewer realignments, and to keep
177 ;; table shape when typing in fields.
178 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
179 ;; into arbitrary major modes.
180 ;; - Fixed bug with realignment in XEmacs.
181 ;; - Startup options can be set with special #+STARTUP line.
182 ;; - Heading following a match in org-occur can be suppressed.
183 ;;
184 ;; Version 3.03
185 ;; - Copyright transfer to the FSF.
186 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
187 ;; - Timeline now always contains today, and `.' jumps to it.
188 ;; - Table editor:
189 ;; - cut and paste of rectangular regions in tables
190 ;; - command to convert org-mode table to table.el table and back
191 ;; - command to treat several cells like a paragraph and fill it
192 ;; - command to convert a buffer region to a table
193 ;; - import/export tables as tab-separated files (exchange with Excel)
194 ;; - Agenda:
195 ;; - Sorting mechanism for agenda items rewritten from scratch.
196 ;; - Sorting fully configurable.
197 ;; - Entries specifying a time are sorted together.
198 ;; - Completion also covers option keywords after `#-'.
199 ;; - Bug fixes.
200 ;;
201 ;; Version 3.01
202 ;; - New reference card, thanks to Philip Rooke for creating it.
203 ;; - Single file agenda renamed to "Timeline". It no longer shows
204 ;; warnings about upcoming deadlines/overdue scheduled items.
205 ;; That functionality is now limited to the (multifile) agenda.
206 ;; - When reading a date, the calendar can be manipulated with keys.
207 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
208 ;; - Minor bug fixes and documentation improvements.
209
210 ;;; Code:
211
212 (eval-when-compile (require 'cl) (require 'calendar))
213 (require 'outline)
214 (require 'time-date)
215 (require 'easymenu)
216
217 (defvar calc-embedded-close-formula)
218 (defvar calc-embedded-open-formula)
219 (defvar font-lock-unfontify-region-function)
220
221 ;;; Customization variables
222
223 (defvar org-version "3.19"
224 "The version number of the file org.el.")
225 (defun org-version ()
226 (interactive)
227 (message "Org-mode version %s" org-version))
228
229 ;; The following two constants are for compatibility with different Emacs
230 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
231 ;; The compatibility code in org.el is based on these two constants.
232 (defconst org-xemacs-p (featurep 'xemacs)
233 "Are we running xemacs?")
234 (defconst org-noutline-p (featurep 'noutline)
235 "Are we using the new outline mode?")
236
237 (defgroup org nil
238 "Outline-based notes management and organizer "
239 :tag "Org"
240 :group 'outlines
241 :group 'hypermedia
242 :group 'calendar)
243
244 (defgroup org-startup nil
245 "Options concerning startup of Org-mode."
246 :tag "Org Startup"
247 :group 'org)
248
249 (defcustom org-CUA-compatible nil
250 "Non-nil means use alternative key bindings for S-<cursor movement>.
251 Org-mode used S-<cursor movement> for changing timestamps and priorities.
252 S-<cursor movement> is also used for example by `CUA-mode' to select text.
253 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
254 alternative bindings. Setting this variable to t will replace the following
255 keys both in Org-mode and in the Org-agenda buffer.
256
257 S-RET -> C-S-RET
258 S-up -> M-p
259 S-down -> M-n
260 S-left -> M--
261 S-right -> M-+
262
263 If you do not like the alternative keys, take a look at the variable
264 `org-disputed-keys'.
265
266 This option is only relevant at load-time of Org-mode. Changing it requires
267 a restart of Emacs to become effective."
268 :group 'org-startup
269 :type 'boolean)
270
271 (defvar org-disputed-keys
272 '((S-up [(shift up)] [(meta ?p)])
273 (S-down [(shift down)] [(meta ?n)])
274 (S-left [(shift left)] [(meta ?-)])
275 (S-right [(shift right)] [(meta ?+)])
276 (S-return [(shift return)] [(control shift return)]))
277 "Keys for which Org-mode and other modes compete.
278 This is an alist, cars are symbols for lookup, 1st element is the default key,
279 second element will be used when `org-CUA-compatible' is t.")
280
281 (defun org-key (key)
282 "Select a key according to `org-CUA-compatible'."
283 (nth (if org-CUA-compatible 2 1)
284 (or (assq key org-disputed-keys)
285 (error "Invalid Key %s in `org-key'" key))))
286
287 (defcustom org-startup-folded t
288 "Non-nil means, entering Org-mode will switch to OVERVIEW.
289 This can also be configured on a per-file basis by adding one of
290 the following lines anywhere in the buffer:
291
292 #+STARTUP: fold
293 #+STARTUP: nofold
294 #+STARTUP: content"
295 :group 'org-startup
296 :type '(choice
297 (const :tag "nofold: show all" nil)
298 (const :tag "fold: overview" t)
299 (const :tag "content: all headlines" content)))
300
301 (defcustom org-startup-truncated t
302 "Non-nil means, entering Org-mode will set `truncate-lines'.
303 This is useful since some lines containing links can be very long and
304 uninteresting. Also tables look terrible when wrapped."
305 :group 'org-startup
306 :type 'boolean)
307
308 (defcustom org-startup-with-deadline-check nil
309 "Non-nil means, entering Org-mode will run the deadline check.
310 This means, if you start editing an org file, you will get an
311 immediate reminder of any due deadlines.
312 This can also be configured on a per-file basis by adding one of
313 the following lines anywhere in the buffer:
314
315 #+STARTUP: dlcheck
316 #+STARTUP: nodlcheck"
317 :group 'org-startup
318 :type 'boolean)
319
320 (defcustom org-insert-mode-line-in-empty-file nil
321 "Non-nil means insert the first line setting Org-mode in empty files.
322 When the function `org-mode' is called interactively in an empty file, this
323 normally means that the file name does not automatically trigger Org-mode.
324 To ensure that the file will always be in Org-mode in the future, a
325 line enforcing Org-mode will be inserted into the buffer, if this option
326 has been set."
327 :group 'org-startup
328 :type 'boolean)
329
330 (defgroup org-keywords nil
331 "Options concerning TODO items in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
334
335 (defcustom org-todo-keywords '("TODO" "DONE")
336 "List of TODO entry keywords.
337 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
338 considered to mean that the entry is \"done\". All the other mean that
339 action is required, and will make the entry show up in todo lists, diaries
340 etc.
341 The command \\[org-todo] cycles an entry through these states, and an
342 additional state where no keyword is present. For details about this
343 cycling, see also the variable `org-todo-interpretation'
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type '(repeat (string :tag "Keyword")))
347
348 (defcustom org-todo-interpretation 'sequence
349 "Controls how TODO keywords are interpreted.
350 \\<org-mode-map>Possible values are `sequence' and `type'.
351 This variable is only relevant if `org-todo-keywords' contains more than two
352 states. There are two ways how these keywords can be used:
353
354 - As a sequence in the process of working on a TODO item, for example
355 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
356 org-todo-interpretation 'sequence)
357
358 - As different types of TODO items, for example
359 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
360 org-todo-interpretation 'type)
361
362 When the states are interpreted as a sequence, \\[org-todo] always cycles
363 to the next state, in order to walk through all different states. So with
364 \\[org-todo], you turn an empty entry into the state TODO. When you started
365 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
366 later to VERIFY and finally to DONE.
367
368 When the states are interpreted as types, \\[org-todo] still cycles through
369 when it is called several times in direct succession, in order to initially
370 select the type. However, if not called immediately after a previous
371 \\[org-todo], it switches from each type directly to DONE. So with the
372 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
373 RELAXED. If you later return to this entry and press \\[org-todo] again,
374 RELAXED will not be changed REMIND, but directly to DONE.
375
376 You can create a large number of types. To initially select a
377 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
378 type with completion. Of course, you can also type the keyword
379 directly into the buffer. M-TAB completes TODO keywords at the
380 beginning of a headline."
381 :group 'org-keywords
382 :type '(choice (const sequence)
383 (const type)))
384
385 (defcustom org-default-priority ?B
386 "The default priority of TODO items.
387 This is the priority an item get if no explicit priority is given."
388 :group 'org-keywords
389 :type 'character)
390
391 (defcustom org-lowest-priority ?C
392 "The lowest priority of TODO items. A character like ?A, ?B etc."
393 :group 'org-keywords
394 :type 'character)
395
396 (defcustom org-deadline-string "DEADLINE:"
397 "String to mark deadline entries.
398 A deadline is this string, followed by a time stamp. Should be a word,
399 terminated by a colon. You can insert a schedule keyword and
400 a timestamp with \\[org-deadline].
401 Changes become only effective after restarting Emacs."
402 :group 'org-keywords
403 :type 'string)
404
405 (defcustom org-scheduled-string "SCHEDULED:"
406 "String to mark scheduled TODO entries.
407 A schedule is this string, followed by a time stamp. Should be a word,
408 terminated by a colon. You can insert a schedule keyword and
409 a timestamp with \\[org-schedule].
410 Changes become only effective after restarting Emacs."
411 :group 'org-keywords
412 :type 'string)
413
414 (defcustom org-comment-string "COMMENT"
415 "Entries starting with this keyword will never be exported.
416 An entry can be toggled between COMMENT and normal with
417 \\[org-toggle-comment].
418 Changes become only effective after restarting Emacs."
419 :group 'org-keywords
420 :type 'string)
421
422 (defcustom org-quote-string "QUOTE"
423 "Entries starting with this keyword will be exported in fixed-width font.
424 Quoting applies only to the text in the entry following the headline, and does
425 not extend beyond the next headline, even if that is lower level.
426 An entry can be toggled between QUOTE and normal with
427 \\[org-toggle-fixed-width-section]"
428 :group 'org-keywords
429 :type 'string)
430
431 (defcustom org-after-todo-state-change-hook nil
432 "Hook which is run after the state of a TODO item was changed.
433 The new state (a string with a todo keyword, or nil) is available in the
434 Lisp variable `state'."
435 :group 'org-keywords
436 :type 'hook)
437
438 ;; Variables for pre-computed regular expressions, all buffer local
439 (defvar org-todo-kwd-priority-p nil
440 "Do TODO items have priorities?")
441 (make-variable-buffer-local 'org-todo-kwd-priority-p)
442 (defvar org-todo-kwd-max-priority nil
443 "Maximum priority of TODO items.")
444 (make-variable-buffer-local 'org-todo-kwd-max-priority)
445 (defvar org-ds-keyword-length 12
446 "Maximum length of the Deadline and SCHEDULED keywords.")
447 (make-variable-buffer-local 'org-ds-keyword-length)
448 (defvar org-done-string nil
449 "The last string in `org-todo-keywords', indicating an item is DONE.")
450 (make-variable-buffer-local 'org-done-string)
451 (defvar org-todo-regexp nil
452 "Matches any of the TODO state keywords.")
453 (make-variable-buffer-local 'org-todo-regexp)
454 (defvar org-not-done-regexp nil
455 "Matches any of the TODO state keywords except the last one.")
456 (make-variable-buffer-local 'org-not-done-regexp)
457 (defvar org-todo-line-regexp nil
458 "Matches a headline and puts TODO state into group 2 if present.")
459 (make-variable-buffer-local 'org-todo-line-regexp)
460 (defvar org-nl-done-regexp nil
461 "Matches newline followed by a headline with the DONE keyword.")
462 (make-variable-buffer-local 'org-nl-done-regexp)
463 (defvar org-looking-at-done-regexp nil
464 "Matches the DONE keyword a point.")
465 (make-variable-buffer-local 'org-looking-at-done-regexp)
466 (defvar org-deadline-regexp nil
467 "Matches the DEADLINE keyword.")
468 (make-variable-buffer-local 'org-deadline-regexp)
469 (defvar org-deadline-time-regexp nil
470 "Matches the DEADLINE keyword together with a time stamp.")
471 (make-variable-buffer-local 'org-deadline-time-regexp)
472 (defvar org-deadline-line-regexp nil
473 "Matches the DEADLINE keyword and the rest of the line.")
474 (make-variable-buffer-local 'org-deadline-line-regexp)
475 (defvar org-scheduled-regexp nil
476 "Matches the SCHEDULED keyword.")
477 (make-variable-buffer-local 'org-scheduled-regexp)
478 (defvar org-scheduled-time-regexp nil
479 "Matches the SCHEDULED keyword together with a time stamp.")
480 (make-variable-buffer-local 'org-scheduled-time-regexp)
481
482 (defvar org-category nil
483 "Variable used by org files to set a category for agenda display.
484 Such files should use a file variable to set it, for example
485
486 -*- mode: org; org-category: \"ELisp\"
487
488 or contain a special line
489
490 #+CATEGORY: ELisp
491
492 If the file does not specify a category, then file's base name
493 is used instead.")
494
495 (defgroup org-time nil
496 "Options concerning time stamps and deadlines in Org-mode."
497 :tag "Org Time"
498 :group 'org)
499
500 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
501 "Formats for `format-time-string' which are used for time stamps.
502 It is not recommended to change this constant.")
503
504
505 (defcustom org-deadline-warning-days 30
506 "No. of days before expiration during which a deadline becomes active.
507 This variable governs the display in the org file."
508 :group 'org-time
509 :type 'number)
510
511 (defcustom org-popup-calendar-for-date-prompt t
512 "Non-nil means, pop up a calendar when prompting for a date.
513 In the calendar, the date can be selected with mouse-1. However, the
514 minibuffer will also be active, and you can simply enter the date as well.
515 When nil, only the minibuffer will be available."
516 :group 'org-time
517 :type 'number)
518
519 (defcustom org-calendar-follow-timestamp-change t
520 "Non-nil means, make the calendar window follow timestamp changes.
521 When a timestamp is modified and the calendar window is visible, it will be
522 moved to the new date."
523 :group 'org-time
524 :type 'boolean)
525
526 (defgroup org-agenda nil
527 "Options concerning agenda display Org-mode."
528 :tag "Org Agenda"
529 :group 'org)
530
531 (defcustom org-agenda-files nil
532 "A list of org files for agenda/diary display.
533 Entries are added to this list with \\[org-add-file] and removed with
534 \\[org-remove-file]. You can also use customize to edit the list."
535 :group 'org-agenda
536 :type '(repeat file))
537
538 (defcustom org-select-timeline-window t
539 "Non-nil means, after creating a timeline, move cursor into Timeline window.
540 When nil, cursor will remain in the current window."
541 :group 'org-agenda
542 :type 'boolean)
543
544 (defcustom org-select-agenda-window t
545 "Non-nil means, after creating an agenda, move cursor into Agenda window.
546 When nil, cursor will remain in the current window."
547 :group 'org-agenda
548 :type 'boolean)
549
550 (defcustom org-fit-agenda-window t
551 "Non-nil means, change window size of agenda to fit content."
552 :group 'org-agenda
553 :type 'boolean)
554
555 (defcustom org-agenda-show-all-dates t
556 "Non-nil means, `org-agenda' shows every day in the selected range.
557 When nil, only the days which actually have entries are shown."
558 :group 'org-agenda
559 :type 'boolean)
560
561 ;; FIXME: First day of month works only for current month because it would
562 ;; require a variable ndays treatment.
563 (defcustom org-agenda-start-on-weekday 1
564 "Non-nil means, start the overview always on the specified weekday.
565 0 Denotes Sunday, 1 denotes Monday etc.
566 When nil, always start on the current day."
567 :group 'org-agenda
568 :type '(choice (const :tag "Today" nil)
569 (const :tag "First day of month" t)
570 (number :tag "Weekday No.")))
571
572 (defcustom org-agenda-ndays 7
573 "Number of days to include in overview display."
574 :group 'org-agenda
575 :type 'number)
576
577 (defcustom org-agenda-include-all-todo t
578 "Non-nil means, the agenda will always contain all TODO entries.
579 When nil, date-less entries will only be shown if `org-agenda' is called
580 with a prefix argument.
581 When non-nil, the TODO entries will be listed at the top of the agenda, before
582 the entries for specific days."
583 :group 'org-agenda
584 :type 'boolean)
585
586 (defcustom org-agenda-include-diary nil
587 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
588 :group 'org-agenda
589 :type 'boolean)
590
591 (defcustom org-calendar-to-agenda-key [?c]
592 "The key to be installed in `calendar-mode-map' for switching to the agenda.
593 The command `org-calendar-goto-agenda' will be bound to this key. The
594 default is the character `c' because then`c' can be used to switch back and
595 force between agenda and calendar."
596 :group 'org-agenda
597 :type 'sexp)
598
599 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
600 "Sorting structure for the agenda items of a single day.
601 This is a list of symbols which will be used in sequence to determine
602 if an entry should be listed before another entry. The following
603 symbols are recognized.
604
605 time-up Put entries with time-of-day indications first, early first
606 time-down Put entries with time-of-day indications first, late first
607 category-keep Keep the default order of categories, corresponding to the
608 sequence in `org-agenda-files'.
609 category-up Sort alphabetically by category, A-Z.
610 category-down Sort alphabetically by category, Z-A.
611 priority-up Sort numerically by priority, high priority last.
612 priority-down Sort numerically by priority, high priority first.
613
614 The different possibilities will be tried in sequence, and testing stops
615 if one comparison returns a \"not-equal\". For example, the default
616 '(time-up category-keep priority-down)
617 means: Pull out all entries having a specified time of day and sort them,
618 in order to make a time schedule for the current day the first thing in the
619 agenda listing for the day. Of the entries without a time indication, keep
620 the grouped in categories, don't sort the categories, but keep them in
621 the sequence given in `org-agenda-files'. Within each category sort by
622 priority.
623
624 Leaving out `category-keep' would mean that items will be sorted across
625 categories by priority."
626 :group 'org-agenda
627 :type '(repeat
628 (choice
629 (const time-up)
630 (const time-down)
631 (const category-keep)
632 (const category-up)
633 (const category-down)
634 (const priority-up)
635 (const priority-down))))
636
637 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
638 "Format specification for the prefix of items in the agenda buffer.
639 This format works similar to a printf format, with the following meaning:
640
641 %c the category of the item, \"Diary\" for entries from the diary, or
642 as given by the CATEGORY keyword or derived from the file name.
643 %t the time-of-day specification if one applies to the entry, in the
644 format HH:MM
645 %s Scheduling/Deadline information, a short string
646
647 All specifiers work basically like the standard `%s' of printf, but may
648 contain two additional characters: A question mark just after the `%' and
649 a whitespace/punctuation character just before the final letter.
650
651 If the first character after `%' is a question mark, the entire field
652 will only be included if the corresponding value applies to the
653 current entry. This is useful for fields which should have fixed
654 width when present, but zero width when absent. For example,
655 \"%?-12t\" will result in a 12 character time field if a time of the
656 day is specified, but will completely disappear in entries which do
657 not contain a time.
658
659 If there is punctuation or whitespace character just before the final
660 format letter, this character will be appended to the field value if
661 the value is not empty. For example, the format \"%-12:c\" leads to
662 \"Diary: \" if the category is \"Diary\". If the category were be
663 empty, no additional colon would be interted.
664
665 The default value of this option is \" %-12:c%?-12t% s\", meaning:
666 - Indent the line with two space characters
667 - Give the category in a 12 chars wide field, padded with whitespace on
668 the right (because of `-'). Append a colon if there is a category
669 (because of `:').
670 - If there is a time-of-day, put it into a 12 chars wide field. If no
671 time, don't put in an empty field, just skip it (because of '?').
672 - Finally, put the scheduling information and append a whitespace.
673
674 As another example, if you don't want the time-of-day of entries in
675 the prefix, you could use:
676
677 (setq org-agenda-prefix-format \" %-11:c% s\")
678
679 See also the variable `org-agenda-remove-times-when-in-prefix'."
680 :type 'string
681 :group 'org-agenda)
682
683 (defcustom org-timeline-prefix-format " % s"
684 "Like `org-agenda-prefix-format', but for the timeline of a single file."
685 :type 'string
686 :group 'org-agenda)
687
688 (defvar org-prefix-format-compiled nil
689 "The compiled version of the most recently used prefix format.
690 Depending on which command was used last, this may be the compiled version
691 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
692
693 (defcustom org-agenda-use-time-grid t
694 "Non-nil means, show a time grid in the agenda schedule.
695 A time grid is a set of lines for specific times (like every two hours between
696 8:00 and 20:00. The items scheduled for a day at specific times are
697 sorted in between these lines.
698 For deails about when the grid will be shown, and what it will look like, see
699 the variable `org-agenda-time-grid'."
700 :group 'org-agenda
701 :type 'boolean)
702
703 (defcustom org-agenda-time-grid
704 '((daily today require-timed)
705 "----------------"
706 (800 1000 1200 1400 1600 1800 2000))
707
708 "The settings for time grid for agenda display.
709 This is a list of three items. The first item is again a list. It contains
710 symbols specifying conditions when the grid should be displayed:
711
712 daily if the agenda shows a single day
713 weekly if the agenda shows an entire week
714 today show grid on current date, independent of daily/weekly display
715 require-timed show grid only if at least on item has a time specification
716
717 The second item is a string which will be places behing the grid time.
718
719 The third item is a list of integers, indicating the times that should have
720 a grid line."
721 :group 'org-agenda
722 :type
723 '(list
724 (set :greedy t :tag "Grid Display Options"
725 (const :tag "Show grid in single day agenda display" daily)
726 (const :tag "Show grid in weekly agenda display" weekly)
727 (const :tag "Always show grid for today" today)
728 (const :tag "Show grid only if any timed entries are present"
729 require-timed)
730 (const :tag "Skip grid times already present in an entry"
731 remove-match))
732 (string :tag "Grid String")
733 (repeat :tag "Grid Times" (integer :tag "Time"))))
734
735 (defcustom org-agenda-remove-times-when-in-prefix t
736 "Non-nil means, remove duplicate time specifications in agenda items.
737 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
738 time-of-day specification in a headline or diary entry is extracted and
739 placed into the prefix. If this option is non-nil, the original specification
740 \(a timestamp or -range, or just a plain time(range) specification like
741 11:30-4pm) will be removed for agenda display. This makes the agenda less
742 cluttered.
743 The option can be t or nil. It may also be the symbol `beg', indicating
744 that the time should only be removed what it is located at the beginning of
745 the headline/diary entry."
746 :group 'org-agenda
747 :type '(choice
748 (const :tag "Always" t)
749 (const :tag "Never" nil)
750 (const :tag "When at beginning of entry" beg)))
751
752 (defcustom org-sort-agenda-notime-is-late t
753 "Non-nil means, items without time are considered late.
754 This is only relevant for sorting. When t, items which have no explicit
755 time like 15:30 will be considered as 24:01, i.e. later than any items which
756 do have a time. When nil, the default time is before 0:00. You can use this
757 option to decide if the schedule for today should come before or after timeless
758 agenda entries."
759 :group 'org-agenda
760 :type 'boolean)
761
762 (defgroup org-structure nil
763 "Options concerning structure editing in Org-mode."
764 :tag "Org Structure"
765 :group 'org)
766
767 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
768 "Hook that is run after `org-cycle' has changed the buffer visibility.
769 The function(s) in this hook must accept a single argument which indicates
770 the new state that was set by the most recent `org-cycle' command. The
771 argument is a symbol. After a global state change, it can have the values
772 `overview', `content', or `all'. After a local state change, it can have
773 the values `folded', `children', or `subtree'."
774 :group 'org-structure
775 :type 'hook)
776
777 (defcustom org-occur-hook '(org-first-headline-recenter)
778 "Hook that is run after `org-occur' has constructed a sparse tree.
779 This can be used to recenter the window to show as much of the structure
780 as possible."
781 :group 'org-structure
782 :type 'hook)
783
784 (defcustom org-level-color-stars-only nil
785 "Non-nil means fontify only the stars in each headline.
786 When nil, the entire headline is fontified.
787 After changin this, requires restart of Emacs to become effective."
788 :group 'org-structure
789 :type 'boolean)
790
791 (defcustom org-adapt-indentation t
792 "Non-nil means, adapt indentation when promoting and demoting.
793 When this is set and the *entire* text in an entry is indented, the
794 indentation is increased by one space in a demotion command, and
795 decreased by one in a promotion command. If any line in the entry
796 body starts at column 0, indentation is not changed at all."
797 :group 'org-structure
798 :type 'boolean)
799
800 (defcustom org-enable-fixed-width-editor t
801 "Non-nil means, lines starting with \":\" are treated as fixed-width.
802 This currently only means, they are never auto-wrapped.
803 When nil, such lines will be treated like ordinary lines.
804 See also the QUOTE keyword."
805 :group 'org-structure
806 :type 'boolean)
807
808 (defcustom org-cycle-emulate-tab t
809 "Where should `org-cycle' emulate TAB.
810 nil Never
811 white Only in completely white lines
812 t Everywhere except in headlines"
813 :group 'org-structure
814 :type '(choice (const :tag "Never" nil)
815 (const :tag "Only in completely white lines" white)
816 (const :tag "Everywhere except in headlines" t)
817 ))
818
819 (defcustom org-show-following-heading t
820 "Non-nil means, show heading following match in `org-occur'.
821 When doing an `org-occur' it is useful to show the headline which
822 follows the match, even if they do not match the regexp. This makes it
823 easier to edit directly inside the sparse tree. However, if you use
824 org-occur mainly as an overview, the following headlines are
825 unnecessary clutter."
826 :group 'org-structure
827 :type 'boolean)
828
829 (defcustom org-archive-location "%s_archive::"
830 "The location where subtrees should be archived.
831 This string consists of two parts, separated by a double-colon.
832
833 The first part is a file name - when omitted, archiving happens in the same
834 file. %s will be replaced by the current file name (without directory part).
835 Archiving to a different file is useful to keep archived entries from
836 contributing to the Org-mode Agenda.
837
838 The part after the double colon is a headline. The archived entries will be
839 filed under that headline. When omitted, the subtrees are simply filed away
840 at the end of the file, as top-level entries.
841
842 Here are a few examples:
843 \"%s_archive::\"
844 If the current file is Projects.org, archive in file
845 Projects.org_archive, as top-level trees. This is the default.
846
847 \"::* Archived Tasks\"
848 Archive in the current file, under the top-level headline
849 \"* Archived Tasks\".
850
851 \"~/org/archive.org::\"
852 Archive in file ~/org/archive.org (absolute path), as top-level trees.
853
854 \"basement::** Finished Tasks\"
855 Archive in file ./basement (relative path), as level 3 trees
856 below the level 2 heading \"** Finished Tasks\".
857
858 You may set this option on a per-file basis by adding to the buffer a
859 line like
860
861 #+ARCHIVE: basement::** Finished Tasks"
862 :group 'org-structure
863 :type 'string)
864
865 (defcustom org-archive-mark-done t
866 "Non-nil means, mark archived entries as DONE."
867 :group 'org-structure
868 :type 'boolean)
869
870 (defcustom org-archive-stamp-time t
871 "Non-nil means, add a time stamp to archived entries.
872 The time stamp will be added directly after the TODO state keyword in the
873 first line, so it is probably best to use this in combinations with
874 `org-archive-mark-done'."
875 :group 'org-structure
876 :type 'boolean)
877
878 (defgroup org-link nil
879 "Options concerning links in Org-mode."
880 :tag "Org Link"
881 :group 'org)
882
883 (defcustom org-link-format "<%s>"
884 "Default format for linkes in the buffer.
885 This is a format string for printf, %s will be replaced by the link text.
886 If you want to make sure that your link is always properly terminated,
887 include angle brackets into this format, like \"<%s>\". Some people also
888 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
889 :group 'org-link
890 :type '(choice
891 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
892 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
893 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
894 (string :tag "Other" :value "<%s>")))
895
896 (defcustom org-allow-space-in-links t
897 "Non-nil means, file names in links may contain space characters.
898 When nil, it becomes possible to put several links into a line.
899 Note that in tables, a link never extends accross fields, so in a table
900 it is always possible to put several links into a line.
901 Changing this varable requires a re-launch of Emacs of become effective."
902 :group 'org-link
903 :type 'boolean)
904
905 (defcustom org-line-numbers-in-file-links t
906 "Non-nil means, file links from `org-store-link' contain line numbers.
907 The line number will be added to the file name with :NNN and interpreted
908 by the command `org-open-at-point'.
909 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
910 negates this setting for the duration of the command."
911 :group 'org-link
912 :type 'boolean)
913
914 (defcustom org-keep-stored-link-after-insertion nil
915 "Non-nil means, keep link in list for entire session.
916
917 The command `org-store-link' adds a link pointing to the current
918 location to an internal list. These links accumulate during a session.
919 The command `org-insert-link' can be used to insert links into any
920 Org-mode file (offering completion for all stored links). When this
921 option is nil, every link which has been inserted once using \\[org-insert-link]
922 will be removed from the list, to make completing the unused links
923 more efficient."
924 :group 'org-link
925 :type 'boolean)
926
927 (defcustom org-link-frame-setup
928 '((vm . vm-visit-folder-other-frame)
929 (gnus . gnus-other-frame)
930 (file . find-file-other-window))
931 "Setup the frame configuration for following links.
932 When following a link with Emacs, it may often be useful to display
933 this link in another window or frame. This variable can be used to
934 set this up for the different types of links.
935 For VM, use any of
936 `vm-visit-folder'
937 `vm-visit-folder-other-frame'
938 For Gnus, use any of
939 `gnus'
940 `gnus-other-frame'
941 For FILE, use any of
942 `find-file'
943 `find-file-other-window'
944 `find-file-other-frame'
945 For the calendar, use the variable `calendar-setup'.
946 For BBDB, it is currently only possible to display the matches in
947 another window."
948 :group 'org-link
949 :type '(list
950 (cons (const vm)
951 (choice
952 (const vm-visit-folder)
953 (const vm-visit-folder-other-window)
954 (const vm-visit-folder-other-frame)))
955 (cons (const gnus)
956 (choice
957 (const gnus)
958 (const gnus-other-frame)))
959 (cons (const file)
960 (choice
961 (const find-file)
962 (const find-file-other-window)
963 (const find-file-other-frame)))))
964
965 (defcustom org-usenet-links-prefer-google nil
966 "Non-nil means, `org-store-link' will create web links to google groups.
967 When nil, Gnus will be used for such links.
968 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
969 negates this setting for the duration of the command."
970 :group 'org-link
971 :type 'boolean)
972
973 (defcustom org-open-non-existing-files nil
974 "Non-nil means, `org-open-file' will open non-existing file.
975 When nil, an error will be generated."
976 :group 'org-link
977 :type 'boolean)
978
979 (defcustom org-confirm-shell-links t
980 "Non-nil means, ask for confirmation before executing shell links.
981 The default is true, to keep new users from shooting into their own foot."
982 :group 'org-link
983 :type 'boolean)
984
985 (defconst org-file-apps-defaults-gnu
986 '((t . emacs)
987 ("jpg" . "xv %s")
988 ("gif" . "xv %s")
989 ("ppm" . "xv %s")
990 ("pgm" . "xv %s")
991 ("pbm" . "xv %s")
992 ("tif" . "xv %s")
993 ("png" . "xv %s")
994 ("ps" . "gv %s")
995 ("ps.gz" . "gv %s")
996 ("eps" . "gv %s")
997 ("eps.gz" . "gv %s")
998 ("dvi" . "xdvi %s")
999 ("mpeg" . "plaympeg %s")
1000 ("mp3" . "plaympeg %s")
1001 ("fig" . "xfig %s")
1002 ("pdf" . "acroread %s")
1003 ("doc" . "soffice %s")
1004 ("ppt" . "soffice %s")
1005 ("pps" . "soffice %s")
1006 ("html" . "netscape -remote openURL(%s,new-window)")
1007 ("htm" . "netscape -remote openURL(%s,new-window)")
1008 ("xs" . "soffice %s"))
1009 "Default file applications on a UNIX/LINUX system.
1010 See `org-file-apps'.")
1011
1012 (defconst org-file-apps-defaults-macosx
1013 '((t . "open %s")
1014 ("ps" . "gv %s")
1015 ("ps.gz" . "gv %s")
1016 ("eps" . "gv %s")
1017 ("eps.gz" . "gv %s")
1018 ("dvi" . "xdvi %s")
1019 ("fig" . "xfig %s"))
1020 "Default file applications on a MacOS X system.
1021 The system \"open\" is known as a default, but we use X11 applications
1022 for some files for which the OS does not have a good default.
1023 See `org-file-apps'.")
1024
1025 (defconst org-file-apps-defaults-windowsnt
1026 '((t . (w32-shell-execute "open" file)))
1027 "Default file applications on a Windows NT system.
1028 The system \"open\" is used for most files.
1029 See `org-file-apps'.")
1030
1031 (defcustom org-file-apps
1032 '(
1033 ("txt" . emacs)
1034 ("tex" . emacs)
1035 ("ltx" . emacs)
1036 ("org" . emacs)
1037 ("el" . emacs)
1038 )
1039 "External applications for opening `file:path' items in a document.
1040 Org-mode uses system defaults for different file types, but
1041 you can use this variable to set the application for a given file
1042 extension. The entries in this list are cons cells with a file extension
1043 and the corresponding command. Possible values for the command are:
1044 `emacs' The file will be visited by the current Emacs process.
1045 `default' Use the default application for this file type.
1046 string A command to be executed by a shell; %s will be replaced
1047 by the path to the file.
1048 sexp A Lisp form which will be evaluated. The file path will
1049 be available in the Lisp variable `file'.
1050 For more examples, see the system specific constants
1051 `org-file-apps-defaults-macosx'
1052 `org-file-apps-defaults-windowsnt'
1053 `org-file-apps-defaults-gnu'."
1054 :group 'org-link
1055 :type '(repeat
1056 (cons (string :tag "Extension")
1057 (choice :value ""
1058 (const :tag "Visit with Emacs" 'emacs)
1059 (const :tag "Use system default" 'default)
1060 (string :tag "Command")
1061 (sexp :tag "Lisp form")))))
1062
1063
1064 (defgroup org-remember nil
1065 "Options concerning interaction with remember.el."
1066 :tag "Org Remember"
1067 :group 'org)
1068
1069 (defcustom org-directory "~/org"
1070 "Directory with org files.
1071 This directory will be used as default to prompt for org files.
1072 Used by the hooks for remember.el."
1073 :group 'org-remember
1074 :type 'directory)
1075
1076 (defcustom org-default-notes-file "~/.notes"
1077 "Default target for storing notes.
1078 Used by the hooks for remember.el. This can be a string, or nil to mean
1079 the value of `remember-data-file'."
1080 :group 'org-remember
1081 :type '(choice
1082 (const :tag "Default from remember-data-file" nil)
1083 file))
1084
1085 (defcustom org-reverse-note-order nil
1086 "Non-nil means, store new notes at the beginning of a file or entry.
1087 When nil, new notes will be filed to the end of a file or entry."
1088 :group 'org-remember
1089 :type '(choice
1090 (const :tag "Reverse always" t)
1091 (const :tag "Reverse never" nil)
1092 (repeat :tag "By file name regexp"
1093 (cons regexp boolean))))
1094
1095 (defgroup org-table nil
1096 "Options concerning tables in Org-mode."
1097 :tag "Org Table"
1098 :group 'org)
1099
1100 (defcustom org-enable-table-editor 'optimized
1101 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1102 When nil, such lines will be treated like ordinary lines.
1103
1104 When equal to the symbol `optimized', the table editor will be optimized to
1105 do the following
1106 - Use automatic overwrite mode in front of whitespace in table fields.
1107 This make the structure of the table stay in tact as long as the edited
1108 field does not exceed the column width.
1109 - Minimize the number of realigns. Normally, the table is aligned each time
1110 TAB or RET are pressed to move to another field. With optimization this
1111 happens only if changes to a field might have changed the column width.
1112 Optimization requires replacing the functions `self-insert-command',
1113 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1114 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1115 very good at guessing when a re-align will be necessary, but you can always
1116 force one with \\[org-ctrl-c-ctrl-c].
1117
1118 If you would like to use the optimized version in Org-mode, but the
1119 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1120
1121 This variable can be used to turn on and off the table editor during a session,
1122 but in order to toggle optimization, a restart is required.
1123
1124 See also the variable `org-table-auto-blank-field'."
1125 :group 'org-table
1126 :type '(choice
1127 (const :tag "off" nil)
1128 (const :tag "on" t)
1129 (const :tag "on, optimized" optimized)))
1130
1131 (defcustom org-table-auto-blank-field t
1132 "Non-nil means, automatically blank table field when starting to type into it.
1133 This only happens when typing immediately after a field motion
1134 command (TAB, S-TAB or RET).
1135 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1136 :group 'org-table
1137 :type 'boolean)
1138
1139 (defcustom org-table-default-size "5x2"
1140 "The default size for newly created tables, Columns x Rows."
1141 :group 'org-table
1142 :type 'string)
1143
1144 (defcustom org-table-automatic-realign t
1145 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1146 When nil, aligning is only done with \\[org-table-align], or after column
1147 removal/insertion."
1148 :group 'org-table
1149 :type 'boolean)
1150
1151 (defcustom org-table-spaces-around-separators '(1 . 1)
1152 "The number of spaces to be placed before and after separators."
1153 :group 'org-table
1154 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1155
1156 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1157 "The number of spaces to be placed before and after separators.
1158 This option applies when the column separators have been made invisible."
1159 :group 'org-table
1160 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1161
1162 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1163 "Regular expression for recognizing numbers in table columns.
1164 If a table column contains mostly numbers, it will be aligned to the
1165 right. If not, it will be aligned to the left.
1166
1167 The default value of this option is a regular expression which allows
1168 anything which looks remotely like a number as used in scientific
1169 context. For example, all of the following will be considered a
1170 number:
1171 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1172
1173 Other options offered by the customize interface are more restrictive."
1174 :group 'org-table
1175 :type '(choice
1176 (const :tag "Positive Integers"
1177 "^[0-9]+$")
1178 (const :tag "Integers"
1179 "^[-+]?[0-9]+$")
1180 (const :tag "Floating Point Numbers"
1181 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1182 (const :tag "Floating Point Number or Integer"
1183 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1184 (const :tag "Exponential, Floating point, Integer"
1185 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1186 (const :tag "Very General Number-Like"
1187 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1188 (string :tag "Regexp:")))
1189
1190 (defcustom org-table-number-fraction 0.5
1191 "Fraction of numbers in a column required to make the column align right.
1192 In a column all non-white fields are considered. If at least this
1193 fraction of fields is matched by `org-table-number-fraction',
1194 alignment to the right border applies."
1195 :group 'org-table
1196 :type 'number)
1197
1198 (defcustom org-export-highlight-first-table-line t
1199 "Non-nil means, highlight the first table line.
1200 In HTML export, this means use <th> instead of <td>.
1201 In tables created with table.el, this applies to the first table line.
1202 In Org-mode tables, all lines before the first horizontal separator
1203 line will be formatted with <th> tags."
1204 :group 'org-table
1205 :type 'boolean)
1206
1207 (defcustom org-table-tab-recognizes-table.el t
1208 "Non-nil means, TAB will automatically notice a table.el table.
1209 When it sees such a table, it moves point into it and - if necessary -
1210 calls `table-recognize-table'."
1211 :group 'org-table
1212 :type 'boolean)
1213
1214 (defgroup org-table-calculation nil
1215 "Options concerning tables in Org-mode."
1216 :tag "Org Table Calculation"
1217 :group 'org)
1218
1219 (defcustom org-table-copy-increment t
1220 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1221 :group 'org-table-calculation
1222 :type 'boolean)
1223
1224 (defcustom org-calc-default-modes
1225 '(calc-internal-prec 12
1226 calc-float-format (float 5)
1227 calc-angle-mode deg
1228 calc-prefer-frac nil
1229 calc-symbolic-mode nil
1230 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1231 calc-display-working-message t
1232 )
1233 "List with Calc mode settings for use in calc-eval for table formulas.
1234 The list must contain alternating symbols (calc modes variables and values.
1235 Don't remove any of the default settings, just change the values. Org-mode
1236 relies on the variables to be present in the list."
1237 :group 'org-table-calculation
1238 :type 'plist)
1239
1240 (defcustom org-table-formula-evaluate-inline t
1241 "Non-nil means, TAB and RET evaluate a formula in current table field.
1242 If the current field starts with an equal sign, it is assumed to be a formula
1243 which should be evaluated as described in the manual and in the documentation
1244 string of the command `org-table-eval-formula'. This feature requires the
1245 Emacs calc package.
1246 When this variable is nil, formula calculation is only available through
1247 the command \\[org-table-eval-formula]."
1248 :group 'org-table-calculation
1249 :type 'boolean)
1250
1251
1252 (defcustom org-table-formula-use-constants t
1253 "Non-nil means, interpret constants in formulas in tables.
1254 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1255 by the value given in `org-table-formula-constants', or by a value obtained
1256 from the `constants.el' package."
1257 :group 'org-table-calculation
1258 :type 'boolean)
1259
1260 (defcustom org-table-formula-constants nil
1261 "Alist with constant names and values, for use in table formulas.
1262 The car of each element is a name of a constant, without the `$' before it.
1263 The cdr is the value as a string. For example, if you'd like to use the
1264 speed of light in a formula, you would configure
1265
1266 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1267
1268 and then use it in an equation like `$1*$c'."
1269 :group 'org-table-calculation
1270 :type '(repeat
1271 (cons (string :tag "name")
1272 (string :tag "value"))))
1273
1274 (defcustom org-table-formula-numbers-only nil
1275 "Non-nil means, calculate only with numbers in table formulas.
1276 Then all input fields will be converted to a number, and the result
1277 must also be a number. When nil, calc's full potential is available
1278 in table calculations, including symbolics etc."
1279 :group 'org-table-calculation
1280 :type 'boolean)
1281
1282 (defcustom org-table-allow-automatic-line-recalculation t
1283 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1284 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1285 :group 'org-table-calculation
1286 :type 'boolean)
1287
1288 (defgroup org-export nil
1289 "Options for exporting org-listings."
1290 :tag "Org Export"
1291 :group 'org)
1292
1293 (defcustom org-export-language-setup
1294 '(("en" "Author" "Date" "Table of Contents")
1295 ("da" "Ophavsmand" "Dato" "Indhold")
1296 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1297 ("es" "Autor" "Fecha" "\xccndice")
1298 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1299 ("it" "Autore" "Data" "Indice")
1300 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1301 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1302 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1303 "Terms used in export text, translated to different languages.
1304 Use the variable `org-export-default-language' to set the language,
1305 or use the +OPTION lines for a per-file setting."
1306 :group 'org-export
1307 :type '(repeat
1308 (list
1309 (string :tag "HTML language tag")
1310 (string :tag "Author")
1311 (string :tag "Date")
1312 (string :tag "Table of Contents"))))
1313
1314 (defcustom org-export-default-language "en"
1315 "The default language of HTML export, as a string.
1316 This should have an association in `org-export-language-setup'"
1317 :group 'org-export
1318 :type 'string)
1319
1320 (defcustom org-export-headline-levels 3
1321 "The last level which is still exported as a headline.
1322 Inferior levels will produce itemize lists when exported.
1323 Note that a numeric prefix argument to an exporter function overrides
1324 this setting.
1325
1326 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1327 :group 'org-export
1328 :type 'number)
1329
1330 (defcustom org-export-with-section-numbers t
1331 "Non-nil means, add section numbers to headlines when exporting.
1332
1333 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1334 :group 'org-export
1335 :type 'boolean)
1336
1337 (defcustom org-export-with-toc t
1338 "Non-nil means, create a table of contents in exported files.
1339 The TOC contains headlines with levels up to`org-export-headline-levels'.
1340
1341 Headlines which contain any TODO items will be marked with \"(*)\" in
1342 ASCII export, and with red color in HTML output.
1343
1344 In HTML output, the TOC will be clickable.
1345
1346 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1347 :group 'org-export
1348 :type 'boolean)
1349
1350 (defcustom org-export-preserve-breaks nil
1351 "Non-nil means, preserve all line breaks when exporting.
1352 Normally, in HTML output paragraphs will be reformatted. In ASCII
1353 export, line breaks will always be preserved, regardless of this variable.
1354
1355 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1356 :group 'org-export
1357 :type 'boolean)
1358
1359 (defcustom org-export-html-inline-images t
1360 "Non-nil means, inline images into exported HTML pages.
1361 The link will still be to the original location of the image file.
1362 So if you are moving the page, lets say to your public HTML site,
1363 you will have to move the image and maybe change the link."
1364 :group 'org-export
1365 :type 'boolean)
1366
1367 (defcustom org-export-html-expand t
1368 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1369 When nil, these tags will be exported as plain text and therefore
1370 not be interpreted by a browser.
1371
1372 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1373 :group 'org-export
1374 :type 'boolean)
1375
1376 (defcustom org-export-with-fixed-width t
1377 "Non-nil means, lines starting with \":\" will be in fixed width font.
1378 This can be used to have pre-formatted text, fragments of code etc. For
1379 example
1380 : ;; Some Lisp examples
1381 : (while (defc cnt)
1382 : (ding))
1383 will be looking just like this in also HTML. In ASCII export, this option
1384 has no effect.
1385
1386 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1387 :group 'org-export
1388 :type 'boolean)
1389
1390 (defcustom org-export-with-tables t
1391 "If non-nil, lines starting with \"|\" define a table.
1392 For example:
1393
1394 | Name | Address | Birthday |
1395 |-------------+----------+-----------|
1396 | Arthur Dent | England | 29.2.2100 |
1397
1398 In ASCII export, this option has no effect.
1399
1400 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1401 :group 'org-export
1402 :type 'boolean)
1403
1404 (defcustom org-export-prefer-native-exporter-for-tables nil
1405 "Non-nil means, always export tables created with table.el natively.
1406 Natively means, use the HTML code generator in table.el.
1407 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1408 the table does not use row- or column-spanning). This has the
1409 advantage, that the automatic HTML conversions for math symbols and
1410 sub/superscripts can be applied. Org-mode's HTML generator is also
1411 much faster."
1412 :group 'org-export
1413 :type 'boolean)
1414
1415 (defcustom org-export-html-table-tag
1416 "<table border=1 cellspacing=0 cellpadding=6>"
1417 "The HTML tag used to start a table.
1418 This must be a <table> tag, but you may change the options like
1419 borders and spacing."
1420 :group 'org-export
1421 :type 'string)
1422
1423 (defcustom org-export-with-emphasize t
1424 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1425 If the export target supports emphasizing text, the word will be
1426 typeset in bold, italic, or underlined, respectively. Works only for
1427 single words, but you can say: I *really* *mean* *this*.
1428 In ASCII export, this option has no effect.
1429
1430 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1431 :group 'org-export
1432 :type 'boolean)
1433
1434 (defcustom org-match-sexp-depth 3
1435 "Number of stacked braces for sub/superscript matching.
1436 This has to be set before loading org.el to be effective."
1437 :group 'org-export
1438 :type 'integer)
1439
1440 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1441 (defcustom org-export-with-sub-superscripts t
1442 "Non-nil means, interpret \"_\" and \"^\" for export.
1443 When this option is turned on, you can use TeX-like syntax for sub- and
1444 superscripts. Several characters after \"_\" or \"^\" will be
1445 considered as a single item - so grouping with {} is normally not
1446 needed. For example, the following things will be parsed as single
1447 sub- or superscripts.
1448
1449 10^24 or 10^tau several digits will be considered 1 item
1450 10^-12 or 10^-tau a leading sign with digits or a word
1451 x^2-y^3 will be read as x^2 - y^3, because items are
1452 terminated by almost any nonword/nondigit char.
1453 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1454
1455 Still, ambiguity is possible - so when in doubt use {} to enclose the
1456 sub/superscript.
1457 In ASCII export, this option has no effect.
1458
1459 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1460 :group 'org-export
1461 :type 'boolean)
1462
1463 (defcustom org-export-with-TeX-macros t
1464 "Non-nil means, interpret simple TeX-like macros when exporting.
1465 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1466 No only real TeX macros will work here, but the standard HTML entities
1467 for math can be used as macro names as well. For a list of supported
1468 names in HTML export, see the constant `org-html-entities'.
1469 In ASCII export, this option has no effect.
1470
1471 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1472 :group 'org-export
1473 :type 'boolean)
1474
1475 (defcustom org-export-html-with-timestamp nil
1476 "If non-nil, write `org-export-html-html-helper-timestamp'
1477 into the exported html text. Otherwise, the buffer will just be saved
1478 to a file."
1479 :group 'org-export
1480 :type 'boolean)
1481
1482 (defcustom org-export-html-html-helper-timestamp
1483 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1484 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1485 :group 'org-export
1486 :type 'string)
1487
1488 (defcustom org-export-ascii-show-new-buffer t
1489 "Non-nil means, popup buffer containing the exported ASCII text.
1490 Otherwise the buffer will just be saved to a file and stay hidden."
1491 :group 'org-export
1492 :type 'boolean)
1493
1494 (defcustom org-export-html-show-new-buffer nil
1495 "Non-nil means, popup buffer containing the exported html text.
1496 Otherwise, the buffer will just be saved to a file and stay hidden."
1497 :group 'org-export
1498 :type 'boolean)
1499
1500 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1501 "The file name for the iCalendar file covering all agenda files.
1502 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1503 :group 'org-export
1504 :type 'file)
1505
1506 (defcustom org-icalendar-include-todo nil
1507 "Non-nil means, export to iCalendar files should also cover TODO items."
1508 :group 'org-export
1509 :type 'boolean)
1510
1511 ;; FIXME: not yet used.
1512 (defcustom org-icalendar-combined-name "OrgMode"
1513 "Calendar name for the combined iCalendar representing all agenda files."
1514 :group 'org-export
1515 :type 'string)
1516
1517 (defgroup org-faces nil
1518 "Faces for highlighting in Org-mode."
1519 :tag "Org Faces"
1520 :group 'org)
1521
1522 (defface org-level-1 ;; font-lock-function-name-face
1523 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1524 (((class color) (background light)) (:foreground "Blue"))
1525 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1526 (t (:inverse-video t :bold t)))
1527 "Face used for level 1 headlines."
1528 :group 'org-faces)
1529
1530 (defface org-level-2 ;; font-lock-variable-name-face
1531 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1532 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1533 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1534 (t (:bold t :italic t)))
1535 "Face used for level 2 headlines."
1536 :group 'org-faces)
1537
1538 (defface org-level-3 ;; font-lock-keyword-face
1539 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1540 (((class color) (background light)) (:foreground "Purple"))
1541 (((class color) (background dark)) (:foreground "Cyan"))
1542 (t (:bold t)))
1543 "Face used for level 3 headlines."
1544 :group 'org-faces)
1545
1546 (defface org-level-4 ;; font-lock-comment-face
1547 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1548 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1549 (((class color) (background light)) (:foreground "Firebrick"))
1550 (((class color) (background dark)) (:foreground "chocolate1"))
1551 (t (:bold t :italic t)))
1552 "Face used for level 4 headlines."
1553 :group 'org-faces)
1554
1555 (defface org-level-5 ;; font-lock-type-face
1556 '((((type tty) (class color)) (:foreground "green"))
1557 (((class color) (background light)) (:foreground "ForestGreen"))
1558 (((class color) (background dark)) (:foreground "PaleGreen"))
1559 (t (:bold t :underline t)))
1560 "Face used for level 5 headlines."
1561 :group 'org-faces)
1562
1563 (defface org-level-6 ;; font-lock-constant-face
1564 '((((type tty) (class color)) (:foreground "magenta"))
1565 (((class color) (background light)) (:foreground "CadetBlue"))
1566 (((class color) (background dark)) (:foreground "Aquamarine"))
1567 (t (:bold t :underline t)))
1568 "Face used for level 6 headlines."
1569 :group 'org-faces)
1570
1571 (defface org-level-7 ;; font-lock-builtin-face
1572 '((((type tty) (class color)) (:foreground "blue" :weight light))
1573 (((class color) (background light)) (:foreground "Orchid"))
1574 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1575 (t (:bold t)))
1576 "Face used for level 7 headlines."
1577 :group 'org-faces)
1578
1579 (defface org-level-8 ;; font-lock-string-face
1580 '((((type tty) (class color)) (:foreground "green"))
1581 (((class color) (background light)) (:foreground "RosyBrown"))
1582 (((class color) (background dark)) (:foreground "LightSalmon"))
1583 (t (:italic t)))
1584 "Face used for level 8 headlines."
1585 :group 'org-faces)
1586
1587 (defface org-special-keyword ;; font-lock-string-face
1588 '((((type tty) (class color)) (:foreground "green"))
1589 (((class color) (background light)) (:foreground "RosyBrown"))
1590 (((class color) (background dark)) (:foreground "LightSalmon"))
1591 (t (:italic t)))
1592 "Face used for level 8 headlines."
1593 :group 'org-faces)
1594
1595 (defface org-warning ;; font-lock-warning-face
1596 '((((type tty) (class color)) (:foreground "red"))
1597 (((class color) (background light)) (:foreground "Red" :bold t))
1598 (((class color) (background dark)) (:foreground "Red1" :bold t))
1599 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1600 (t (:inverse-video t :bold t)))
1601 "Face for deadlines and TODO keywords."
1602 :group 'org-faces)
1603
1604 (defcustom org-fontify-done-headline nil
1605 "Non-nil means, change the face of a headline if it is marked DONE.
1606 Normally, only the TODO/DONE keyword indicates the state of a headline.
1607 When this is non-nil, the headline after the keyword is set to the
1608 `org-headline-done' as an additional indication."
1609 :group 'org-faces
1610 :type 'boolean)
1611
1612 (defface org-headline-done ;; font-lock-string-face
1613 '((((type tty) (class color)) (:foreground "green"))
1614 (((class color) (background light)) (:foreground "RosyBrown"))
1615 (((class color) (background dark)) (:foreground "LightSalmon"))
1616 (t (:italic t)))
1617 "Face used to indicate that a headline is DONE. See also the variable
1618 `org-fontify-done-headline'."
1619 :group 'org-faces)
1620
1621 ;; Inheritance does not yet work for xemacs. So we just copy...
1622
1623 (defface org-deadline-announce
1624 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1625 (((class color) (background light)) (:foreground "Blue"))
1626 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1627 (t (:inverse-video t :bold t)))
1628 "Face for upcoming deadlines."
1629 :group 'org-faces)
1630
1631 (defface org-scheduled-today
1632 '((((type tty) (class color)) (:foreground "green"))
1633 (((class color) (background light)) (:foreground "DarkGreen"))
1634 (((class color) (background dark)) (:foreground "PaleGreen"))
1635 (t (:bold t :underline t)))
1636 "Face for items scheduled for a certain day."
1637 :group 'org-faces)
1638
1639 (defface org-scheduled-previously
1640 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1641 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1642 (((class color) (background light)) (:foreground "Firebrick"))
1643 (((class color) (background dark)) (:foreground "chocolate1"))
1644 (t (:bold t :italic t)))
1645 "Face for items scheduled previously, and not yet done."
1646 :group 'org-faces)
1647
1648 (defface org-formula
1649 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1650 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1651 (((class color) (background light)) (:foreground "Firebrick"))
1652 (((class color) (background dark)) (:foreground "chocolate1"))
1653 (t (:bold t :italic t)))
1654 "Face for items scheduled previously, and not yet done."
1655 :group 'org-faces)
1656
1657 (defface org-link
1658 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1659 (((class color) (background light)) (:foreground "Purple"))
1660 (((class color) (background dark)) (:foreground "Cyan"))
1661 (t (:bold t)))
1662 "Face for links."
1663 :group 'org-faces)
1664
1665 (defface org-done ;; font-lock-type-face
1666 '((((type tty) (class color)) (:foreground "green"))
1667 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1668 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1669 (t (:bold t :underline t)))
1670 "Face used for DONE."
1671 :group 'org-faces)
1672
1673 (defface org-table ;; font-lock-function-name-face
1674 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1675 (((class color) (background light)) (:foreground "Blue"))
1676 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1677 (t (:inverse-video t :bold t)))
1678 "Face used for tables."
1679 :group 'org-faces)
1680
1681 (defface org-time-grid ;; font-lock-variable-name-face
1682 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1683 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1684 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1685 (t (:bold t :italic t)))
1686 "Face used for level 2 headlines."
1687 :group 'org-faces)
1688
1689 (defvar org-level-faces
1690 '(
1691 org-level-1
1692 org-level-2
1693 org-level-3
1694 org-level-4
1695 org-level-5
1696 org-level-6
1697 org-level-7
1698 org-level-8
1699 ))
1700 (defvar org-n-levels (length org-level-faces))
1701
1702 (defun org-set-regexps-and-options ()
1703 "Precompute regular expressions for current buffer."
1704 (when (eq major-mode 'org-mode)
1705 (let ((re (org-make-options-regexp
1706 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1707 "STARTUP" "ARCHIVE")))
1708 (splitre "[ \t]+")
1709 kwds int key value cat arch)
1710 (save-excursion
1711 (save-restriction
1712 (widen)
1713 (goto-char (point-min))
1714 (while (re-search-forward re nil t)
1715 (setq key (match-string 1) value (match-string 2))
1716 (cond
1717 ((equal key "CATEGORY")
1718 (if (string-match "[ \t]+$" value)
1719 (setq value (replace-match "" t t value)))
1720 (setq cat (intern value)))
1721 ((equal key "SEQ_TODO")
1722 (setq int 'sequence
1723 kwds (append kwds (org-split-string value splitre))))
1724 ((equal key "PRI_TODO")
1725 (setq int 'priority
1726 kwds (append kwds (org-split-string value splitre))))
1727 ((equal key "TYP_TODO")
1728 (setq int 'type
1729 kwds (append kwds (org-split-string value splitre))))
1730 ((equal key "STARTUP")
1731 (let ((opts (org-split-string value splitre))
1732 (set '(("fold" org-startup-folded t)
1733 ("nofold" org-startup-folded nil)
1734 ("content" org-startup-folded content)
1735 ("dlcheck" org-startup-with-deadline-check t)
1736 ("nodlcheck" org-startup-with-deadline-check nil)))
1737 l var val)
1738 (while (setq l (assoc (pop opts) set))
1739 (setq var (nth 1 l) val (nth 2 l))
1740 (set (make-local-variable var) val))))
1741 ((equal key "ARCHIVE")
1742 (string-match " *$" value)
1743 (setq arch (replace-match "" t t value))
1744 (remove-text-properties 0 (length arch)
1745 '(face t fontified t) arch)))
1746 )))
1747 (and cat (set (make-local-variable 'org-category) cat))
1748 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1749 (and arch (set (make-local-variable 'org-archive-location) arch))
1750 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1751 ;; Compute the regular expressions and other local variables
1752 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1753 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1754 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1755 (length org-scheduled-string)))
1756 org-done-string
1757 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1758 org-todo-regexp
1759 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1760 "\\|") "\\)\\>")
1761 org-not-done-regexp
1762 (concat "\\<\\("
1763 (mapconcat 'regexp-quote
1764 (nreverse (cdr (reverse org-todo-keywords)))
1765 "\\|")
1766 "\\)\\>")
1767 org-todo-line-regexp
1768 (concat "^\\(\\*+\\)[ \t]*\\("
1769 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1770 "\\)? *\\(.*\\)")
1771 org-nl-done-regexp
1772 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1773 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1774 org-deadline-regexp (concat "\\<" org-deadline-string)
1775 org-deadline-time-regexp
1776 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1777 org-deadline-line-regexp
1778 (concat "\\<\\(" org-deadline-string "\\).*")
1779 org-scheduled-regexp
1780 (concat "\\<" org-scheduled-string)
1781 org-scheduled-time-regexp
1782 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1783 (org-set-font-lock-defaults)))
1784
1785 ;; Tell the compiler about dynamically scoped variables,
1786 ;; and variables from other packages
1787 (eval-when-compile
1788 (defvar zmacs-regions)
1789 (defvar original-date)
1790 (defvar org-transient-mark-mode)
1791 (defvar org-old-auto-fill-inhibit-regexp)
1792 (defvar orgtbl-mode-menu)
1793 (defvar org-html-entities)
1794 (defvar org-goto-start-pos)
1795 (defvar org-cursor-color)
1796 (defvar org-time-was-given)
1797 (defvar org-ts-what)
1798 (defvar mark-active)
1799 (defvar timecnt)
1800 (defvar levels-open)
1801 (defvar title)
1802 (defvar author)
1803 (defvar email)
1804 (defvar text)
1805 (defvar entry)
1806 (defvar date)
1807 (defvar language)
1808 (defvar options)
1809 (defvar ans1)
1810 (defvar ans2)
1811 (defvar starting-day)
1812 (defvar include-all-loc)
1813 (defvar vm-message-pointer)
1814 (defvar vm-folder-directory)
1815 (defvar wl-summary-buffer-elmo-folder)
1816 (defvar wl-summary-buffer-folder-name)
1817 (defvar gnus-group-name)
1818 (defvar gnus-article-current)
1819 (defvar w3m-current-url)
1820 (defvar org-selected-point)
1821 (defvar calendar-mode-map)
1822 (defvar remember-save-after-remembering)
1823 (defvar remember-data-file))
1824
1825
1826 ;;; Define the mode
1827
1828 (defvar org-mode-map (copy-keymap outline-mode-map)
1829 "Keymap for Org-mode.")
1830
1831 (defvar org-struct-menu)
1832 (defvar org-org-menu)
1833 (defvar org-tbl-menu)
1834
1835 ;; We use a before-change function to check if a table might need
1836 ;; an update.
1837 (defvar org-table-may-need-update t
1838 "Indicates of a table might need an update.
1839 This variable is set by `org-before-change-function'. `org-table-align'
1840 sets it back to nil.")
1841 (defvar org-mode-hook nil)
1842 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1843
1844
1845 ;;;###autoload
1846 (define-derived-mode org-mode outline-mode "Org"
1847 "Outline-based notes management and organizer, alias
1848 \"Carstens outline-mode for keeping track of everything.\"
1849
1850 Org-mode develops organizational tasks around a NOTES file which
1851 contains information about projects as plain text. Org-mode is
1852 implemented on top of outline-mode, which is ideal to keep the content
1853 of large files well structured. It supports ToDo items, deadlines and
1854 time stamps, which magically appear in the diary listing of the Emacs
1855 calendar. Tables are easily created with a built-in table editor.
1856 Plain text URL-like links connect to websites, emails (VM), Usenet
1857 messages (Gnus), BBDB entries, and any files related to the project.
1858 For printing and sharing of notes, an Org-mode file (or a part of it)
1859 can be exported as a structured ASCII or HTML file.
1860
1861 The following commands are available:
1862
1863 \\{org-mode-map}"
1864 (easy-menu-add org-org-menu)
1865 (easy-menu-add org-tbl-menu)
1866 (org-install-agenda-files-menu)
1867 (setq outline-regexp "\\*+")
1868 (if org-startup-truncated (setq truncate-lines t))
1869 (org-set-regexps-and-options)
1870 (set (make-local-variable 'font-lock-unfontify-region-function)
1871 'org-unfontify-region)
1872 ;; Activate before-change-function
1873 (set (make-local-variable 'org-table-may-need-update) t)
1874 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1875 (add-hook 'before-change-functions 'org-before-change-function nil
1876 'local)
1877 ;; Paragraph regular expressions
1878 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1879 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1880 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1881 (set (make-local-variable 'auto-fill-inhibit-regexp)
1882 (concat "\\*\\|#"
1883 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1884 (concat
1885 "\\|[ \t]*["
1886 (if org-enable-table-editor "|" "")
1887 (if org-enable-fixed-width-editor ":" "")
1888 "]"))))
1889 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1890 ;; Settings for Calc embedded mode
1891 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1892 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1893 (if (and org-insert-mode-line-in-empty-file
1894 (interactive-p)
1895 (= (point-min) (point-max)))
1896 (insert " -*- mode: org -*-\n\n"))
1897
1898 ;; Get rid of Outline menus, they are not needed
1899 ;; Need to do this here because define-derived-mode sets up
1900 ;; the keymap so late.
1901 (if org-xemacs-p
1902 (progn
1903 (delete-menu-item '("Headings"))
1904 (delete-menu-item '("Show"))
1905 (delete-menu-item '("Hide"))
1906 (set-menubar-dirty-flag))
1907 (define-key org-mode-map [menu-bar headings] 'undefined)
1908 (define-key org-mode-map [menu-bar hide] 'undefined)
1909 (define-key org-mode-map [menu-bar show] 'undefined))
1910
1911 (unless org-inhibit-startup
1912 (if org-startup-with-deadline-check
1913 (call-interactively 'org-check-deadlines)
1914 (cond
1915 ((eq org-startup-folded t)
1916 (org-cycle '(4)))
1917 ((eq org-startup-folded 'content)
1918 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1919 (org-cycle '(4)) (org-cycle '(4))))))))
1920
1921 (defun org-fill-paragraph (&optional justify)
1922 "Re-align a table, pass through to fill-paragraph if no table."
1923 (save-excursion
1924 (beginning-of-line 1)
1925 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1926
1927 (defsubst org-current-line (&optional pos)
1928 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1929
1930 ;;; Font-Lock stuff
1931
1932 (defvar org-mouse-map (make-sparse-keymap))
1933 (define-key org-mouse-map
1934 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1935 (define-key org-mouse-map
1936 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1937
1938 (require 'font-lock)
1939
1940 (defconst org-non-link-chars "\t\n\r|<>\000")
1941 (defconst org-link-regexp
1942 (if org-allow-space-in-links
1943 (concat
1944 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1945 (concat
1946 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1947 )
1948 "Regular expression for matching links.")
1949 (defconst org-link-maybe-angles-regexp
1950 (concat "<?\\(" org-link-regexp "\\)>?")
1951 "Matches a link and optionally surrounding angle brackets.")
1952 (defconst org-protected-link-regexp
1953 (concat "\000" org-link-regexp "\000")
1954 "Matches a link and optionally surrounding angle brackets.")
1955
1956 (defconst org-ts-lengths
1957 (cons (length (format-time-string (car org-time-stamp-formats)))
1958 (length (format-time-string (cdr org-time-stamp-formats))))
1959 "This holds the lengths of the two different time formats.")
1960 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1961 "Regular expression for fast time stamp matching.")
1962 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1963 "Regular expression matching time strings for analysis.")
1964 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1965 "Regular expression matching time stamps, with groups.")
1966 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1967 "Regular expression matching a time stamp range.")
1968 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1969 org-ts-regexp "\\)?")
1970 "Regular expression matching a time stamp or time stamp range.")
1971
1972 (defun org-activate-links (limit)
1973 "Run through the buffer and add overlays to links."
1974 (if (re-search-forward org-link-regexp limit t)
1975 (progn
1976 (add-text-properties (match-beginning 0) (match-end 0)
1977 (list 'mouse-face 'highlight
1978 'keymap org-mouse-map))
1979 t)))
1980
1981 (defun org-activate-dates (limit)
1982 "Run through the buffer and add overlays to dates."
1983 (if (re-search-forward org-tsr-regexp limit t)
1984 (progn
1985 (add-text-properties (match-beginning 0) (match-end 0)
1986 (list 'mouse-face 'highlight
1987 'keymap org-mouse-map))
1988 t)))
1989
1990 (defun org-font-lock-level ()
1991 (save-excursion
1992 (org-back-to-heading t)
1993 (- (match-end 0) (match-beginning 0))))
1994
1995 (defvar org-font-lock-keywords nil)
1996
1997 (defun org-set-font-lock-defaults ()
1998 (let ((org-font-lock-extra-keywords
1999 (list
2000 '(org-activate-links (0 'org-link))
2001 '(org-activate-dates (0 'org-link))
2002 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2003 '(1 'org-warning t))
2004 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2005 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
2006 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
2007 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2008 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2009 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2010 ;; (3 'bold))
2011 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2012 ;; (3 'italic))
2013 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2014 ;; (3 'underline))
2015 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2016 ; '(1 'org-warning t))
2017 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2018 "\\|" org-quote-string "\\)\\>")
2019 '(1 'org-special-keyword t))
2020 '("^#.*" (0 'font-lock-comment-face t))
2021 (if org-fontify-done-headline
2022 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2023 '(1 'org-done t) '(2 'org-headline-done t))
2024 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2025 '(1 'org-done t)))
2026 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2027 (1 'org-table t))
2028 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2029 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2030 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2031 )))
2032 (set (make-local-variable 'org-font-lock-keywords)
2033 (append
2034 (if org-noutline-p ; FIXME: I am not sure if eval will work
2035 ; on XEmacs if noutline is ever ported
2036 `((eval . (list "^\\(\\*+\\).*"
2037 ,(if org-level-color-stars-only 1 0)
2038 '(nth ;; FIXME: 1<->0 ????
2039 (% (- (match-end 1) (match-beginning 1) 1)
2040 org-n-levels)
2041 org-level-faces)
2042 nil t)))
2043 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2044 (,(if org-level-color-stars-only 2 0)
2045 (nth (% (- (match-end 2) (match-beginning 2) 1)
2046 org-n-levels)
2047 org-level-faces)
2048 nil t))))
2049 org-font-lock-extra-keywords))
2050 (set (make-local-variable 'font-lock-defaults)
2051 '(org-font-lock-keywords t nil nil backward-paragraph))
2052 (kill-local-variable 'font-lock-keywords) nil))
2053
2054 (defun org-unfontify-region (beg end &optional maybe_loudly)
2055 "Remove fontification and activation overlays from links."
2056 (font-lock-default-unfontify-region beg end)
2057 (let* ((buffer-undo-list t)
2058 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2059 (inhibit-modification-hooks t)
2060 deactivate-mark buffer-file-name buffer-file-truename)
2061 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2062
2063 ;;; Visibility cycling
2064
2065 (defvar org-cycle-global-status nil)
2066 (defvar org-cycle-subtree-status nil)
2067 (defun org-cycle (&optional arg)
2068 "Visibility cycling for Org-mode.
2069
2070 - When this function is called with a prefix argument, rotate the entire
2071 buffer through 3 states (global cycling)
2072 1. OVERVIEW: Show only top-level headlines.
2073 2. CONTENTS: Show all headlines of all levels, but no body text.
2074 3. SHOW ALL: Show everything.
2075
2076 - When point is at the beginning of a headline, rotate the subtree started
2077 by this line through 3 different states (local cycling)
2078 1. FOLDED: Only the main headline is shown.
2079 2. CHILDREN: The main headline and the direct children are shown. From
2080 this state, you can move to one of the children and
2081 zoom in further.
2082 3. SUBTREE: Show the entire subtree, including body text.
2083
2084 - When there is a numeric prefix, go up to a heading with level ARG, do
2085 a `show-subtree' and return to the previous cursor position. If ARG
2086 is negative, go up that many levels.
2087
2088 - When point is not at the beginning of a headline, execute
2089 `indent-relative', like TAB normally does. See the option
2090 `org-cycle-emulate-tab' for details.
2091
2092 - Special case: if point is the the beginning of the buffer and there is
2093 no headline in line 1, this function will act as if called with prefix arg."
2094 (interactive "P")
2095
2096 (if (or (and (bobp) (not (looking-at outline-regexp)))
2097 (equal arg '(4)))
2098 ;; special case: use global cycling
2099 (setq arg t))
2100
2101 (cond
2102
2103 ((org-at-table-p 'any)
2104 ;; Enter the table or move to the next field in the table
2105 (or (org-table-recognize-table.el)
2106 (progn
2107 (org-table-justify-field-maybe)
2108 (org-table-next-field))))
2109
2110 ((eq arg t) ;; Global cycling
2111
2112 (cond
2113 ((and (eq last-command this-command)
2114 (eq org-cycle-global-status 'overview))
2115 ;; We just created the overview - now do table of contents
2116 ;; This can be slow in very large buffers, so indicate action
2117 (message "CONTENTS...")
2118 (save-excursion
2119 ;; Visit all headings and show their offspring
2120 (goto-char (point-max))
2121 (catch 'exit
2122 (while (and (progn (condition-case nil
2123 (outline-previous-visible-heading 1)
2124 (error (goto-char (point-min))))
2125 t)
2126 (looking-at outline-regexp))
2127 (show-branches)
2128 (if (bobp) (throw 'exit nil))))
2129 (message "CONTENTS...done"))
2130 (setq org-cycle-global-status 'contents)
2131 (run-hook-with-args 'org-cycle-hook 'contents))
2132
2133 ((and (eq last-command this-command)
2134 (eq org-cycle-global-status 'contents))
2135 ;; We just showed the table of contents - now show everything
2136 (show-all)
2137 (message "SHOW ALL")
2138 (setq org-cycle-global-status 'all)
2139 (run-hook-with-args 'org-cycle-hook 'all))
2140
2141 (t
2142 ;; Default action: go to overview
2143 (hide-sublevels 1)
2144 (message "OVERVIEW")
2145 (setq org-cycle-global-status 'overview)
2146 (run-hook-with-args 'org-cycle-hook 'overview))))
2147
2148 ((integerp arg)
2149 ;; Show-subtree, ARG levels up from here.
2150 (save-excursion
2151 (org-back-to-heading)
2152 (outline-up-heading (if (< arg 0) (- arg)
2153 (- (outline-level) arg)))
2154 (org-show-subtree)))
2155
2156 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2157 ;; At a heading: rotate between three different views
2158 (org-back-to-heading)
2159 (let ((goal-column 0) eoh eol eos)
2160 ;; First, some boundaries
2161 (save-excursion
2162 (org-back-to-heading)
2163 (save-excursion
2164 (beginning-of-line 2)
2165 (while (and (not (eobp)) ;; this is like `next-line'
2166 (get-char-property (1- (point)) 'invisible))
2167 (beginning-of-line 2)) (setq eol (point)))
2168 (outline-end-of-heading) (setq eoh (point))
2169 (outline-end-of-subtree) (setq eos (point))
2170 (outline-next-heading))
2171 ;; Find out what to do next and set `this-command'
2172 (cond
2173 ((= eos eoh)
2174 ;; Nothing is hidden behind this heading
2175 (message "EMPTY ENTRY")
2176 (setq org-cycle-subtree-status nil))
2177 ((>= eol eos)
2178 ;; Entire subtree is hidden in one line: open it
2179 (org-show-entry)
2180 (show-children)
2181 (message "CHILDREN")
2182 (setq org-cycle-subtree-status 'children)
2183 (run-hook-with-args 'org-cycle-hook 'children))
2184 ((and (eq last-command this-command)
2185 (eq org-cycle-subtree-status 'children))
2186 ;; We just showed the children, now show everything.
2187 (org-show-subtree)
2188 (message "SUBTREE")
2189 (setq org-cycle-subtree-status 'subtree)
2190 (run-hook-with-args 'org-cycle-hook 'subtree))
2191 (t
2192 ;; Default action: hide the subtree.
2193 (hide-subtree)
2194 (message "FOLDED")
2195 (setq org-cycle-subtree-status 'folded)
2196 (run-hook-with-args 'org-cycle-hook 'folded)))))
2197
2198 ;; TAB emulation
2199 (buffer-read-only (org-back-to-heading))
2200 ((if (and (eq org-cycle-emulate-tab 'white)
2201 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2202 t
2203 (eq org-cycle-emulate-tab t))
2204 (if (and (looking-at "[ \n\r\t]")
2205 (string-match "^[ \t]*$" (buffer-substring
2206 (point-at-bol) (point))))
2207 (progn
2208 (beginning-of-line 1)
2209 (and (looking-at "[ \t]+") (replace-match ""))))
2210 (indent-relative))
2211
2212 (t (save-excursion
2213 (org-back-to-heading)
2214 (org-cycle)))))
2215
2216 (defun org-optimize-window-after-visibility-change (state)
2217 "Adjust the window after a change in outline visibility.
2218 This function is the default value of the hook `org-cycle-hook'."
2219 (cond
2220 ((eq state 'overview) (org-first-headline-recenter 1))
2221 ((eq state 'content) nil)
2222 ((eq state 'all) nil)
2223 ((eq state 'folded) nil)
2224 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2225 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2226
2227 (defun org-subtree-end-visible-p ()
2228 "Is the end of the current subtree visible?"
2229 (pos-visible-in-window-p
2230 (save-excursion (outline-end-of-subtree) (point))))
2231
2232 (defun org-first-headline-recenter (&optional N)
2233 "Move cursor to the first headline and recenter the headline.
2234 Optional argument N means, put the headline into the Nth line of the window."
2235 (goto-char (point-min))
2236 (when (re-search-forward (concat "^" outline-regexp) nil t)
2237 (beginning-of-line)
2238 (recenter (prefix-numeric-value N))))
2239
2240 (defvar org-goto-window-configuration nil)
2241 (defvar org-goto-marker nil)
2242 (defvar org-goto-map (make-sparse-keymap))
2243 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2244 (while (setq cmd (pop cmds))
2245 (substitute-key-definition cmd cmd org-goto-map global-map)))
2246 (define-key org-goto-map "\C-m" 'org-goto-ret)
2247 (define-key org-goto-map [(left)] 'org-goto-left)
2248 (define-key org-goto-map [(right)] 'org-goto-right)
2249 (define-key org-goto-map [(?q)] 'org-goto-quit)
2250 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2251 (define-key org-goto-map "\C-i" 'org-cycle)
2252 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2253 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2254 (define-key org-goto-map "n" 'outline-next-visible-heading)
2255 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2256 (define-key org-goto-map "f" 'outline-forward-same-level)
2257 (define-key org-goto-map "b" 'outline-backward-same-level)
2258 (define-key org-goto-map "u" 'outline-up-heading)
2259 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2260 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2261 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2262 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2263 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2264 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2265 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2266
2267 (defconst org-goto-help
2268 "Select a location to jump to, press RET
2269 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2270
2271 (defun org-goto ()
2272 "Go to a different location of the document, keeping current visibility.
2273
2274 When you want to go to a different location in a document, the fastest way
2275 is often to fold the entire buffer and then dive into the tree. This
2276 method has the disadvantage, that the previous location will be folded,
2277 which may not be what you want.
2278
2279 This command works around this by showing a copy of the current buffer in
2280 overview mode. You can dive into the tree in that copy, to find the
2281 location you want to reach. When pressing RET, the command returns to the
2282 original buffer in which the visibility is still unchanged. It then jumps
2283 to the new location, making it and the headline hierarchy above it visible."
2284 (interactive)
2285 (let* ((org-goto-start-pos (point))
2286 (selected-point
2287 (org-get-location (current-buffer) org-goto-help)))
2288 (if selected-point
2289 (progn
2290 (goto-char selected-point)
2291 (if (org-invisible-p) (org-show-hierarchy-above)))
2292 (error "Quit"))))
2293
2294 (defun org-get-location (buf help)
2295 "Let the user select a location in the Org-mode buffer BUF.
2296 This function uses a recursive edit. It returns the selected position
2297 or nil."
2298 (let (org-selected-point)
2299 (save-excursion
2300 (save-window-excursion
2301 (delete-other-windows)
2302 (switch-to-buffer (get-buffer-create "*org-goto*"))
2303 (with-output-to-temp-buffer "*Help*"
2304 (princ help))
2305 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2306 (setq buffer-read-only nil)
2307 (erase-buffer)
2308 (insert-buffer-substring buf)
2309 (let ((org-startup-truncated t)
2310 (org-startup-folded t)
2311 (org-startup-with-deadline-check nil))
2312 (org-mode))
2313 (setq buffer-read-only t)
2314 (if (boundp 'org-goto-start-pos)
2315 (goto-char org-goto-start-pos)
2316 (goto-char (point-min)))
2317 (org-beginning-of-line)
2318 (message "Select location and press RET")
2319 ;; now we make sure that during selection, ony very few keys work
2320 ;; and that it is impossible to switch to another window.
2321 (let ((gm (current-global-map))
2322 (overriding-local-map org-goto-map))
2323 (unwind-protect
2324 (progn
2325 (use-global-map org-goto-map)
2326 (recursive-edit))
2327 (use-global-map gm)))))
2328 (kill-buffer "*org-goto*")
2329 org-selected-point))
2330
2331 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2332 (defun org-goto-ret (&optional arg)
2333 "Finish org-goto by going to the new location."
2334 (interactive "P")
2335 (setq org-selected-point (point)
2336 current-prefix-arg arg)
2337 (throw 'exit nil))
2338
2339 (defun org-goto-left ()
2340 "Finish org-goto by going to the new location."
2341 (interactive)
2342 (if (org-on-heading-p)
2343 (progn
2344 (beginning-of-line 1)
2345 (setq org-selected-point (point)
2346 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2347 (throw 'exit nil))
2348 (error "Not on a heading")))
2349
2350 (defun org-goto-right ()
2351 "Finish org-goto by going to the new location."
2352 (interactive)
2353 (if (org-on-heading-p)
2354 (progn
2355 (outline-end-of-subtree)
2356 (or (eobp) (forward-char 1))
2357 (setq org-selected-point (point)
2358 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2359 (throw 'exit nil))
2360 (error "Not on a heading")))
2361
2362 (defun org-goto-quit ()
2363 "Finish org-goto without cursor motion."
2364 (interactive)
2365 (setq org-selected-point nil)
2366 (throw 'exit nil))
2367
2368 ;;; Promotion, Demotion, Inserting new headlines
2369
2370 (defvar org-ignore-region nil
2371 "To temporarily disable the active region.")
2372
2373 (defun org-insert-heading ()
2374 "Insert a new heading with same depth at point."
2375 (interactive)
2376 (let* ((head (save-excursion
2377 (condition-case nil
2378 (org-back-to-heading)
2379 (error (outline-next-heading)))
2380 (prog1 (match-string 0)
2381 (funcall outline-level)))))
2382 (unless (bolp) (newline))
2383 (insert head)
2384 (unless (eolp)
2385 (save-excursion (newline-and-indent)))
2386 (unless (equal (char-before) ?\ )
2387 (insert " "))
2388 (run-hooks 'org-insert-heading-hook)))
2389
2390 (defun org-insert-todo-heading (arg)
2391 "Insert a new heading with the same level and TODO state as current heading.
2392 If the heading has no TODO state, or if the state is DONE, use the first
2393 state (TODO by default). Also with prefix arg, force first state."
2394 (interactive "P")
2395 (org-insert-heading)
2396 (save-excursion
2397 (org-back-to-heading)
2398 (outline-previous-heading)
2399 (looking-at org-todo-line-regexp))
2400 (if (or arg
2401 (not (match-beginning 2))
2402 (equal (match-string 2) org-done-string))
2403 (insert (car org-todo-keywords) " ")
2404 (insert (match-string 2) " ")))
2405
2406 (defun org-promote-subtree ()
2407 "Promote the entire subtree.
2408 See also `org-promote'."
2409 (interactive)
2410 (save-excursion
2411 (org-map-tree 'org-promote)))
2412
2413 (defun org-demote-subtree ()
2414 "Demote the entire subtree. See `org-demote'.
2415 See also `org-promote'."
2416 (interactive)
2417 (save-excursion
2418 (org-map-tree 'org-demote)))
2419
2420 (defun org-do-promote ()
2421 "Promote the current heading higher up the tree.
2422 If the region is active in `transient-mark-mode', promote all headings
2423 in the region."
2424 (interactive)
2425 (save-excursion
2426 (if (org-region-active-p)
2427 (org-map-region 'org-promote (region-beginning) (region-end))
2428 (org-promote)))
2429 (org-fix-position-after-promote))
2430
2431 (defun org-do-demote ()
2432 "Demote the current heading lower down the tree.
2433 If the region is active in `transient-mark-mode', demote all headings
2434 in the region."
2435 (interactive)
2436 (save-excursion
2437 (if (org-region-active-p)
2438 (org-map-region 'org-demote (region-beginning) (region-end))
2439 (org-demote)))
2440 (org-fix-position-after-promote))
2441
2442 (defun org-fix-position-after-promote ()
2443 "Make sure that after pro/demotion cursor position is right."
2444 (and (equal (char-after) ?\ )
2445 (equal (char-before) ?*)
2446 (forward-char 1)))
2447
2448 (defun org-promote ()
2449 "Promote the current heading higher up the tree.
2450 If the region is active in `transient-mark-mode', promote all headings
2451 in the region."
2452 (org-back-to-heading t)
2453 (let* ((level (save-match-data (funcall outline-level)))
2454 (up-head (make-string (1- level) ?*)))
2455 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2456 (replace-match up-head nil t)
2457 (if org-adapt-indentation
2458 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2459
2460 (defun org-demote ()
2461 "Demote the current heading lower down the tree.
2462 If the region is active in `transient-mark-mode', demote all headings
2463 in the region."
2464 (org-back-to-heading t)
2465 (let* ((level (save-match-data (funcall outline-level)))
2466 (down-head (make-string (1+ level) ?*)))
2467 (replace-match down-head nil t)
2468 (if org-adapt-indentation
2469 (org-fixup-indentation "^ " " " "^\\S-"))))
2470
2471 (defun org-map-tree (fun)
2472 "Call FUN for every heading underneath the current one."
2473 (org-back-to-heading)
2474 (let ((level (outline-level)))
2475 (save-excursion
2476 (funcall fun)
2477 (while (and (progn
2478 (outline-next-heading)
2479 (> (funcall outline-level) level))
2480 (not (eobp)))
2481 (funcall fun)))))
2482
2483 (defun org-map-region (fun beg end)
2484 "Call FUN for every heading between BEG and END."
2485 (let ((org-ignore-region t))
2486 (save-excursion
2487 (setq end (copy-marker end))
2488 (goto-char beg)
2489 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2490 (< (point) end))
2491 (funcall fun))
2492 (while (and (progn
2493 (outline-next-heading)
2494 (< (point) end))
2495 (not (eobp)))
2496 (funcall fun)))))
2497
2498 (defun org-fixup-indentation (from to prohibit)
2499 "Change the indentation in the current entry by re-replacing FROM with TO.
2500 However, if the regexp PROHIBIT matches at all, don't do anything.
2501 This is being used to change indentation along with the length of the
2502 heading marker. But if there are any lines which are not indented, nothing
2503 is changed at all."
2504 (save-excursion
2505 (let ((end (save-excursion (outline-next-heading)
2506 (point-marker))))
2507 (unless (save-excursion (re-search-forward prohibit end t))
2508 (while (re-search-forward from end t)
2509 (replace-match to)
2510 (beginning-of-line 2)))
2511 (move-marker end nil))))
2512
2513 ;;; Vertical tree motion, cutting and pasting of subtrees
2514
2515 (defun org-move-subtree-up (&optional arg)
2516 "Move the current subtree up past ARG headlines of the same level."
2517 (interactive "p")
2518 (org-move-subtree-down (- (prefix-numeric-value arg))))
2519
2520 (defun org-move-subtree-down (&optional arg)
2521 "Move the current subtree down past ARG headlines of the same level."
2522 (interactive "p")
2523 (setq arg (prefix-numeric-value arg))
2524 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2525 'outline-get-last-sibling))
2526 (ins-point (make-marker))
2527 (cnt (abs arg))
2528 beg end txt folded)
2529 ;; Select the tree
2530 (org-back-to-heading)
2531 (setq beg (point))
2532 (save-match-data
2533 (save-excursion (outline-end-of-heading)
2534 (setq folded (org-invisible-p)))
2535 (outline-end-of-subtree))
2536 (outline-next-heading)
2537 (setq end (point))
2538 ;; Find insertion point, with error handling
2539 (goto-char beg)
2540 (while (> cnt 0)
2541 (or (and (funcall movfunc) (looking-at outline-regexp))
2542 (progn (goto-char beg)
2543 (error "Cannot move past superior level or buffer limit")))
2544 (setq cnt (1- cnt)))
2545 (if (> arg 0)
2546 ;; Moving forward - still need to move over subtree
2547 (progn (outline-end-of-subtree)
2548 (outline-next-heading)
2549 (if (not (or (looking-at (concat "^" outline-regexp))
2550 (bolp)))
2551 (newline))))
2552 (move-marker ins-point (point))
2553 (setq txt (buffer-substring beg end))
2554 (delete-region beg end)
2555 (insert txt)
2556 (goto-char ins-point)
2557 (if folded (hide-subtree))
2558 (move-marker ins-point nil)))
2559
2560 (defvar org-subtree-clip ""
2561 "Clipboard for cut and paste of subtrees.
2562 This is actually only a copy of the kill, because we use the normal kill
2563 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2564
2565 (defvar org-subtree-clip-folded nil
2566 "Was the last copied subtree folded?
2567 This is used to fold the tree back after pasting.")
2568
2569 (defun org-cut-subtree ()
2570 "Cut the current subtree into the clipboard.
2571 This is a short-hand for marking the subtree and then cutting it."
2572 (interactive)
2573 (org-copy-subtree 'cut))
2574
2575 (defun org-copy-subtree (&optional cut)
2576 "Cut the current subtree into the clipboard.
2577 This is a short-hand for marking the subtree and then copying it.
2578 If CUT is non nil, actually cut the subtree."
2579 (interactive)
2580 (let (beg end folded)
2581 (org-back-to-heading)
2582 (setq beg (point))
2583 (save-match-data
2584 (save-excursion (outline-end-of-heading)
2585 (setq folded (org-invisible-p)))
2586 (outline-end-of-subtree))
2587 (if (equal (char-after) ?\n) (forward-char 1))
2588 (setq end (point))
2589 (goto-char beg)
2590 (when (> end beg)
2591 (setq org-subtree-clip-folded folded)
2592 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2593 (setq org-subtree-clip (current-kill 0))
2594 (message "%s: Subtree with %d characters"
2595 (if cut "Cut" "Copied")
2596 (length org-subtree-clip)))))
2597
2598 (defun org-paste-subtree (&optional level tree)
2599 "Paste the clipboard as a subtree, with modification of headline level.
2600 The entire subtree is promoted or demoted in order to match a new headline
2601 level. By default, the new level is derived from the visible headings
2602 before and after the insertion point, and taken to be the inferior headline
2603 level of the two. So if the previous visible heading is level 3 and the
2604 next is level 4 (or vice versa), level 4 will be used for insertion.
2605 This makes sure that the subtree remains an independent subtree and does
2606 not swallow low level entries.
2607
2608 You can also force a different level, either by using a numeric prefix
2609 argument, or by inserting the heading marker by hand. For example, if the
2610 cursor is after \"*****\", then the tree will be shifted to level 5.
2611
2612 If you want to insert the tree as is, just use \\[yank].
2613
2614 If optional TREE is given, use this text instead of the kill ring."
2615 (interactive "P")
2616 (unless (org-kill-is-subtree-p tree)
2617 (error
2618 (substitute-command-keys
2619 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2620 (let* ((txt (or tree (current-kill 0)))
2621 (^re (concat "^\\(" outline-regexp "\\)"))
2622 (re (concat "\\(" outline-regexp "\\)"))
2623 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2624
2625 (old-level (if (string-match ^re txt)
2626 (- (match-end 0) (match-beginning 0))
2627 -1))
2628 (force-level (cond (level (prefix-numeric-value level))
2629 ((string-match
2630 ^re_ (buffer-substring (point-at-bol) (point)))
2631 (- (match-end 0) (match-beginning 0)))
2632 (t nil)))
2633 (previous-level (save-excursion
2634 (condition-case nil
2635 (progn
2636 (outline-previous-visible-heading 1)
2637 (if (looking-at re)
2638 (- (match-end 0) (match-beginning 0))
2639 1))
2640 (error 1))))
2641 (next-level (save-excursion
2642 (condition-case nil
2643 (progn
2644 (outline-next-visible-heading 1)
2645 (if (looking-at re)
2646 (- (match-end 0) (match-beginning 0))
2647 1))
2648 (error 1))))
2649 (new-level (or force-level (max previous-level next-level)))
2650 (shift (if (or (= old-level -1)
2651 (= new-level -1)
2652 (= old-level new-level))
2653 0
2654 (- new-level old-level)))
2655 (shift1 shift)
2656 (delta (if (> shift 0) -1 1))
2657 (func (if (> shift 0) 'org-demote 'org-promote))
2658 beg end)
2659 ;; Remove the forces level indicator
2660 (if force-level
2661 (delete-region (point-at-bol) (point)))
2662 ;; Make sure we start at the beginning of an empty line
2663 (if (not (bolp)) (insert "\n"))
2664 (if (not (looking-at "[ \t]*$"))
2665 (progn (insert "\n") (backward-char 1)))
2666 ;; Paste
2667 (setq beg (point))
2668 (insert txt)
2669 (setq end (point))
2670 (goto-char beg)
2671 ;; Shift if necessary
2672 (if (= shift 0)
2673 (message "Pasted at level %d, without shift" new-level)
2674 (save-restriction
2675 (narrow-to-region beg end)
2676 (while (not (= shift 0))
2677 (org-map-region func (point-min) (point-max))
2678 (setq shift (+ delta shift)))
2679 (goto-char (point-min))
2680 (message "Pasted at level %d, with shift by %d levels"
2681 new-level shift1)))
2682 (if (and (eq org-subtree-clip (current-kill 0))
2683 org-subtree-clip-folded)
2684 ;; The tree was folded before it was killed/copied
2685 (hide-subtree))))
2686
2687 (defun org-kill-is-subtree-p (&optional txt)
2688 "Check if the current kill is an outline subtree, or a set of trees.
2689 Returns nil if kill does not start with a headline, or if the first
2690 headline level is not the largest headline level in the tree.
2691 So this will actually accept several entries of equal levels as well,
2692 which is OK for `org-paste-subtree'.
2693 If optional TXT is given, check this string instead of the current kill."
2694 (let* ((kill (or txt (current-kill 0) ""))
2695 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2696 (- (match-end 0) (match-beginning 0))))
2697 (re (concat "^" outline-regexp))
2698 (start 1))
2699 (if (not start-level)
2700 nil ;; does not even start with a heading
2701 (catch 'exit
2702 (while (setq start (string-match re kill (1+ start)))
2703 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2704 (throw 'exit nil)))
2705 t))))
2706
2707 (defun org-archive-subtree ()
2708 "Move the current subtree to the archive.
2709 The archive can be a certain top-level heading in the current file, or in
2710 a different file. The tree will be moved to that location, the subtree
2711 heading be marked DONE, and the current time will be added."
2712 (interactive)
2713 ;; Save all relevant TODO keyword-relatex variables
2714 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2715 (tr-org-todo-keywords org-todo-keywords)
2716 (tr-org-todo-interpretation org-todo-interpretation)
2717 (tr-org-done-string org-done-string)
2718 (tr-org-todo-regexp org-todo-regexp)
2719 (tr-org-todo-line-regexp org-todo-line-regexp)
2720 (this-buffer (current-buffer))
2721 file heading buffer level newfile-p)
2722 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2723 (progn
2724 (setq file (format (match-string 1 org-archive-location)
2725 (file-name-nondirectory (buffer-file-name)))
2726 heading (match-string 2 org-archive-location)))
2727 (error "Invalid `org-archive-location'"))
2728 (if (> (length file) 0)
2729 (setq newfile-p (not (file-exists-p file))
2730 buffer (find-file-noselect file))
2731 (setq buffer (current-buffer)))
2732 (unless buffer
2733 (error "Cannot access file \"%s\"" file))
2734 (if (and (> (length heading) 0)
2735 (string-match "^\\*+" heading))
2736 (setq level (match-end 0))
2737 (setq heading nil level 0))
2738 (save-excursion
2739 ;; We first only copy, in case something goes wrong
2740 ;; we need to protect this-command, to avoid kill-region sets it,
2741 ;; which would lead to duplication of subtrees
2742 (let (this-command) (org-copy-subtree))
2743 (set-buffer buffer)
2744 ;; Enforce org-mode for the archive buffer
2745 (if (not (eq major-mode 'org-mode))
2746 ;; Force the mode for future visits.
2747 (let ((org-insert-mode-line-in-empty-file t))
2748 (call-interactively 'org-mode)))
2749 (when newfile-p
2750 (goto-char (point-max))
2751 (insert (format "\nArchived entries from file %s\n\n"
2752 (buffer-file-name this-buffer))))
2753 ;; Force the TODO keywords of the original buffer
2754 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2755 (org-todo-keywords tr-org-todo-keywords)
2756 (org-todo-interpretation tr-org-todo-interpretation)
2757 (org-done-string tr-org-done-string)
2758 (org-todo-regexp tr-org-todo-regexp)
2759 (org-todo-line-regexp tr-org-todo-line-regexp))
2760 (goto-char (point-min))
2761 (if heading
2762 (progn
2763 (if (re-search-forward
2764 (concat "\\(^\\|\r\\)"
2765 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2766 nil t)
2767 (goto-char (match-end 0))
2768 ;; Heading not found, just insert it at the end
2769 (goto-char (point-max))
2770 (or (bolp) (insert "\n"))
2771 (insert "\n" heading "\n")
2772 (end-of-line 0))
2773 ;; Make the heading visible, and the following as well
2774 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2775 (if (re-search-forward
2776 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2777 nil t)
2778 (progn (goto-char (match-beginning 0)) (insert "\n")
2779 (beginning-of-line 0))
2780 (goto-char (point-max)) (insert "\n")))
2781 (goto-char (point-max)) (insert "\n"))
2782 ;; Paste
2783 (org-paste-subtree (1+ level))
2784 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2785 (if org-archive-mark-done
2786 (org-todo (length org-todo-keywords)))
2787 ;; Move cursor to right after the TODO keyword
2788 (when org-archive-stamp-time
2789 (beginning-of-line 1)
2790 (looking-at org-todo-line-regexp)
2791 (goto-char (or (match-end 2) (match-beginning 3)))
2792 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2793 (current-time))
2794 ")"))
2795 ;; Save the buffer, if it is not the same buffer.
2796 (if (not (eq this-buffer buffer)) (save-buffer))))
2797 ;; Here we are back in the original buffer. Everything seems to have
2798 ;; worked. So now cut the tree and finish up.
2799 (let (this-command) (org-cut-subtree))
2800 (if (looking-at "[ \t]*$") (kill-line))
2801 (message "Subtree archived %s"
2802 (if (eq this-buffer buffer)
2803 (concat "under heading: " heading)
2804 (concat "in file: " (abbreviate-file-name file))))))
2805
2806 ;;; Completion
2807
2808 (defun org-complete (&optional arg)
2809 "Perform completion on word at point.
2810 At the beginning of a headline, this completes TODO keywords as given in
2811 `org-todo-keywords'.
2812 If the current word is preceded by a backslash, completes the TeX symbols
2813 that are supported for HTML support.
2814 If the current word is preceded by \"#+\", completes special words for
2815 setting file options.
2816 At all other locations, this simply calls `ispell-complete-word'."
2817 (interactive "P")
2818 (catch 'exit
2819 (let* ((end (point))
2820 (beg (save-excursion
2821 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2822 (skip-chars-backward "a-zA-Z0-9_:$")
2823 (point)))
2824 (texp (equal (char-before beg) ?\\))
2825 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2826 beg)
2827 "#+"))
2828 (pattern (buffer-substring-no-properties beg end))
2829 (completion-ignore-case opt)
2830 (type nil)
2831 (table (cond
2832 (opt
2833 (setq type :opt)
2834 (mapcar (lambda (x)
2835 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2836 (cons (match-string 2 x) (match-string 1 x)))
2837 (org-split-string (org-get-current-options) "\n")))
2838 (texp
2839 (setq type :tex)
2840 org-html-entities)
2841 ((string-match "\\`\\*+[ \t]*\\'"
2842 (buffer-substring (point-at-bol) beg))
2843 (setq type :todo)
2844 (mapcar 'list org-todo-keywords))
2845 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2846 (completion (try-completion pattern table)))
2847 (cond ((eq completion t)
2848 (if (equal type :opt)
2849 (insert (substring (cdr (assoc (upcase pattern) table))
2850 (length pattern)))))
2851 ((null completion)
2852 (message "Can't find completion for \"%s\"" pattern)
2853 (ding))
2854 ((not (string= pattern completion))
2855 (delete-region beg end)
2856 (if (string-match " +$" completion)
2857 (setq completion (replace-match "" t t completion)))
2858 (insert completion)
2859 (if (get-buffer-window "*Completions*")
2860 (delete-window (get-buffer-window "*Completions*")))
2861 (if (and (eq type :todo)
2862 (assoc completion table))
2863 (insert " "))
2864 (if (and (equal type :opt) (assoc completion table))
2865 (message "%s" (substitute-command-keys
2866 "Press \\[org-complete] again to insert example settings"))))
2867 (t
2868 (message "Making completion list...")
2869 (let ((list (sort (all-completions pattern table) 'string<)))
2870 (with-output-to-temp-buffer "*Completions*"
2871 (display-completion-list list)))
2872 (message "Making completion list...%s" "done"))))))
2873
2874 ;;; Comments, TODO and DEADLINE
2875
2876 (defun org-toggle-comment ()
2877 "Change the COMMENT state of an entry."
2878 (interactive)
2879 (save-excursion
2880 (org-back-to-heading)
2881 (if (looking-at (concat outline-regexp
2882 "\\( +\\<" org-comment-string "\\>\\)"))
2883 (replace-match "" t t nil 1)
2884 (if (looking-at outline-regexp)
2885 (progn
2886 (goto-char (match-end 0))
2887 (insert " " org-comment-string))))))
2888
2889 (defvar org-last-todo-state-is-todo nil
2890 "This is non-nil when the last TODO state change led to a TODO state.
2891 If the last change removed the TODO tag or switched to DONE, then
2892 this is nil.")
2893
2894 (defun org-todo (&optional arg)
2895 "Change the TODO state of an item.
2896 The state of an item is given by a keyword at the start of the heading,
2897 like
2898 *** TODO Write paper
2899 *** DONE Call mom
2900
2901 The different keywords are specified in the variable `org-todo-keywords'. By
2902 default the available states are \"TODO\" and \"DONE\".
2903 So for this example: when the item starts with TODO, it is changed to DONE.
2904 When it starts with DONE, the DONE is removed. And when neither TODO nor
2905 DONE are present, add TODO at the beginning of the heading.
2906
2907 With prefix arg, use completion to determined the new state. With numeric
2908 prefix arg, switch to that state."
2909 (interactive "P")
2910 (save-excursion
2911 (org-back-to-heading)
2912 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2913 (or (looking-at (concat " +" org-todo-regexp " *"))
2914 (looking-at " *"))
2915 (let* ((this (match-string 1))
2916 (completion-ignore-case t)
2917 (member (member this org-todo-keywords))
2918 (tail (cdr member))
2919 (state (cond
2920 ((equal arg '(4))
2921 ;; Read a state with completion
2922 (completing-read "State: " (mapcar (lambda(x) (list x))
2923 org-todo-keywords)
2924 nil t))
2925 (arg
2926 ;; user requests a specific state
2927 (nth (1- (prefix-numeric-value arg))
2928 org-todo-keywords))
2929 ((null member) (car org-todo-keywords))
2930 ((null tail) nil) ;; -> first entry
2931 ((eq org-todo-interpretation 'sequence)
2932 (car tail))
2933 ((memq org-todo-interpretation '(type priority))
2934 (if (eq this-command last-command)
2935 (car tail)
2936 (if (> (length tail) 0) org-done-string nil)))
2937 (t nil)))
2938 (next (if state (concat " " state " ") " ")))
2939 (replace-match next t t)
2940 (setq org-last-todo-state-is-todo
2941 (not (equal state org-done-string)))
2942 (run-hooks 'org-after-todo-state-change-hook)))
2943 ;; Fixup cursor location if close to the keyword
2944 (if (and (outline-on-heading-p)
2945 (not (bolp))
2946 (save-excursion (beginning-of-line 1)
2947 (looking-at org-todo-line-regexp))
2948 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2949 (progn
2950 (goto-char (or (match-end 2) (match-end 1)))
2951 (just-one-space))))
2952
2953 (defun org-show-todo-tree (arg)
2954 "Make a compact tree which shows all headlines marked with TODO.
2955 The tree will show the lines where the regexp matches, and all higher
2956 headlines above the match."
2957 (interactive "P")
2958 (let ((case-fold-search nil)
2959 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2960 (message "%d TODO entries found"
2961 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2962
2963 (defun org-deadline ()
2964 "Insert the DEADLINE: string to make a deadline.
2965 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2966 to modify it to the correct date."
2967 (interactive)
2968 (insert
2969 org-deadline-string " "
2970 (format-time-string (car org-time-stamp-formats)
2971 (org-read-date nil 'to-time)))
2972 (message "%s" (substitute-command-keys
2973 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2974
2975 (defun org-schedule ()
2976 "Insert the SCHEDULED: string to schedule a TODO item.
2977 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2978 to modify it to the correct date."
2979 (interactive)
2980 (insert
2981 org-scheduled-string " "
2982 (format-time-string (car org-time-stamp-formats)
2983 (org-read-date nil 'to-time)))
2984 (message "%s" (substitute-command-keys
2985 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2986
2987
2988 (defun org-occur (regexp &optional callback)
2989 "Make a compact tree which shows all matches of REGEXP.
2990 The tree will show the lines where the regexp matches, and all higher
2991 headlines above the match. It will also show the heading after the match,
2992 to make sure editing the matching entry is easy.
2993 if CALLBACK is non-nil, it is a function which is called to confirm
2994 that the match should indeed be shown."
2995 (interactive "sRegexp: ")
2996 (setq regexp (org-check-occur-regexp regexp))
2997 (let ((cnt 0))
2998 (save-excursion
2999 (goto-char (point-min))
3000 (hide-sublevels 1)
3001 (while (re-search-forward regexp nil t)
3002 (when (or (not callback)
3003 (funcall callback))
3004 (setq cnt (1+ cnt))
3005 (org-show-hierarchy-above))))
3006 (run-hooks 'org-occur-hook)
3007 (if (interactive-p)
3008 (message "%d match(es) for regexp %s" cnt regexp))
3009 cnt))
3010
3011 (defun org-show-hierarchy-above ()
3012 "Make sure point and the headings hierarchy above is visible."
3013 (if (org-on-heading-p t)
3014 (org-flag-heading nil) ; only show the heading
3015 (org-show-hidden-entry)) ; show entire entry
3016 (save-excursion
3017 (and org-show-following-heading
3018 (outline-next-heading)
3019 (org-flag-heading nil))) ; show the next heading
3020 (save-excursion ; show all higher headings
3021 (while (condition-case nil
3022 (progn (org-up-heading-all 1) t)
3023 (error nil))
3024 (org-flag-heading nil))))
3025
3026 ;;; Priorities
3027
3028 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3029 "Regular expression matching the priority indicator.")
3030
3031 (defvar org-remove-priority-next-time nil)
3032
3033 (defun org-priority-up ()
3034 "Increase the priority of the current item."
3035 (interactive)
3036 (org-priority 'up))
3037
3038 (defun org-priority-down ()
3039 "Decrease the priority of the current item."
3040 (interactive)
3041 (org-priority 'down))
3042
3043 (defun org-priority (&optional action)
3044 "Change the priority of an item by ARG.
3045 ACTION can be set, up, or down."
3046 (interactive)
3047 (setq action (or action 'set))
3048 (let (current new news have remove)
3049 (save-excursion
3050 (org-back-to-heading)
3051 (if (looking-at org-priority-regexp)
3052 (setq current (string-to-char (match-string 2))
3053 have t)
3054 (setq current org-default-priority))
3055 (cond
3056 ((eq action 'set)
3057 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3058 (setq new (read-char-exclusive))
3059 (cond ((equal new ?\ ) (setq remove t))
3060 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3061 (error "Priority must be between `%c' and `%c'"
3062 ?A org-lowest-priority))))
3063 ((eq action 'up)
3064 (setq new (1- current)))
3065 ((eq action 'down)
3066 (setq new (1+ current)))
3067 (t (error "Invalid action")))
3068 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3069 (setq news (format "%c" new))
3070 (if have
3071 (if remove
3072 (replace-match "" t t nil 1)
3073 (replace-match news t t nil 2))
3074 (if remove
3075 (error "No priority cookie found in line")
3076 (looking-at org-todo-line-regexp)
3077 (if (match-end 2)
3078 (progn
3079 (goto-char (match-end 2))
3080 (insert " [#" news "]"))
3081 (goto-char (match-beginning 3))
3082 (insert "[#" news "] ")))))
3083 (if remove
3084 (message "Priority removed")
3085 (message "Priority of current item set to %s" news))))
3086
3087
3088 (defun org-get-priority (s)
3089 "Find priority cookie and return priority."
3090 (save-match-data
3091 (if (not (string-match org-priority-regexp s))
3092 (* 1000 (- org-lowest-priority org-default-priority))
3093 (* 1000 (- org-lowest-priority
3094 (string-to-char (match-string 2 s)))))))
3095
3096 ;;; Timestamps
3097
3098 (defvar org-last-changed-timestamp nil)
3099
3100 (defun org-time-stamp (arg)
3101 "Prompt for a date/time and insert a time stamp.
3102 If the user specifies a time like HH:MM, or if this command is called
3103 with a prefix argument, the time stamp will contain date and time.
3104 Otherwise, only the date will be included. All parts of a date not
3105 specified by the user will be filled in from the current date/time.
3106 So if you press just return without typing anything, the time stamp
3107 will represent the current date/time. If there is already a timestamp
3108 at the cursor, it will be modified."
3109 (interactive "P")
3110 (let ((fmt (if arg (cdr org-time-stamp-formats)
3111 (car org-time-stamp-formats)))
3112 (org-time-was-given nil)
3113 time)
3114 (cond
3115 ((and (org-at-timestamp-p)
3116 (eq last-command 'org-time-stamp)
3117 (eq this-command 'org-time-stamp))
3118 (insert "--")
3119 (setq time (let ((this-command this-command))
3120 (org-read-date arg 'totime)))
3121 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3122 (insert (format-time-string fmt time)))
3123 ((org-at-timestamp-p)
3124 (setq time (let ((this-command this-command))
3125 (org-read-date arg 'totime)))
3126 (and (org-at-timestamp-p) (replace-match
3127 (setq org-last-changed-timestamp
3128 (format-time-string fmt time))
3129 t t))
3130 (message "Timestamp updated"))
3131 (t
3132 (setq time (let ((this-command this-command))
3133 (org-read-date arg 'totime)))
3134 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3135 (insert (format-time-string fmt time))))))
3136
3137 (defun org-time-stamp-inactive (&optional arg)
3138 "Insert an inactive time stamp.
3139 An inactive time stamp is enclosed in square brackets instead of angle
3140 brackets. It is inactive in the sense that it does not trigger agenda entries,
3141 does not link to the calendar and cannot be changed with the S-cursor keys."
3142 (interactive "P")
3143 (let ((fmt (if arg (cdr org-time-stamp-formats)
3144 (car org-time-stamp-formats)))
3145 (org-time-was-given nil)
3146 time)
3147 (setq time (org-read-date arg 'totime))
3148 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3149 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3150 (insert (format-time-string fmt time))))
3151
3152 ;;; FIXME: Make the function take "Fri" as "next friday"
3153 (defun org-read-date (&optional with-time to-time)
3154 "Read a date and make things smooth for the user.
3155 The prompt will suggest to enter an ISO date, but you can also enter anything
3156 which will at least partially be understood by `parse-time-string'.
3157 Unrecognized parts of the date will default to the current day, month ,year,
3158 hour and minute. For example,
3159 3-2-5 --> 2003-02-05
3160 feb 15 --> currentyear-02-15
3161 sep 12 9 --> 2009-09-12
3162 12:45 --> today 12:45
3163 22 sept 0:34 --> currentyear-09-22 0:34
3164 12 --> currentyear-currentmonth-12
3165 etc.
3166 The function understands only English month and weekday abbreviations,
3167 but this can be configured with the variables `parse-time-months' and
3168 `parse-time-weekdays'.
3169
3170 While prompting, a calendar is popped up - you can also select the
3171 date with the mouse (button 1). The calendar shows a period of three
3172 month. To scroll it to other months, use the keys `>' and `<'.
3173 If you don't like the calendar, turn it off with
3174 \(setq org-popup-calendar-for-date-prompt nil).
3175
3176 With optional argument TO-TIME, the date will immediately be converted
3177 to an internal time.
3178 With an optional argument WITH-TIME, the prompt will suggest to also
3179 insert a time. Note that when WITH-TIME is not set, you can still
3180 enter a time, and this function will inform the calling routine about
3181 this change. The calling routine may then choose to change the format
3182 used to insert the time stamp into the buffer to include the time."
3183 (let* ((default-time
3184 ;; Default time is either today, or, when entering a range,
3185 ;; the range start.
3186 (if (save-excursion
3187 (re-search-backward
3188 (concat org-ts-regexp "--\\=")
3189 (- (point) 20) t))
3190 (apply
3191 'encode-time
3192 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3193 (parse-time-string (match-string 1))))
3194 (current-time)))
3195 (calendar-move-hook nil)
3196 (view-diary-entries-initially nil)
3197 (timestr (format-time-string
3198 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3199 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3200 ans ans1 ans2
3201 second minute hour day month year tl)
3202
3203 (if org-popup-calendar-for-date-prompt
3204 ;; Also show a calendar for date selection
3205 ;; Copied (with modifications) from planner.el by John Wiegley
3206 (save-excursion
3207 (save-window-excursion
3208 (calendar)
3209 (calendar-forward-day (- (time-to-days default-time)
3210 (calendar-absolute-from-gregorian
3211 (calendar-current-date))))
3212 (let* ((old-map (current-local-map))
3213 (map (copy-keymap calendar-mode-map))
3214 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3215 (define-key map (kbd "RET") 'org-calendar-select)
3216 (define-key map (if org-xemacs-p [button1] [mouse-1])
3217 'org-calendar-select)
3218 (define-key minibuffer-local-map [(meta shift left)]
3219 (lambda () (interactive)
3220 (org-eval-in-calendar '(calendar-backward-month 1))))
3221 (define-key minibuffer-local-map [(meta shift right)]
3222 (lambda () (interactive)
3223 (org-eval-in-calendar '(calendar-forward-month 1))))
3224 (define-key minibuffer-local-map [(shift up)]
3225 (lambda () (interactive)
3226 (org-eval-in-calendar '(calendar-backward-week 1))))
3227 (define-key minibuffer-local-map [(shift down)]
3228 (lambda () (interactive)
3229 (org-eval-in-calendar '(calendar-forward-week 1))))
3230 (define-key minibuffer-local-map [(shift left)]
3231 (lambda () (interactive)
3232 (org-eval-in-calendar '(calendar-backward-day 1))))
3233 (define-key minibuffer-local-map [(shift right)]
3234 (lambda () (interactive)
3235 (org-eval-in-calendar '(calendar-forward-day 1))))
3236 (define-key minibuffer-local-map ">"
3237 (lambda () (interactive)
3238 (org-eval-in-calendar '(scroll-calendar-left 1))))
3239 (define-key minibuffer-local-map "<"
3240 (lambda () (interactive)
3241 (org-eval-in-calendar '(scroll-calendar-right 1))))
3242 (unwind-protect
3243 (progn
3244 (use-local-map map)
3245 (setq ans (read-string prompt "" nil nil))
3246 (setq ans (or ans1 ans2 ans)))
3247 (use-local-map old-map)))))
3248 ;; Naked prompt only
3249 (setq ans (read-string prompt "" nil timestr)))
3250
3251 (if (string-match
3252 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3253 (progn
3254 (setq year (if (match-end 2)
3255 (string-to-number (match-string 2 ans))
3256 (string-to-number (format-time-string "%Y")))
3257 month (string-to-number (match-string 3 ans))
3258 day (string-to-number (match-string 4 ans)))
3259 (if (< year 100) (setq year (+ 2000 year)))
3260 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3261 t t ans))))
3262 (setq tl (parse-time-string ans)
3263 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3264 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3265 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3266 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3267 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3268 second (or (nth 0 tl) 0))
3269 (if (and (boundp 'org-time-was-given)
3270 (nth 2 tl))
3271 (setq org-time-was-given t))
3272 (if (< year 100) (setq year (+ 2000 year)))
3273 (if to-time
3274 (encode-time second minute hour day month year)
3275 (if (or (nth 1 tl) (nth 2 tl))
3276 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3277 (format "%04d-%02d-%02d" year month day)))))
3278
3279 (defun org-eval-in-calendar (form)
3280 "Eval FORM in the calendar window and return to current window.
3281 Also, store the cursor date in variable ans2."
3282 (let ((sw (selected-window)))
3283 (select-window (get-buffer-window "*Calendar*"))
3284 (eval form)
3285 (when (calendar-cursor-to-date)
3286 (let* ((date (calendar-cursor-to-date))
3287 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3288 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3289 (select-window sw)))
3290
3291 (defun org-calendar-select ()
3292 "Return to `org-read-date' with the date currently selected.
3293 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3294 (interactive)
3295 (when (calendar-cursor-to-date)
3296 (let* ((date (calendar-cursor-to-date))
3297 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3298 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3299 (if (active-minibuffer-window) (exit-minibuffer))))
3300
3301 (defun org-check-deadlines (ndays)
3302 "Check if there are any deadlines due or past due.
3303 A deadline is considered due if it happens within `org-deadline-warning-days'
3304 days from today's date. If the deadline appears in an entry marked DONE,
3305 it is not shown. The prefix arg NDAYS can be used to test that many
3306 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3307 (interactive "P")
3308 (let* ((org-warn-days
3309 (cond
3310 ((equal ndays '(4)) 100000)
3311 (ndays (prefix-numeric-value ndays))
3312 (t org-deadline-warning-days)))
3313 (case-fold-search nil)
3314 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3315 (callback
3316 (lambda ()
3317 (and (let ((d1 (time-to-days (current-time)))
3318 (d2 (time-to-days
3319 (org-time-string-to-time (match-string 1)))))
3320 (< (- d2 d1) org-warn-days))
3321 (not (org-entry-is-done-p))))))
3322 (message "%d deadlines past-due or due within %d days"
3323 (org-occur regexp callback)
3324 org-warn-days)))
3325
3326 (defun org-evaluate-time-range (&optional to-buffer)
3327 "Evaluate a time range by computing the difference between start and end.
3328 Normally the result is just printed in the echo area, but with prefix arg
3329 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3330 If the time range is actually in a table, the result is inserted into the
3331 next column.
3332 For time difference computation, a year is assumed to be exactly 365
3333 days in order to avoid rounding problems."
3334 (interactive "P")
3335 (save-excursion
3336 (unless (org-at-date-range-p)
3337 (goto-char (point-at-bol))
3338 (re-search-forward org-tr-regexp (point-at-eol) t))
3339 (if (not (org-at-date-range-p))
3340 (error "Not at a time-stamp range, and none found in current line")))
3341 (let* ((ts1 (match-string 1))
3342 (ts2 (match-string 2))
3343 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3344 (match-end (match-end 0))
3345 (time1 (org-time-string-to-time ts1))
3346 (time2 (org-time-string-to-time ts2))
3347 (t1 (time-to-seconds time1))
3348 (t2 (time-to-seconds time2))
3349 (diff (abs (- t2 t1)))
3350 (negative (< (- t2 t1) 0))
3351 ;; (ys (floor (* 365 24 60 60)))
3352 (ds (* 24 60 60))
3353 (hs (* 60 60))
3354 (fy "%dy %dd %02d:%02d")
3355 (fy1 "%dy %dd")
3356 (fd "%dd %02d:%02d")
3357 (fd1 "%dd")
3358 (fh "%02d:%02d")
3359 y d h m align)
3360 ;; FIXME: Should I re-introduce years, make year refer to same date?
3361 ;; This would be the only useful way to have years, actually.
3362 (if havetime
3363 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3364 y 0
3365 d (floor (/ diff ds)) diff (mod diff ds)
3366 h (floor (/ diff hs)) diff (mod diff hs)
3367 m (floor (/ diff 60)))
3368 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3369 y 0
3370 d (floor (+ (/ diff ds) 0.5))
3371 h 0 m 0))
3372 (if (not to-buffer)
3373 (message (org-make-tdiff-string y d h m))
3374 (when (org-at-table-p)
3375 (goto-char match-end)
3376 (setq align t)
3377 (and (looking-at " *|") (goto-char (match-end 0))))
3378 (if (looking-at
3379 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3380 (replace-match ""))
3381 (if negative (insert " -"))
3382 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3383 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3384 (insert " " (format fh h m))))
3385 (if align (org-table-align))
3386 (message "Time difference inserted"))))
3387
3388 (defun org-make-tdiff-string (y d h m)
3389 (let ((fmt "")
3390 (l nil))
3391 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3392 l (push y l)))
3393 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3394 l (push d l)))
3395 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3396 l (push h l)))
3397 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3398 l (push m l)))
3399 (apply 'format fmt (nreverse l))))
3400
3401 (defun org-time-string-to-time (s)
3402 (apply 'encode-time (org-parse-time-string s)))
3403
3404 (defun org-parse-time-string (s &optional nodefault)
3405 "Parse the standard Org-mode time string.
3406 This should be a lot faster than the normal `parse-time-string'.
3407 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3408 hour and minute fields will be nil if not given."
3409 (if (string-match org-ts-regexp1 s)
3410 (list 0
3411 (if (or (match-beginning 8) (not nodefault))
3412 (string-to-number (or (match-string 8 s) "0")))
3413 (if (or (match-beginning 7) (not nodefault))
3414 (string-to-number (or (match-string 7 s) "0")))
3415 (string-to-number (match-string 4 s))
3416 (string-to-number (match-string 3 s))
3417 (string-to-number (match-string 2 s))
3418 nil nil nil)
3419 (make-list 9 0)))
3420
3421 (defun org-timestamp-up (&optional arg)
3422 "Increase the date item at the cursor by one.
3423 If the cursor is on the year, change the year. If it is on the month or
3424 the day, change that.
3425 With prefix ARG, change by that many units."
3426 (interactive "p")
3427 (org-timestamp-change (prefix-numeric-value arg)))
3428
3429 (defun org-timestamp-down (&optional arg)
3430 "Decrease the date item at the cursor by one.
3431 If the cursor is on the year, change the year. If it is on the month or
3432 the day, change that.
3433 With prefix ARG, change by that many units."
3434 (interactive "p")
3435 (org-timestamp-change (- (prefix-numeric-value arg))))
3436
3437 (defun org-timestamp-up-day (&optional arg)
3438 "Increase the date in the time stamp by one day.
3439 With prefix ARG, change that many days."
3440 (interactive "p")
3441 (org-timestamp-change (prefix-numeric-value arg) 'day))
3442
3443 (defun org-timestamp-down-day (&optional arg)
3444 "Decrease the date in the time stamp by one day.
3445 With prefix ARG, change that many days."
3446 (interactive "p")
3447 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3448
3449 (defsubst org-pos-in-match-range (pos n)
3450 (and (match-beginning n)
3451 (<= (match-beginning n) pos)
3452 (>= (match-end n) pos)))
3453
3454 (defun org-at-timestamp-p ()
3455 "Determine if the cursor is or at a timestamp."
3456 (interactive)
3457 (let* ((tsr org-ts-regexp2)
3458 (pos (point))
3459 (ans (or (looking-at tsr)
3460 (save-excursion
3461 (skip-chars-backward "^<\n\r\t")
3462 (if (> (point) 1) (backward-char 1))
3463 (and (looking-at tsr)
3464 (> (- (match-end 0) pos) -1))))))
3465 (and (boundp 'org-ts-what)
3466 (setq org-ts-what
3467 (cond
3468 ((org-pos-in-match-range pos 2) 'year)
3469 ((org-pos-in-match-range pos 3) 'month)
3470 ((org-pos-in-match-range pos 7) 'hour)
3471 ((org-pos-in-match-range pos 8) 'minute)
3472 ((or (org-pos-in-match-range pos 4)
3473 (org-pos-in-match-range pos 5)) 'day)
3474 (t 'day))))
3475 ans))
3476
3477 (defun org-timestamp-change (n &optional what)
3478 "Change the date in the time stamp at point.
3479 The date will be changed by N times WHAT. WHAT can be `day', `month',
3480 `year', `minute', `second'. If WHAT is not given, the cursor position
3481 in the timestamp determines what will be changed."
3482 (let ((fmt (car org-time-stamp-formats))
3483 org-ts-what
3484 (pos (point))
3485 ts time time0)
3486 (if (not (org-at-timestamp-p))
3487 (error "Not at a timestamp"))
3488 (setq org-ts-what (or what org-ts-what))
3489 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3490 (- (match-end 0) (match-beginning 0))))
3491 1)
3492 (cdr org-time-stamp-formats)
3493 (car org-time-stamp-formats)))
3494 (setq ts (match-string 0))
3495 (replace-match "")
3496 (setq time0 (org-parse-time-string ts))
3497 (setq time
3498 (apply 'encode-time
3499 (append
3500 (list (or (car time0) 0))
3501 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3502 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3503 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3504 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3505 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3506 (nthcdr 6 time0))))
3507 (if (eq what 'calendar)
3508 (let ((cal-date
3509 (save-excursion
3510 (save-match-data
3511 (set-buffer "*Calendar*")
3512 (calendar-cursor-to-date)))))
3513 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3514 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3515 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3516 (setcar time0 (or (car time0) 0))
3517 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3518 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3519 (setq time (apply 'encode-time time0))))
3520 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3521 (goto-char pos)
3522 ;; Try to recenter the calendar window, if any
3523 (if (and org-calendar-follow-timestamp-change
3524 (get-buffer-window "*Calendar*" t)
3525 (memq org-ts-what '(day month year)))
3526 (org-recenter-calendar (time-to-days time)))))
3527
3528 (defun org-recenter-calendar (date)
3529 "If the calendar is visible, recenter it to DATE."
3530 (let* ((win (selected-window))
3531 (cwin (get-buffer-window "*Calendar*" t))
3532 (calendar-move-hook nil))
3533 (when cwin
3534 (select-window cwin)
3535 (calendar-goto-date (if (listp date) date
3536 (calendar-gregorian-from-absolute date)))
3537 (select-window win))))
3538
3539 (defun org-goto-calendar (&optional arg)
3540 "Go to the Emacs calendar at the current date.
3541 If there is a time stamp in the current line, go to that date.
3542 A prefix ARG can be used force the current date."
3543 (interactive "P")
3544 (let ((tsr org-ts-regexp) diff
3545 (calendar-move-hook nil)
3546 (view-diary-entries-initially nil))
3547 (if (or (org-at-timestamp-p)
3548 (save-excursion
3549 (beginning-of-line 1)
3550 (looking-at (concat ".*" tsr))))
3551 (let ((d1 (time-to-days (current-time)))
3552 (d2 (time-to-days
3553 (org-time-string-to-time (match-string 1)))))
3554 (setq diff (- d2 d1))))
3555 (calendar)
3556 (calendar-goto-today)
3557 (if (and diff (not arg)) (calendar-forward-day diff))))
3558
3559 (defun org-date-from-calendar ()
3560 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3561 If there is already a time stamp at the cursor position, update it."
3562 (interactive)
3563 (org-timestamp-change 0 'calendar))
3564
3565 ;;; Agenda, and Diary Integration
3566
3567 ;;; Define the mode
3568
3569 (defvar org-agenda-mode-map (make-sparse-keymap)
3570 "Keymap for `org-agenda-mode'.")
3571
3572 (defvar org-agenda-menu)
3573 (defvar org-agenda-follow-mode nil)
3574 (defvar org-agenda-buffer-name "*Org Agenda*")
3575 (defvar org-agenda-redo-command nil)
3576 (defvar org-agenda-mode-hook nil)
3577
3578 ;;;###autoload
3579 (defun org-agenda-mode ()
3580 "Mode for time-sorted view on action items in Org-mode files.
3581
3582 The following commands are available:
3583
3584 \\{org-agenda-mode-map}"
3585 (interactive)
3586 (kill-all-local-variables)
3587 (setq major-mode 'org-agenda-mode)
3588 (setq mode-name "Org-Agenda")
3589 (use-local-map org-agenda-mode-map)
3590 (easy-menu-add org-agenda-menu)
3591 (if org-startup-truncated (setq truncate-lines t))
3592 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3593 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3594 (setq org-agenda-follow-mode nil)
3595 (easy-menu-change
3596 '("Agenda") "Agenda Files"
3597 (append
3598 (list
3599 ["Edit File List" (customize-variable 'org-agenda-files) t]
3600 "--")
3601 (mapcar 'org-file-menu-entry org-agenda-files)))
3602 (org-agenda-set-mode-name)
3603 (apply
3604 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3605 org-agenda-mode-hook))
3606
3607 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3608 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3609 (define-key org-agenda-mode-map " " 'org-agenda-show)
3610 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3611 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3612 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3613 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3614 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3615 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3616 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3617 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3618 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3619 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
3620 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
3621
3622 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3623 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3624 (while l (define-key org-agenda-mode-map
3625 (int-to-string (pop l)) 'digit-argument)))
3626
3627 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3628 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3629 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3630 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3631 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3632 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3633 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3634 (define-key org-agenda-mode-map "n" 'next-line)
3635 (define-key org-agenda-mode-map "p" 'previous-line)
3636 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3637 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3638 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3639 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3640 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3641 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3642 (eval-after-load "calendar"
3643 '(define-key calendar-mode-map org-calendar-to-agenda-key
3644 'org-calendar-goto-agenda))
3645 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3646 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3647 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3648 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3649 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3650 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3651 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3652 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3653 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3654 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3655 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3656 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
3657 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
3658 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3659 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3660 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
3661 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3662 "Local keymap for agenda entries from Org-mode.")
3663
3664 (define-key org-agenda-keymap
3665 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3666 (define-key org-agenda-keymap
3667 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3668
3669 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3670 '("Agenda"
3671 ("Agenda Files")
3672 "--"
3673 ["Show" org-agenda-show t]
3674 ["Go To (other window)" org-agenda-goto t]
3675 ["Go To (one window)" org-agenda-switch-to t]
3676 ["Follow Mode" org-agenda-follow-mode
3677 :style toggle :selected org-agenda-follow-mode :active t]
3678 "--"
3679 ["Cycle TODO" org-agenda-todo t]
3680 ("Reschedule"
3681 ["Reschedule +1 day" org-agenda-date-later t]
3682 ["Reschedule -1 day" org-agenda-date-earlier t]
3683 "--"
3684 ["Reschedule to ..." org-agenda-date-prompt t])
3685 ("Priority"
3686 ["Set Priority" org-agenda-priority t]
3687 ["Increase Priority" org-agenda-priority-up t]
3688 ["Decrease Priority" org-agenda-priority-down t]
3689 ["Show Priority" org-agenda-show-priority t])
3690 "--"
3691 ["Rebuild buffer" org-agenda-redo t]
3692 ["Goto Today" org-agenda-goto-today t]
3693 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3694 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3695 "--"
3696 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3697 :style radio :selected (equal org-agenda-ndays 1)]
3698 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3699 :style radio :selected (equal org-agenda-ndays 7)]
3700 "--"
3701 ["Include Diary" org-agenda-toggle-diary
3702 :style toggle :selected org-agenda-include-diary :active t]
3703 ["Use Time Grid" org-agenda-toggle-time-grid
3704 :style toggle :selected org-agenda-use-time-grid :active t]
3705 "--"
3706 ["New Diary Entry" org-agenda-diary-entry t]
3707 ("Calendar Commands"
3708 ["Goto Calendar" org-agenda-goto-calendar t]
3709 ["Phases of the Moon" org-agenda-phases-of-moon t]
3710 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3711 ["Holidays" org-agenda-holidays t]
3712 ["Convert" org-agenda-convert-date t])
3713 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
3714 "--"
3715 ["Quit" org-agenda-quit t]
3716 ["Exit and Release Buffers" org-agenda-exit t]
3717 ))
3718
3719 (defvar org-agenda-markers nil
3720 "List of all currently active markers created by `org-agenda'.")
3721 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3722 "Creation time of the last agenda marker.")
3723
3724 (defun org-agenda-new-marker (&optional pos)
3725 "Return a new agenda marker.
3726 Org-mode keeps a list of these markers and resets them when they are
3727 no longer in use."
3728 (let ((m (copy-marker (or pos (point)))))
3729 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3730 (push m org-agenda-markers)
3731 m))
3732
3733 (defun org-agenda-maybe-reset-markers (&optional force)
3734 "Reset markers created by `org-agenda'. But only if they are old enough."
3735 (if (or force
3736 (> (- (time-to-seconds (current-time))
3737 org-agenda-last-marker-time)
3738 5))
3739 (while org-agenda-markers
3740 (move-marker (pop org-agenda-markers) nil))))
3741
3742 (defvar org-agenda-new-buffers nil
3743 "Buffers created to visit agenda files.")
3744
3745 (defun org-get-agenda-file-buffer (file)
3746 "Get a buffer visiting FILE. If the buffer needs to be created, add
3747 it to the list of buffers which might be released later."
3748 (let ((buf (find-buffer-visiting file)))
3749 (if buf
3750 buf ; just return it
3751 ;; Make a new buffer and remember it
3752 (setq buf (find-file-noselect file))
3753 (if buf (push buf org-agenda-new-buffers))
3754 buf)))
3755
3756 (defun org-release-buffers (blist)
3757 "Release all buffers in list, asking the user for confirmation when needed.
3758 When a buffer is unmodified, it is just killed. When modified, it is saved
3759 \(if the user agrees) and then killed."
3760 (let (buf file)
3761 (while (setq buf (pop blist))
3762 (setq file (buffer-file-name buf))
3763 (when (and (buffer-modified-p buf)
3764 file
3765 (y-or-n-p (format "Save file %s? " file)))
3766 (with-current-buffer buf (save-buffer)))
3767 (kill-buffer buf))))
3768
3769 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3770
3771 (defun org-timeline (&optional include-all)
3772 "Show a time-sorted view of the entries in the current org file.
3773 Only entries with a time stamp of today or later will be listed. With
3774 one \\[universal-argument] prefix argument, past entries will also be listed.
3775 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3776 under the current date.
3777 If the buffer contains an active region, only check the region for
3778 dates."
3779 (interactive "P")
3780 (require 'calendar)
3781 (org-agenda-maybe-reset-markers 'force)
3782 (org-compile-prefix-format org-timeline-prefix-format)
3783 (let* ((dopast include-all)
3784 (dotodo (equal include-all '(16)))
3785 (entry (buffer-file-name))
3786 (org-agenda-files (list (buffer-file-name)))
3787 (date (calendar-current-date))
3788 (win (selected-window))
3789 (pos1 (point))
3790 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3791 (end (if (org-region-active-p) (region-end) (point-max)))
3792 (day-numbers (org-get-all-dates beg end 'no-ranges
3793 t)) ; always include today
3794 (today (time-to-days (current-time)))
3795 (org-respect-restriction t)
3796 (past t)
3797 s e rtn d)
3798 (setq org-agenda-redo-command
3799 (list 'progn
3800 (list 'switch-to-buffer-other-window (current-buffer))
3801 (list 'org-timeline (list 'quote include-all))))
3802 (if (not dopast)
3803 ;; Remove past dates from the list of dates.
3804 (setq day-numbers (delq nil (mapcar (lambda(x)
3805 (if (>= x today) x nil))
3806 day-numbers))))
3807 (switch-to-buffer-other-window
3808 (get-buffer-create org-agenda-buffer-name))
3809 (setq buffer-read-only nil)
3810 (erase-buffer)
3811 (org-agenda-mode) (setq buffer-read-only nil)
3812 (while (setq d (pop day-numbers))
3813 (if (and (>= d today)
3814 dopast
3815 past)
3816 (progn
3817 (setq past nil)
3818 (insert (make-string 79 ?-) "\n")))
3819 (setq date (calendar-gregorian-from-absolute d))
3820 (setq s (point))
3821 (if dotodo
3822 (setq rtn (org-agenda-get-day-entries
3823 entry date :todo :timestamp))
3824 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3825 (if (or rtn (equal d today))
3826 (progn
3827 (insert (calendar-day-name date) " "
3828 (number-to-string (extract-calendar-day date)) " "
3829 (calendar-month-name (extract-calendar-month date)) " "
3830 (number-to-string (extract-calendar-year date)) "\n")
3831 (put-text-property s (1- (point)) 'face
3832 'org-link)
3833 (if (equal d today)
3834 (put-text-property s (1- (point)) 'org-today t))
3835 (insert (org-finalize-agenda-entries rtn) "\n")
3836 (put-text-property s (1- (point)) 'day d))))
3837 (goto-char (point-min))
3838 (setq buffer-read-only t)
3839 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3840 (point-min)))
3841 (when (not org-select-timeline-window)
3842 (select-window win)
3843 (goto-char pos1))))
3844
3845 ;;;###autoload
3846 (defun org-agenda (&optional include-all start-day ndays)
3847 "Produce a weekly view from all files in variable `org-agenda-files'.
3848 The view will be for the current week, but from the overview buffer you
3849 will be able to go to other weeks.
3850 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3851 also be shown, under the current date.
3852 START-DAY defaults to TODAY, or to the most recent match for the weekday
3853 given in `org-agenda-start-on-weekday'.
3854 NDAYS defaults to `org-agenda-ndays'."
3855 (interactive "P")
3856 (org-agenda-maybe-reset-markers 'force)
3857 (org-compile-prefix-format org-agenda-prefix-format)
3858 (require 'calendar)
3859 (let* ((org-agenda-start-on-weekday
3860 (if (or (equal ndays 1)
3861 (and (null ndays) (equal 1 org-agenda-ndays)))
3862 nil org-agenda-start-on-weekday))
3863 (files (copy-sequence org-agenda-files))
3864 (win (selected-window))
3865 (today (time-to-days (current-time)))
3866 (sd (or start-day today))
3867 (start (if (or (null org-agenda-start-on-weekday)
3868 (< org-agenda-ndays 7))
3869 sd
3870 (let* ((nt (calendar-day-of-week
3871 (calendar-gregorian-from-absolute sd)))
3872 (n1 org-agenda-start-on-weekday)
3873 (d (- nt n1)))
3874 (- sd (+ (if (< d 0) 7 0) d)))))
3875 (day-numbers (list start))
3876 (inhibit-redisplay t)
3877 s e rtn rtnall file date d start-pos end-pos todayp nd)
3878 (setq org-agenda-redo-command
3879 (list 'org-agenda (list 'quote include-all) start-day ndays))
3880 ;; Make the list of days
3881 (setq ndays (or ndays org-agenda-ndays)
3882 nd ndays)
3883 (while (> ndays 1)
3884 (push (1+ (car day-numbers)) day-numbers)
3885 (setq ndays (1- ndays)))
3886 (setq day-numbers (nreverse day-numbers))
3887 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3888 (progn
3889 (delete-other-windows)
3890 (switch-to-buffer-other-window
3891 (get-buffer-create org-agenda-buffer-name))))
3892 (setq buffer-read-only nil)
3893 (erase-buffer)
3894 (org-agenda-mode) (setq buffer-read-only nil)
3895 (set (make-local-variable 'starting-day) (car day-numbers))
3896 (set (make-local-variable 'include-all-loc) include-all)
3897 (when (and (or include-all org-agenda-include-all-todo)
3898 (member today day-numbers))
3899 (setq files org-agenda-files
3900 rtnall nil)
3901 (while (setq file (pop files))
3902 (catch 'nextfile
3903 (org-check-agenda-file file)
3904 (setq date (calendar-gregorian-from-absolute today)
3905 rtn (org-agenda-get-day-entries
3906 file date :todo))
3907 (setq rtnall (append rtnall rtn))))
3908 (when rtnall
3909 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3910 (add-text-properties (point-min) (1- (point))
3911 (list 'face 'org-link))
3912 (insert (org-finalize-agenda-entries rtnall) "\n")))
3913 (while (setq d (pop day-numbers))
3914 (setq date (calendar-gregorian-from-absolute d)
3915 s (point))
3916 (if (or (setq todayp (= d today))
3917 (and (not start-pos) (= d sd)))
3918 (setq start-pos (point))
3919 (if (and start-pos (not end-pos))
3920 (setq end-pos (point))))
3921 (setq files org-agenda-files
3922 rtnall nil)
3923 (while (setq file (pop files))
3924 (catch 'nextfile
3925 (org-check-agenda-file file)
3926 (setq rtn (org-agenda-get-day-entries file date))
3927 (setq rtnall (append rtnall rtn))))
3928 (if org-agenda-include-diary
3929 (progn
3930 (require 'diary-lib)
3931 (setq rtn (org-get-entries-from-diary date))
3932 (setq rtnall (append rtnall rtn))))
3933 (if (or rtnall org-agenda-show-all-dates)
3934 (progn
3935 (insert (format "%-9s %2d %s %4d\n"
3936 (calendar-day-name date)
3937 (extract-calendar-day date)
3938 (calendar-month-name (extract-calendar-month date))
3939 (extract-calendar-year date)))
3940 (put-text-property s (1- (point)) 'face
3941 'org-link)
3942 (if rtnall (insert
3943 (org-finalize-agenda-entries ;; FIXME: condition needed
3944 (org-agenda-add-time-grid-maybe
3945 rtnall nd todayp))
3946 "\n"))
3947 (put-text-property s (1- (point)) 'day d))))
3948 (goto-char (point-min))
3949 (setq buffer-read-only t)
3950 (if org-fit-agenda-window
3951 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3952 (/ (frame-height) 2)))
3953 (unless (and (pos-visible-in-window-p (point-min))
3954 (pos-visible-in-window-p (point-max)))
3955 (goto-char (1- (point-max)))
3956 (recenter -1)
3957 (if (not (pos-visible-in-window-p (or start-pos 1)))
3958 (progn
3959 (goto-char (or start-pos 1))
3960 (recenter 1))))
3961 (goto-char (or start-pos 1))
3962 (if (not org-select-agenda-window) (select-window win))
3963 (message "")))
3964
3965 (defun org-check-agenda-file (file)
3966 "Make sure FILE exists. If not, ask user what to do."
3967 ;; FIXME: this does not correctly change the menus
3968 ;; Could probably be fixed by explicitly going to the buffer.
3969 (when (not (file-exists-p file))
3970 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3971 file)
3972 (let ((r (downcase (read-char-exclusive))))
3973 (cond
3974 ((equal r ?r)
3975 (org-remove-file file)
3976 (throw 'nextfile t))
3977 (t (error "Abort"))))))
3978
3979 (defun org-agenda-quit ()
3980 "Exit agenda by removing the window or the buffer."
3981 (interactive)
3982 (let ((buf (current-buffer)))
3983 (if (not (one-window-p)) (delete-window))
3984 (kill-buffer buf)
3985 (org-agenda-maybe-reset-markers 'force)))
3986
3987 (defun org-agenda-exit ()
3988 "Exit agenda by removing the window or the buffer.
3989 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3990 Org-mode buffers visited directly by the user will not be touched."
3991 (interactive)
3992 (org-release-buffers org-agenda-new-buffers)
3993 (setq org-agenda-new-buffers nil)
3994 (org-agenda-quit))
3995
3996 (defun org-agenda-redo ()
3997 "Rebuild Agenda."
3998 (interactive)
3999 (eval org-agenda-redo-command))
4000
4001 (defun org-agenda-goto-today ()
4002 "Go to today."
4003 (interactive)
4004 (if (boundp 'starting-day)
4005 (let ((cmd (car org-agenda-redo-command))
4006 (iall (nth 1 org-agenda-redo-command))
4007 (nday (nth 3 org-agenda-redo-command)))
4008 (eval (list cmd iall nil nday)))
4009 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4010 (point-min)))))
4011
4012 (defun org-agenda-later (arg)
4013 "Go forward in time by `org-agenda-ndays' days.
4014 With prefix ARG, go forward that many times `org-agenda-ndays'."
4015 (interactive "p")
4016 (unless (boundp 'starting-day)
4017 (error "Not allowed"))
4018 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4019 (+ starting-day (* arg org-agenda-ndays))))
4020
4021 (defun org-agenda-earlier (arg)
4022 "Go back in time by `org-agenda-ndays' days.
4023 With prefix ARG, go back that many times `org-agenda-ndays'."
4024 (interactive "p")
4025 (unless (boundp 'starting-day)
4026 (error "Not allowed"))
4027 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4028 (- starting-day (* arg org-agenda-ndays))))
4029
4030 (defun org-agenda-week-view ()
4031 "Switch to weekly view for agenda."
4032 (interactive)
4033 (unless (boundp 'starting-day)
4034 (error "Not allowed"))
4035 (setq org-agenda-ndays 7)
4036 (org-agenda include-all-loc
4037 (or (get-text-property (point) 'day)
4038 starting-day))
4039 (org-agenda-set-mode-name)
4040 (message "Switched to week view"))
4041
4042 (defun org-agenda-day-view ()
4043 "Switch to weekly view for agenda."
4044 (interactive)
4045 (unless (boundp 'starting-day)
4046 (error "Not allowed"))
4047 (setq org-agenda-ndays 1)
4048 (org-agenda include-all-loc
4049 (or (get-text-property (point) 'day)
4050 starting-day))
4051 (org-agenda-set-mode-name)
4052 (message "Switched to day view"))
4053
4054 (defun org-agenda-next-date-line (&optional arg)
4055 "Jump to the next line indicating a date in agenda buffer."
4056 (interactive "p")
4057 (beginning-of-line 1)
4058 (if (looking-at "^\\S-") (forward-char 1))
4059 (if (not (re-search-forward "^\\S-" nil t arg))
4060 (progn
4061 (backward-char 1)
4062 (error "No next date after this line in this buffer")))
4063 (goto-char (match-beginning 0)))
4064
4065 (defun org-agenda-previous-date-line (&optional arg)
4066 "Jump to the next line indicating a date in agenda buffer."
4067 (interactive "p")
4068 (beginning-of-line 1)
4069 (if (not (re-search-backward "^\\S-" nil t arg))
4070 (error "No previous date before this line in this buffer")))
4071
4072 ;; Initialize the highlight
4073 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4074 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4075 'face 'highlight)
4076
4077 (defun org-highlight (begin end &optional buffer)
4078 "Highlight a region with overlay."
4079 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4080 org-hl begin end (or buffer (current-buffer))))
4081
4082 (defun org-unhighlight ()
4083 "Detach overlay INDEX."
4084 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4085
4086
4087 (defun org-agenda-follow-mode ()
4088 "Toggle follow mode in an agenda buffer."
4089 (interactive)
4090 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4091 (org-agenda-set-mode-name)
4092 (message "Follow mode is %s"
4093 (if org-agenda-follow-mode "on" "off")))
4094
4095 (defun org-agenda-toggle-diary ()
4096 "Toggle follow mode in an agenda buffer."
4097 (interactive)
4098 (setq org-agenda-include-diary (not org-agenda-include-diary))
4099 (org-agenda-redo)
4100 (org-agenda-set-mode-name)
4101 (message "Diary inclusion turned %s"
4102 (if org-agenda-include-diary "on" "off")))
4103
4104 (defun org-agenda-toggle-time-grid ()
4105 "Toggle follow mode in an agenda buffer."
4106 (interactive)
4107 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4108 (org-agenda-redo)
4109 (org-agenda-set-mode-name)
4110 (message "Time-grid turned %s"
4111 (if org-agenda-use-time-grid "on" "off")))
4112
4113 (defun org-agenda-set-mode-name ()
4114 "Set the mode name to indicate all the small mode settings."
4115 (setq mode-name
4116 (concat "Org-Agenda"
4117 (if (equal org-agenda-ndays 1) " Day" "")
4118 (if (equal org-agenda-ndays 7) " Week" "")
4119 (if org-agenda-follow-mode " Follow" "")
4120 (if org-agenda-include-diary " Diary" "")
4121 (if org-agenda-use-time-grid " Grid" "")))
4122 (force-mode-line-update))
4123
4124 (defun org-agenda-post-command-hook ()
4125 (and (eolp) (not (bolp)) (backward-char 1))
4126 (if (and org-agenda-follow-mode
4127 (get-text-property (point) 'org-marker))
4128 (org-agenda-show)))
4129
4130 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4131
4132 (defun org-get-entries-from-diary (date)
4133 "Get the (Emacs Calendar) diary entries for DATE."
4134 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4135 (diary-display-hook '(fancy-diary-display))
4136 (list-diary-entries-hook
4137 (cons 'org-diary-default-entry list-diary-entries-hook))
4138 (diary-file-name-prefix-function nil) ; turn this feature off
4139 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4140 entries
4141 (org-disable-agenda-to-diary t))
4142 (save-excursion
4143 (save-window-excursion
4144 (list-diary-entries date 1)))
4145 (if (not (get-buffer fancy-diary-buffer))
4146 (setq entries nil)
4147 (with-current-buffer fancy-diary-buffer
4148 (setq buffer-read-only nil)
4149 (if (= (point-max) 1)
4150 ;; No entries
4151 (setq entries nil)
4152 ;; Omit the date and other unnecessary stuff
4153 (org-agenda-cleanup-fancy-diary)
4154 ;; Add prefix to each line and extend the text properties
4155 (if (= (point-max) 1)
4156 (setq entries nil)
4157 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4158 (set-buffer-modified-p nil)
4159 (kill-buffer fancy-diary-buffer)))
4160 (when entries
4161 (setq entries (org-split-string entries "\n"))
4162 (setq entries
4163 (mapcar
4164 (lambda (x)
4165 (setq x (org-format-agenda-item "" x "Diary" 'time))
4166 ;; Extend the text properties to the beginning of the line
4167 (add-text-properties
4168 0 (length x)
4169 (text-properties-at (1- (length x)) x)
4170 x)
4171 x)
4172 entries)))))
4173
4174 (defun org-agenda-cleanup-fancy-diary ()
4175 "Remove unwanted stuff in buffer created by fancy-diary-display.
4176 This gets rid of the date, the underline under the date, and
4177 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4178 date. Itt also removes lines that contain only whitespace."
4179 (goto-char (point-min))
4180 (if (looking-at ".*?:[ \t]*")
4181 (progn
4182 (replace-match "")
4183 (re-search-forward "\n=+$" nil t)
4184 (replace-match "")
4185 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4186 (re-search-forward "\n=+$" nil t)
4187 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4188 (goto-char (point-min))
4189 (while (re-search-forward "^ +\n" nil t)
4190 (replace-match ""))
4191 (goto-char (point-min))
4192 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4193 (replace-match "")))
4194
4195 ;; Make sure entries from the diary have the right text properties.
4196 (eval-after-load "diary-lib"
4197 '(if (boundp 'diary-modify-entry-list-string-function)
4198 ;; We can rely on the hook, nothing to do
4199 nil
4200 ;; Hook not avaiable, must use advice to make this work
4201 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4202 "Make the position visible."
4203 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4204 (stringp string)
4205 (buffer-file-name))
4206 (setq string (org-modify-diary-entry-string string))))))
4207
4208 (defun org-modify-diary-entry-string (string)
4209 "Add text properties to string, allowing org-mode to act on it."
4210 (add-text-properties
4211 0 (length string)
4212 (list 'mouse-face 'highlight
4213 'keymap org-agenda-keymap
4214 'help-echo
4215 (format
4216 "mouse-2 or RET jump to diary file %s"
4217 (abbreviate-file-name (buffer-file-name)))
4218 'org-agenda-diary-link t
4219 'org-marker (org-agenda-new-marker (point-at-bol)))
4220 string)
4221 string)
4222
4223 (defun org-diary-default-entry ()
4224 "Add a dummy entry to the diary.
4225 Needed to avoid empty dates which mess up holiday display."
4226 ;; Catch the error if dealing with the new add-to-diary-alist
4227 (when org-disable-agenda-to-diary
4228 (condition-case nil
4229 (add-to-diary-list original-date "Org-mode dummy" "")
4230 (error
4231 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4232
4233 (defun org-add-file (&optional file)
4234 "Add current file to the list of files in variable `org-agenda-files'.
4235 These are the files which are being checked for agenda entries.
4236 Optional argument FILE means, use this file instead of the current.
4237 It is possible (but not recommended) to add this function to the
4238 `org-mode-hook'."
4239 (interactive)
4240 (catch 'exit
4241 (let* ((file (or file (buffer-file-name)
4242 (if (interactive-p)
4243 (error "Buffer is not visiting a file")
4244 (throw 'exit nil))))
4245 (true-file (file-truename file))
4246 (afile (abbreviate-file-name file))
4247 (present (delq nil (mapcar
4248 (lambda (x)
4249 (equal true-file (file-truename x)))
4250 org-agenda-files))))
4251 (if (not present)
4252 (progn
4253 (setq org-agenda-files
4254 (cons afile org-agenda-files))
4255 ;; Make sure custom.el does not end up with Org-mode
4256 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4257 (customize-save-variable 'org-agenda-files org-agenda-files))
4258 (org-install-agenda-files-menu)
4259 (message "Added file: %s" afile))
4260 (message "File was already in list: %s" afile)))))
4261
4262 (defun org-remove-file (&optional file)
4263 "Remove current file from the list of files in variable `org-agenda-files'.
4264 These are the files which are being checked for agenda entries.
4265 Optional argument FILE means, use this file instead of the current."
4266 (interactive)
4267 (let* ((file (or file (buffer-file-name)))
4268 (true-file (file-truename file))
4269 (afile (abbreviate-file-name file))
4270 (files (delq nil (mapcar
4271 (lambda (x)
4272 (if (equal true-file
4273 (file-truename x))
4274 nil x))
4275 org-agenda-files))))
4276 (if (not (= (length files) (length org-agenda-files)))
4277 (progn
4278 (setq org-agenda-files files)
4279 (customize-save-variable 'org-agenda-files org-agenda-files)
4280 (org-install-agenda-files-menu)
4281 (message "Removed file: %s" afile))
4282 (message "File was not in list: %s" afile))))
4283
4284 (defun org-file-menu-entry (file)
4285 (vector file (list 'find-file file) t))
4286 ;; FIXME: Maybe removed a buffer visited through the menu from
4287 ;; org-agenda-new-buffers, so that the buffer will not be removed
4288 ;; when exiting the agenda????
4289
4290 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4291 "Return a list of all relevant day numbers from BEG to END buffer positions.
4292 If NO-RANGES is non-nil, include only the start and end dates of a range,
4293 not every single day in the range. If FORCE-TODAY is non-nil, make
4294 sure that TODAY is included in the list."
4295 (let (dates date day day1 day2 ts1 ts2)
4296 (if force-today
4297 (setq dates (list (time-to-days (current-time)))))
4298 (save-excursion
4299 (goto-char beg)
4300 (while (re-search-forward org-ts-regexp end t)
4301 (setq day (time-to-days (org-time-string-to-time
4302 (substring (match-string 1) 0 10))))
4303 (or (memq day dates) (push day dates)))
4304 (unless no-ranges
4305 (goto-char beg)
4306 (while (re-search-forward org-tr-regexp end t)
4307 (setq ts1 (substring (match-string 1) 0 10)
4308 ts2 (substring (match-string 2) 0 10)
4309 day1 (time-to-days (org-time-string-to-time ts1))
4310 day2 (time-to-days (org-time-string-to-time ts2)))
4311 (while (< (setq day1 (1+ day1)) day2)
4312 (or (memq day1 dates) (push day1 dates)))))
4313 (sort dates '<))))
4314
4315 ;;;###autoload
4316 (defun org-diary (&rest args)
4317 "Return diary information from org-files.
4318 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4319 It accesses org files and extracts information from those files to be
4320 listed in the diary. The function accepts arguments specifying what
4321 items should be listed. The following arguments are allowed:
4322
4323 :timestamp List the headlines of items containing a date stamp or
4324 date range matching the selected date. Deadlines will
4325 also be listed, on the expiration day.
4326
4327 :deadline List any deadlines past due, or due within
4328 `org-deadline-warning-days'. The listing occurs only
4329 in the diary for *today*, not at any other date. If
4330 an entry is marked DONE, it is no longer listed.
4331
4332 :scheduled List all items which are scheduled for the given date.
4333 The diary for *today* also contains items which were
4334 scheduled earlier and are not yet marked DONE.
4335
4336 :todo List all TODO items from the org-file. This may be a
4337 long list - so this is not turned on by default.
4338 Like deadlines, these entries only show up in the
4339 diary for *today*, not at any other date.
4340
4341 The call in the diary file should look like this:
4342
4343 &%%(org-diary) ~/path/to/some/orgfile.org
4344
4345 Use a separate line for each org file to check. Or, if you omit the file name,
4346 all files listed in `org-agenda-files' will be checked automatically:
4347
4348 &%%(org-diary)
4349
4350 If you don't give any arguments (as in the example above), the default
4351 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4352 also be written as
4353
4354 &%%(org-diary :deadline :timestamp :scheduled)
4355
4356 The function expects the lisp variables `entry' and `date' to be provided
4357 by the caller, because this is how the calendar works. Don't use this
4358 function from a program - use `org-agenda-get-day-entries' instead."
4359 (org-agenda-maybe-reset-markers)
4360 (org-compile-prefix-format org-agenda-prefix-format)
4361 (setq args (or args '(:deadline :scheduled :timestamp)))
4362 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4363 (list entry)
4364 org-agenda-files))
4365 file rtn results)
4366 ;; If this is called during org-agenda, don't return any entries to
4367 ;; the calendar. Org Agenda will list these entries itself.
4368 (if org-disable-agenda-to-diary (setq files nil))
4369 (while (setq file (pop files))
4370 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4371 (setq results (append results rtn)))
4372 (if results
4373 (concat (org-finalize-agenda-entries results) "\n"))))
4374
4375 (defun org-agenda-get-day-entries (file date &rest args)
4376 "Does the work for `org-diary' and `org-agenda'.
4377 FILE is the path to a file to be checked for entries. DATE is date like
4378 the one returned by `calendar-current-date'. ARGS are symbols indicating
4379 which kind of entries should be extracted. For details about these, see
4380 the documentation of `org-diary'."
4381 (setq args (or args '(:deadline :scheduled :timestamp)))
4382 (let* ((org-startup-with-deadline-check nil)
4383 (org-startup-folded nil)
4384 (buffer (if (file-exists-p file)
4385 (org-get-agenda-file-buffer file)
4386 (error "No such file %s" file)))
4387 arg results rtn)
4388 (if (not buffer)
4389 ;; If file does not exist, make sure an error message ends up in diary
4390 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4391 (with-current-buffer buffer
4392 (unless (eq major-mode 'org-mode)
4393 (error "Agenda file %s is not in `org-mode'" file))
4394 (let ((case-fold-search nil))
4395 (save-excursion
4396 (save-restriction
4397 (if org-respect-restriction
4398 (if (org-region-active-p)
4399 ;; Respect a region to restrict search
4400 (narrow-to-region (region-beginning) (region-end)))
4401 ;; If we work for the calendar or many files,
4402 ;; get rid of any restriction
4403 (widen))
4404 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4405 (while (setq arg (pop args))
4406 (cond
4407 ((and (eq arg :todo)
4408 (equal date (calendar-current-date)))
4409 (setq rtn (org-agenda-get-todos))
4410 (setq results (append results rtn)))
4411 ((eq arg :timestamp)
4412 (setq rtn (org-agenda-get-blocks))
4413 (setq results (append results rtn))
4414 (setq rtn (org-agenda-get-timestamps))
4415 (setq results (append results rtn)))
4416 ((eq arg :scheduled)
4417 (setq rtn (org-agenda-get-scheduled))
4418 (setq results (append results rtn)))
4419 ((and (eq arg :deadline)
4420 (equal date (calendar-current-date)))
4421 (setq rtn (org-agenda-get-deadlines))
4422 (setq results (append results rtn))))))))
4423 results))))
4424
4425 (defun org-entry-is-done-p ()
4426 "Is the current entry marked DONE?"
4427 (save-excursion
4428 (and (re-search-backward "[\r\n]\\*" nil t)
4429 (looking-at org-nl-done-regexp))))
4430
4431 (defun org-at-date-range-p ()
4432 "Is the cursor inside a date range?"
4433 (interactive)
4434 (save-excursion
4435 (catch 'exit
4436 (let ((pos (point)))
4437 (skip-chars-backward "^<\r\n")
4438 (skip-chars-backward "<")
4439 (and (looking-at org-tr-regexp)
4440 (>= (match-end 0) pos)
4441 (throw 'exit t))
4442 (skip-chars-backward "^<\r\n")
4443 (skip-chars-backward "<")
4444 (and (looking-at org-tr-regexp)
4445 (>= (match-end 0) pos)
4446 (throw 'exit t)))
4447 nil)))
4448
4449 (defun org-agenda-get-todos ()
4450 "Return the TODO information for agenda display."
4451 (let* ((props (list 'face nil
4452 'done-face 'org-done
4453 'mouse-face 'highlight
4454 'keymap org-agenda-keymap
4455 'help-echo
4456 (format "mouse-2 or RET jump to org file %s"
4457 (abbreviate-file-name (buffer-file-name)))))
4458 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4459 "[^\n\r]*\\)"))
4460 marker priority
4461 ee txt)
4462 (goto-char (point-min))
4463 (while (re-search-forward regexp nil t)
4464 (goto-char (match-beginning 1))
4465 (setq marker (org-agenda-new-marker (point-at-bol))
4466 txt (org-format-agenda-item "" (match-string 1))
4467 priority
4468 (+ (org-get-priority txt)
4469 (if org-todo-kwd-priority-p
4470 (- org-todo-kwd-max-priority -2
4471 (length
4472 (member (match-string 2) org-todo-keywords)))
4473 1)))
4474 (add-text-properties
4475 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4476 'priority priority)
4477 props)
4478 txt)
4479 (push txt ee)
4480 (goto-char (match-end 1)))
4481 (nreverse ee)))
4482
4483 (defconst org-agenda-no-heading-message
4484 "No heading for this item in buffer or region")
4485
4486 (defun org-agenda-get-timestamps ()
4487 "Return the date stamp information for agenda display."
4488 (let* ((props (list 'face nil
4489 'mouse-face 'highlight
4490 'keymap org-agenda-keymap
4491 'help-echo
4492 (format "mouse-2 or RET jump to org file %s"
4493 (abbreviate-file-name (buffer-file-name)))))
4494 (regexp (regexp-quote
4495 (substring
4496 (format-time-string
4497 (car org-time-stamp-formats)
4498 (apply 'encode-time ; DATE bound by calendar
4499 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4500 0 11)))
4501 marker hdmarker deadlinep scheduledp donep tmp priority
4502 ee txt timestr)
4503 (goto-char (point-min))
4504 (while (re-search-forward regexp nil t)
4505 (if (not (save-match-data (org-at-date-range-p)))
4506 (progn
4507 (setq marker (org-agenda-new-marker (match-beginning 0))
4508 tmp (buffer-substring (max (point-min)
4509 (- (match-beginning 0)
4510 org-ds-keyword-length))
4511 (match-beginning 0))
4512 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4513 deadlinep (string-match org-deadline-regexp tmp)
4514 scheduledp (string-match org-scheduled-regexp tmp)
4515 donep (org-entry-is-done-p))
4516 (if (string-match ">" timestr)
4517 ;; substring should only run to end of time stamp
4518 (setq timestr (substring timestr 0 (match-end 0))))
4519 (save-excursion
4520 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4521 (progn
4522 (goto-char (match-end 1))
4523 (setq hdmarker (org-agenda-new-marker))
4524 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4525 (setq txt (org-format-agenda-item
4526 (format "%s%s"
4527 (if deadlinep "Deadline: " "")
4528 (if scheduledp "Scheduled: " ""))
4529 (match-string 1) nil timestr)))
4530 (setq txt org-agenda-no-heading-message))
4531 (setq priority (org-get-priority txt))
4532 (add-text-properties
4533 0 (length txt) (append (list 'org-marker marker
4534 'org-hd-marker hdmarker) props)
4535 txt)
4536 (if deadlinep
4537 (add-text-properties
4538 0 (length txt)
4539 (list 'face
4540 (if donep 'org-done 'org-warning)
4541 'undone-face 'org-warning
4542 'done-face 'org-done
4543 'priority (+ 100 priority))
4544 txt)
4545 (if scheduledp
4546 (add-text-properties
4547 0 (length txt)
4548 (list 'face 'org-scheduled-today
4549 'undone-face 'org-scheduled-today
4550 'done-face 'org-done
4551 priority (+ 99 priority))
4552 txt)
4553 (add-text-properties
4554 0 (length txt)
4555 (list 'priority priority) txt)))
4556 (push txt ee))
4557 (outline-next-heading))))
4558 (nreverse ee)))
4559
4560 (defun org-agenda-get-deadlines ()
4561 "Return the deadline information for agenda display."
4562 (let* ((wdays org-deadline-warning-days)
4563 (props (list 'mouse-face 'highlight
4564 'keymap org-agenda-keymap
4565 'help-echo
4566 (format "mouse-2 or RET jump to org file %s"
4567 (abbreviate-file-name (buffer-file-name)))))
4568 (regexp org-deadline-time-regexp)
4569 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4570 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4571 d2 diff pos pos1
4572 ee txt head)
4573 (goto-char (point-min))
4574 (while (re-search-forward regexp nil t)
4575 (setq pos (1- (match-beginning 1))
4576 d2 (time-to-days
4577 (org-time-string-to-time (match-string 1)))
4578 diff (- d2 d1))
4579 ;; When to show a deadline in the calendar:
4580 ;; If the expiration is within wdays warning time.
4581 ;; Past-due deadlines are only shown on the current date
4582 (if (and (< diff wdays) todayp (not (= diff 0)))
4583 (save-excursion
4584 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4585 (progn
4586 (goto-char (match-end 0))
4587 (setq pos1 (match-end 1))
4588 (setq head (buffer-substring-no-properties
4589 (point)
4590 (progn (skip-chars-forward "^\r\n")
4591 (point))))
4592 (if (string-match org-looking-at-done-regexp head)
4593 (setq txt nil)
4594 (setq txt (org-format-agenda-item
4595 (format "In %3d d.: " diff) head))))
4596 (setq txt org-agenda-no-heading-message))
4597 (when txt
4598 (add-text-properties
4599 0 (length txt)
4600 (append
4601 (list 'org-marker (org-agenda-new-marker pos)
4602 'org-hd-marker (org-agenda-new-marker pos1)
4603 'priority (+ (- 10 diff) (org-get-priority txt))
4604 'face (cond ((<= diff 0) 'org-warning)
4605 ((<= diff 5) 'org-scheduled-previously)
4606 (t nil))
4607 'undone-face (cond
4608 ((<= diff 0) 'org-warning)
4609 ((<= diff 5) 'org-scheduled-previously)
4610 (t nil))
4611 'done-face 'org-done)
4612 props)
4613 txt)
4614 (push txt ee)))))
4615 ee))
4616
4617 (defun org-agenda-get-scheduled ()
4618 "Return the scheduled information for agenda display."
4619 (let* ((props (list 'face 'org-scheduled-previously
4620 'undone-face 'org-scheduled-previously
4621 'done-face 'org-done
4622 'mouse-face 'highlight
4623 'keymap org-agenda-keymap
4624 'help-echo
4625 (format "mouse-2 or RET jump to org file %s"
4626 (abbreviate-file-name (buffer-file-name)))))
4627 (regexp org-scheduled-time-regexp)
4628 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4629 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4630 d2 diff pos pos1
4631 ee txt head)
4632 (goto-char (point-min))
4633 (while (re-search-forward regexp nil t)
4634 (setq pos (1- (match-beginning 1))
4635 d2 (time-to-days
4636 (org-time-string-to-time (match-string 1)))
4637 diff (- d2 d1))
4638 ;; When to show a scheduled item in the calendar:
4639 ;; If it is on or past the date.
4640 (if (and (< diff 0) todayp)
4641 (save-excursion
4642 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4643 (progn
4644 (goto-char (match-end 0))
4645 (setq pos1 (match-end 1))
4646 (setq head (buffer-substring-no-properties
4647 (point)
4648 (progn (skip-chars-forward "^\r\n") (point))))
4649 (if (string-match org-looking-at-done-regexp head)
4650 (setq txt nil)
4651 (setq txt (org-format-agenda-item
4652 (format "Sched.%2dx: " (- 1 diff)) head))))
4653 (setq txt org-agenda-no-heading-message))
4654 (when txt
4655 (add-text-properties
4656 0 (length txt)
4657 (append (list 'org-marker (org-agenda-new-marker pos)
4658 'org-hd-marker (org-agenda-new-marker pos1)
4659 'priority (+ (- 5 diff) (org-get-priority txt)))
4660 props) txt)
4661 (push txt ee)))))
4662 ee))
4663
4664 (defun org-agenda-get-blocks ()
4665 "Return the date-range information for agenda display."
4666 (let* ((props (list 'face nil
4667 'mouse-face 'highlight
4668 'keymap org-agenda-keymap
4669 'help-echo
4670 (format "mouse-2 or RET jump to org file %s"
4671 (abbreviate-file-name (buffer-file-name)))))
4672 (regexp org-tr-regexp)
4673 (d0 (calendar-absolute-from-gregorian date))
4674 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4675 (goto-char (point-min))
4676 (while (re-search-forward regexp nil t)
4677 (setq timestr (match-string 0)
4678 s1 (match-string 1)
4679 s2 (match-string 2)
4680 d1 (time-to-days (org-time-string-to-time s1))
4681 d2 (time-to-days (org-time-string-to-time s2)))
4682 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4683 ;; Only allow days between the limits, because the normal
4684 ;; date stamps will catch the limits.
4685 (save-excursion
4686 (setq marker (org-agenda-new-marker (point)))
4687 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4688 (progn
4689 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4690 (goto-char (match-end 1))
4691 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4692 (setq txt (org-format-agenda-item
4693 (format (if (= d1 d2) "" "(%d/%d): ")
4694 (1+ (- d0 d1)) (1+ (- d2 d1)))
4695 (match-string 1) nil (if (= d0 d1) timestr))))
4696 (setq txt org-agenda-no-heading-message))
4697 (add-text-properties
4698 0 (length txt) (append (list 'org-marker marker
4699 'org-hd-marker hdmarker
4700 'priority (org-get-priority txt))
4701 props)
4702 txt)
4703 (push txt ee)))
4704 (outline-next-heading))
4705 ;; Sort the entries by expiration date.
4706 (nreverse ee)))
4707
4708
4709
4710 (defconst org-plain-time-of-day-regexp
4711 (concat
4712 "\\(\\<[012]?[0-9]"
4713 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4714 "\\(--?"
4715 "\\(\\<[012]?[0-9]"
4716 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4717 "\\)?")
4718 "Regular expression to match a plain time or time range.
4719 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4720 groups carry important information:
4721 0 the full match
4722 1 the first time, range or not
4723 8 the second time, if it is a range.")
4724
4725 (defconst org-stamp-time-of-day-regexp
4726 (concat
4727 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4728 "\\([012][0-9]:[0-5][0-9]\\)>"
4729 "\\(--?"
4730 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4731 "Regular expression to match a timestamp time or time range.
4732 After a match, the following groups carry important information:
4733 0 the full match
4734 1 date plus weekday, for backreferencing to make sure both times on same day
4735 2 the first time, range or not
4736 4 the second time, if it is a range.")
4737
4738 (defvar org-prefix-has-time nil
4739 "A flag, set by `org-compile-prefix-format'.
4740 The flag is set if the currently compiled format contains a `%t'.")
4741
4742 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4743 "Format TXT to be inserted into the agenda buffer.
4744 In particular, it adds the prefix and corresponding text properties. EXTRA
4745 must be a string and replaces the `%s' specifier in the prefix format.
4746 CATEGORY (string, symbol or nil) may be used to overule the default
4747 category taken from local variable or file name. It will replace the `%c'
4748 specifier in the format. DOTIME, when non-nil, indicates that a
4749 time-of-day should be extracted from TXT for sorting of this entry, and for
4750 the `%t' specifier in the format. When DOTIME is a string, this string is
4751 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4752 only the correctly processes TXT should be returned - this is used by
4753 `org-agenda-change-all-lines'."
4754 (save-match-data
4755 ;; Diary entries sometimes have extra whitespace at the beginning
4756 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4757 (let* ((category (or category
4758 org-category
4759 (if (buffer-file-name)
4760 (file-name-sans-extension
4761 (file-name-nondirectory (buffer-file-name)))
4762 "")))
4763 time ;; needed for the eval of the prefix format
4764 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4765 (time-of-day (and dotime (org-get-time-of-day ts)))
4766 stamp plain s0 s1 s2 rtn)
4767 (when (and dotime time-of-day org-prefix-has-time)
4768 ;; Extract starting and ending time and move them to prefix
4769 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4770 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4771 (setq s0 (match-string 0 ts)
4772 s1 (match-string (if plain 1 2) ts)
4773 s2 (match-string (if plain 8 4) ts))
4774
4775 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4776 ;; them, we might want to remove them there to avoid duplication.
4777 ;; The user can turn this off with a variable.
4778 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4779 (string-match (concat (regexp-quote s0) " *") txt)
4780 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4781 (= (match-beginning 0) 0)
4782 t))
4783 (setq txt (replace-match "" nil nil txt))))
4784 ;; Normalize the time(s) to 24 hour
4785 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4786 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4787
4788 ;; Create the final string
4789 (if noprefix
4790 (setq rtn txt)
4791 ;; Prepare the variables needed in the eval of the compiled format
4792 (setq time (cond (s2 (concat s1 "-" s2))
4793 (s1 (concat s1 "......"))
4794 (t ""))
4795 extra (or extra "")
4796 category (if (symbolp category) (symbol-name category) category))
4797 ;; Evaluate the compiled format
4798 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4799
4800 ;; And finally add the text properties
4801 (add-text-properties
4802 0 (length rtn) (list 'category (downcase category)
4803 'prefix-length (- (length rtn) (length txt))
4804 'time-of-day time-of-day
4805 'dotime dotime)
4806 rtn)
4807 rtn)))
4808
4809 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4810 (catch 'exit
4811 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4812 ((and todayp (member 'today (car org-agenda-time-grid))))
4813 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4814 ((member 'weekly (car org-agenda-time-grid)))
4815 (t (throw 'exit list)))
4816 (let* ((have (delq nil (mapcar
4817 (lambda (x) (get-text-property 1 'time-of-day x))
4818 list)))
4819 (string (nth 1 org-agenda-time-grid))
4820 (gridtimes (nth 2 org-agenda-time-grid))
4821 (req (car org-agenda-time-grid))
4822 (remove (member 'remove-match req))
4823 new time)
4824 (if (and (member 'require-timed req) (not have))
4825 ;; don't show empty grid
4826 (throw 'exit list))
4827 (while (setq time (pop gridtimes))
4828 (unless (and remove (member time have))
4829 (setq time (int-to-string time))
4830 (push (org-format-agenda-item
4831 nil string "" ;; FIXME: put a category?
4832 (concat (substring time 0 -2) ":" (substring time -2)))
4833 new)
4834 (put-text-property
4835 1 (length (car new)) 'face 'org-time-grid (car new))))
4836 (if (member 'time-up org-agenda-sorting-strategy)
4837 (append new list)
4838 (append list new)))))
4839
4840 (defun org-compile-prefix-format (format)
4841 "Compile the prefix format into a Lisp form that can be evaluated.
4842 The resulting form is returned and stored in the variable
4843 `org-prefix-format-compiled'."
4844 (setq org-prefix-has-time nil)
4845 (let ((start 0) varform vars var (s format) c f opt)
4846 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4847 s start)
4848 (setq var (cdr (assoc (match-string 4 s)
4849 '(("c" . category) ("t" . time) ("s" . extra))))
4850 c (or (match-string 3 s) "")
4851 opt (match-beginning 1)
4852 start (1+ (match-beginning 0)))
4853 (if (equal var 'time) (setq org-prefix-has-time t))
4854 (setq f (concat "%" (match-string 2 s) "s"))
4855 (if opt
4856 (setq varform
4857 `(if (equal "" ,var)
4858 ""
4859 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4860 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4861 (setq s (replace-match "%s" t nil s))
4862 (push varform vars))
4863 (setq vars (nreverse vars))
4864 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4865
4866 (defun org-get-time-of-day (s &optional string)
4867 "Check string S for a time of day.
4868 If found, return it as a military time number between 0 and 2400.
4869 If not found, return nil.
4870 The optional STRING argument forces conversion into a 5 character wide string
4871 HH:MM."
4872 (save-match-data
4873 (when
4874 (or
4875 (string-match
4876 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4877 (string-match
4878 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4879 (let* ((t0 (+ (* 100
4880 (+ (string-to-number (match-string 1 s))
4881 (if (and (match-beginning 4)
4882 (equal (downcase (match-string 4 s)) "pm"))
4883 12 0)))
4884 (if (match-beginning 3)
4885 (string-to-number (match-string 3 s))
4886 0)))
4887 (t1 (concat " " (int-to-string t0))))
4888 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4889
4890 (defun org-finalize-agenda-entries (list)
4891 "Sort and concatenate the agenda items."
4892 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4893
4894 (defsubst org-cmp-priority (a b)
4895 "Compare the priorities of string a and b."
4896 (let ((pa (or (get-text-property 1 'priority a) 0))
4897 (pb (or (get-text-property 1 'priority b) 0)))
4898 (cond ((> pa pb) +1)
4899 ((< pa pb) -1)
4900 (t nil))))
4901
4902 (defsubst org-cmp-category (a b)
4903 "Compare the string values of categories of strings a and b."
4904 (let ((ca (or (get-text-property 1 'category a) ""))
4905 (cb (or (get-text-property 1 'category b) "")))
4906 (cond ((string-lessp ca cb) -1)
4907 ((string-lessp cb ca) +1)
4908 (t nil))))
4909
4910 (defsubst org-cmp-time (a b)
4911 "Compare the time-of-day values of strings a and b."
4912 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4913 (ta (or (get-text-property 1 'time-of-day a) def))
4914 (tb (or (get-text-property 1 'time-of-day b) def)))
4915 (cond ((< ta tb) -1)
4916 ((< tb ta) +1)
4917 (t nil))))
4918
4919 (defun org-entries-lessp (a b)
4920 "Predicate for sorting agenda entries."
4921 ;; The following variables will be used when the form is evaluated.
4922 (let* ((time-up (org-cmp-time a b))
4923 (time-down (if time-up (- time-up) nil))
4924 (priority-up (org-cmp-priority a b))
4925 (priority-down (if priority-up (- priority-up) nil))
4926 (category-up (org-cmp-category a b))
4927 (category-down (if category-up (- category-up) nil))
4928 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4929 (cdr (assoc
4930 (eval (cons 'or org-agenda-sorting-strategy))
4931 '((-1 . t) (1 . nil) (nil . nil))))))
4932
4933 (defun org-agenda-show-priority ()
4934 "Show the priority of the current item.
4935 This priority is composed of the main priority given with the [#A] cookies,
4936 and by additional input from the age of a schedules or deadline entry."
4937 (interactive)
4938 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4939 (message "Priority is %d" (if pri pri -1000))))
4940
4941 (defun org-agenda-goto (&optional highlight)
4942 "Go to the Org-mode file which contains the item at point."
4943 (interactive)
4944 (let* ((marker (or (get-text-property (point) 'org-marker)
4945 (org-agenda-error)))
4946 (buffer (marker-buffer marker))
4947 (pos (marker-position marker)))
4948 (switch-to-buffer-other-window buffer)
4949 (widen)
4950 (goto-char pos)
4951 (when (eq major-mode 'org-mode)
4952 (org-show-hidden-entry)
4953 (save-excursion
4954 (and (outline-next-heading)
4955 (org-flag-heading nil)))) ; show the next heading
4956 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4957
4958 (defun org-agenda-switch-to ()
4959 "Go to the Org-mode file which contains the item at point."
4960 (interactive)
4961 (let* ((marker (or (get-text-property (point) 'org-marker)
4962 (org-agenda-error)))
4963 (buffer (marker-buffer marker))
4964 (pos (marker-position marker)))
4965 (switch-to-buffer buffer)
4966 (delete-other-windows)
4967 (widen)
4968 (goto-char pos)
4969 (when (eq major-mode 'org-mode)
4970 (org-show-hidden-entry)
4971 (save-excursion
4972 (and (outline-next-heading)
4973 (org-flag-heading nil)))))) ; show the next heading
4974
4975 (defun org-agenda-goto-mouse (ev)
4976 "Go to the Org-mode file which contains the item at the mouse click."
4977 (interactive "e")
4978 (mouse-set-point ev)
4979 (org-agenda-goto))
4980
4981 (defun org-agenda-show ()
4982 "Display the Org-mode file which contains the item at point."
4983 (interactive)
4984 (let ((win (selected-window)))
4985 (org-agenda-goto t)
4986 (select-window win)))
4987
4988 (defun org-agenda-recenter (arg)
4989 "Display the Org-mode file which contains the item at point and recenter."
4990 (interactive "P")
4991 (let ((win (selected-window)))
4992 (org-agenda-goto t)
4993 (recenter arg)
4994 (select-window win)))
4995
4996 (defun org-agenda-show-mouse (ev)
4997 "Display the Org-mode file which contains the item at the mouse click."
4998 (interactive "e")
4999 (mouse-set-point ev)
5000 (org-agenda-show))
5001
5002 (defun org-agenda-check-no-diary ()
5003 "Check if the entry is a diary link and abort if yes."
5004 (if (get-text-property (point) 'org-agenda-diary-link)
5005 (org-agenda-error)))
5006
5007 (defun org-agenda-error ()
5008 (error "Command not allowed in this line"))
5009
5010 (defvar org-last-heading-marker (make-marker)
5011 "Marker pointing to the headline that last changed its TODO state
5012 by a remote command from the agenda.")
5013
5014 (defun org-agenda-todo ()
5015 "Cycle TODO state of line at point, also in Org-mode file.
5016 This changes the line at point, all other lines in the agenda referring to
5017 the same tree node, and the headline of the tree node in the Org-mode file."
5018 (interactive)
5019 (org-agenda-check-no-diary)
5020 (let* ((col (current-column))
5021 (marker (or (get-text-property (point) 'org-marker)
5022 (org-agenda-error)))
5023 (buffer (marker-buffer marker))
5024 (pos (marker-position marker))
5025 (hdmarker (get-text-property (point) 'org-hd-marker))
5026 (buffer-read-only nil)
5027 newhead)
5028 (with-current-buffer buffer
5029 (widen)
5030 (goto-char pos)
5031 (org-show-hidden-entry)
5032 (save-excursion
5033 (and (outline-next-heading)
5034 (org-flag-heading nil))) ; show the next heading
5035 (org-todo)
5036 (forward-char 1)
5037 (setq newhead (org-get-heading))
5038 (save-excursion
5039 (org-back-to-heading)
5040 (move-marker org-last-heading-marker (point))))
5041 (beginning-of-line 1)
5042 (save-excursion
5043 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5044 (move-to-column col)))
5045
5046 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5047 "Change all lines in the agenda buffer which match hdmarker.
5048 The new content of the line will be NEWHEAD (as modified by
5049 `org-format-agenda-item'). HDMARKER is checked with
5050 `equal' against all `org-hd-marker' text properties in the file.
5051 If FIXFACE is non-nil, the face of each item is modified acording to
5052 the new TODO state."
5053 (let* (props m pl undone-face done-face finish new dotime)
5054 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5055 (save-excursion
5056 (goto-char (point-max))
5057 (beginning-of-line 1)
5058 (while (not finish)
5059 (setq finish (bobp))
5060 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5061 (equal m hdmarker))
5062 (setq props (text-properties-at (point))
5063 dotime (get-text-property (point) 'dotime)
5064 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
5065 pl (get-text-property (point) 'prefix-length)
5066 undone-face (get-text-property (point) 'undone-face)
5067 done-face (get-text-property (point) 'done-face))
5068 (move-to-column pl)
5069 (if (looking-at ".*")
5070 (progn
5071 (replace-match new t t)
5072 (beginning-of-line 1)
5073 (add-text-properties (point-at-bol) (point-at-eol) props)
5074 (if fixface
5075 (add-text-properties
5076 (point-at-bol) (point-at-eol)
5077 (list 'face
5078 (if org-last-todo-state-is-todo
5079 undone-face done-face))))
5080 (beginning-of-line 1))
5081 (error "Line update did not work")))
5082 (beginning-of-line 0)))))
5083
5084 (defun org-agenda-priority-up ()
5085 "Increase the priority of line at point, also in Org-mode file."
5086 (interactive)
5087 (org-agenda-priority 'up))
5088
5089 (defun org-agenda-priority-down ()
5090 "Decrease the priority of line at point, also in Org-mode file."
5091 (interactive)
5092 (org-agenda-priority 'down))
5093
5094 (defun org-agenda-priority (&optional force-direction)
5095 "Set the priority of line at point, also in Org-mode file.
5096 This changes the line at point, all other lines in the agenda referring to
5097 the same tree node, and the headline of the tree node in the Org-mode file."
5098 (interactive)
5099 (org-agenda-check-no-diary)
5100 (let* ((marker (or (get-text-property (point) 'org-marker)
5101 (org-agenda-error)))
5102 (buffer (marker-buffer marker))
5103 (pos (marker-position marker))
5104 (hdmarker (get-text-property (point) 'org-hd-marker))
5105 (buffer-read-only nil)
5106 newhead)
5107 (with-current-buffer buffer
5108 (widen)
5109 (goto-char pos)
5110 (org-show-hidden-entry)
5111 (save-excursion
5112 (and (outline-next-heading)
5113 (org-flag-heading nil))) ; show the next heading
5114 (funcall 'org-priority force-direction)
5115 (end-of-line 1)
5116 (setq newhead (org-get-heading)))
5117 (org-agenda-change-all-lines newhead hdmarker)
5118 (beginning-of-line 1)))
5119
5120 (defun org-agenda-date-later (arg &optional what)
5121 "Change the date of this item to one day later."
5122 (interactive "p")
5123 (org-agenda-check-no-diary)
5124 (let* ((marker (or (get-text-property (point) 'org-marker)
5125 (org-agenda-error)))
5126 (buffer (marker-buffer marker))
5127 (pos (marker-position marker)))
5128 (with-current-buffer buffer
5129 (widen)
5130 (goto-char pos)
5131 (if (not (org-at-timestamp-p))
5132 (error "Cannot find time stamp"))
5133 (org-timestamp-change arg (or what 'day))
5134 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5135
5136 (defun org-agenda-date-earlier (arg &optional what)
5137 "Change the date of this item to one day earlier."
5138 (interactive "p")
5139 (org-agenda-date-later (- arg) what))
5140
5141 (defun org-agenda-date-prompt (arg)
5142 "Change the date of this item. Date is prompted for, with default today.
5143 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5144 be used to request time specification in the time stamp."
5145 (interactive "P")
5146 (org-agenda-check-no-diary)
5147 (let* ((marker (or (get-text-property (point) 'org-marker)
5148 (org-agenda-error)))
5149 (buffer (marker-buffer marker))
5150 (pos (marker-position marker)))
5151 (with-current-buffer buffer
5152 (widen)
5153 (goto-char pos)
5154 (if (not (org-at-timestamp-p))
5155 (error "Cannot find time stamp"))
5156 (org-time-stamp arg)
5157 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5158
5159 (defun org-get-heading ()
5160 "Return the heading of the current entry, without the stars."
5161 (save-excursion
5162 (if (and (re-search-backward "[\r\n]\\*" nil t)
5163 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5164 (match-string 1)
5165 "")))
5166
5167 (defun org-agenda-diary-entry ()
5168 "Make a diary entry, like the `i' command from the calendar.
5169 All the standard commands work: block, weekly etc"
5170 (interactive)
5171 (require 'diary-lib)
5172 (let* ((char (progn
5173 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5174 (read-char-exclusive)))
5175 (cmd (cdr (assoc char
5176 '((?d . insert-diary-entry)
5177 (?w . insert-weekly-diary-entry)
5178 (?m . insert-monthly-diary-entry)
5179 (?y . insert-yearly-diary-entry)
5180 (?a . insert-anniversary-diary-entry)
5181 (?b . insert-block-diary-entry)
5182 (?c . insert-cyclic-diary-entry)))))
5183 (oldf (symbol-function 'calendar-cursor-to-date))
5184 (point (point))
5185 (mark (or (mark t) (point))))
5186 (unless cmd
5187 (error "No command associated with <%c>" char))
5188 (unless (and (get-text-property point 'day)
5189 (or (not (equal ?b char))
5190 (get-text-property mark 'day)))
5191 (error "Don't know which date to use for diary entry"))
5192 ;; We implement this by hacking the `calendar-cursor-to-date' function
5193 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5194 (let ((calendar-mark-ring
5195 (list (calendar-gregorian-from-absolute
5196 (or (get-text-property mark 'day)
5197 (get-text-property point 'day))))))
5198 (unwind-protect
5199 (progn
5200 (fset 'calendar-cursor-to-date
5201 (lambda (&optional error)
5202 (calendar-gregorian-from-absolute
5203 (get-text-property point 'day))))
5204 (call-interactively cmd))
5205 (fset 'calendar-cursor-to-date oldf)))))
5206
5207
5208 (defun org-agenda-execute-calendar-command (cmd)
5209 "Execute a calendar command from the agenda, with the date associated to
5210 the cursor position."
5211 (require 'diary-lib)
5212 (unless (get-text-property (point) 'day)
5213 (error "Don't know which date to use for calendar command"))
5214 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5215 (point (point))
5216 (date (calendar-gregorian-from-absolute
5217 (get-text-property point 'day)))
5218 (displayed-day (extract-calendar-day date))
5219 (displayed-month (extract-calendar-month date))
5220 (displayed-year (extract-calendar-year date)))
5221 (unwind-protect
5222 (progn
5223 (fset 'calendar-cursor-to-date
5224 (lambda (&optional error)
5225 (calendar-gregorian-from-absolute
5226 (get-text-property point 'day))))
5227 (call-interactively cmd))
5228 (fset 'calendar-cursor-to-date oldf))))
5229
5230 (defun org-agenda-phases-of-moon ()
5231 "Display the phases of the moon for the 3 months around the cursor date."
5232 (interactive)
5233 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5234
5235 (defun org-agenda-holidays ()
5236 "Display the holidays for the 3 months around the cursor date."
5237 (interactive)
5238 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5239
5240 (defun org-agenda-sunrise-sunset (arg)
5241 "Display sunrise and sunset for the cursor date.
5242 Latitude and longitude can be specified with the variables
5243 `calendar-latitude' and `calendar-longitude'. When called with prefix
5244 argument, latitude and longitude will be prompted for."
5245 (interactive "P")
5246 (let ((calendar-longitude (if arg nil calendar-longitude))
5247 (calendar-latitude (if arg nil calendar-latitude))
5248 (calendar-location-name
5249 (if arg "the given coordinates" calendar-location-name)))
5250 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5251
5252 (defun org-agenda-goto-calendar ()
5253 "Open the Emacs calendar with the date at the cursor."
5254 (interactive)
5255 (let* ((day (or (get-text-property (point) 'day)
5256 (error "Don't know which date to open in calendar")))
5257 (date (calendar-gregorian-from-absolute day))
5258 (calendar-move-hook nil)
5259 (view-diary-entries-initially nil))
5260 (calendar)
5261 (calendar-goto-date date)))
5262
5263 (defun org-calendar-goto-agenda ()
5264 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5265 This is a command that has to be installed in `calendar-mode-map'."
5266 (interactive)
5267 (org-agenda nil (calendar-absolute-from-gregorian
5268 (calendar-cursor-to-date))))
5269
5270 (defun org-agenda-convert-date ()
5271 (interactive)
5272 (let ((day (get-text-property (point) 'day))
5273 date s)
5274 (unless day
5275 (error "Don't know which date to convert"))
5276 (setq date (calendar-gregorian-from-absolute day))
5277 (setq s (concat
5278 "Gregorian: " (calendar-date-string date) "\n"
5279 "ISO: " (calendar-iso-date-string date) "\n"
5280 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5281 "Julian: " (calendar-julian-date-string date) "\n"
5282 "Astron. JD: " (calendar-astro-date-string date)
5283 " (Julian date number at noon UTC)\n"
5284 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5285 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5286 "French: " (calendar-french-date-string date) "\n"
5287 "Mayan: " (calendar-mayan-date-string date) "\n"
5288 "Coptic: " (calendar-coptic-date-string date) "\n"
5289 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5290 "Persian: " (calendar-persian-date-string date) "\n"
5291 "Chinese: " (calendar-chinese-date-string date) "\n"))
5292 (with-output-to-temp-buffer "*Dates*"
5293 (princ s))
5294 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5295
5296 ;;; Link Stuff
5297
5298 (defun org-find-file-at-mouse (ev)
5299 "Open file link or URL at mouse."
5300 (interactive "e")
5301 (mouse-set-point ev)
5302 (org-open-at-point 'in-emacs))
5303
5304 (defun org-open-at-mouse (ev)
5305 "Open file link or URL at mouse."
5306 (interactive "e")
5307 (mouse-set-point ev)
5308 (org-open-at-point))
5309
5310 (defun org-open-at-point (&optional in-emacs)
5311 "Open link at or after point.
5312 If there is no link at point, this function will search forward up to
5313 the end of the current subtree.
5314 Normally, files will be opened by an appropriate application. If the
5315 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5316 (interactive "P")
5317 (if (org-at-timestamp-p)
5318 (org-agenda nil (time-to-days (org-time-string-to-time
5319 (substring (match-string 1) 0 10)))
5320 1)
5321 (let (type path line (pos (point)))
5322 (save-excursion
5323 (skip-chars-backward
5324 (concat (if org-allow-space-in-links "^" "^ ")
5325 org-non-link-chars))
5326 (if (re-search-forward
5327 org-link-regexp
5328 (save-excursion
5329 (condition-case nil
5330 (progn (outline-end-of-subtree) (max pos (point)))
5331 (error (end-of-line 1) (point))))
5332 t)
5333 (setq type (match-string 1)
5334 path (match-string 2)))
5335 (unless path
5336 (error "No link found"))
5337 ;; Remove any trailing spaces in path
5338 (if (string-match " +\\'" path)
5339 (setq path (replace-match "" t t path)))
5340
5341 (cond
5342
5343 ((string= type "file")
5344 (if (string-match ":\\([0-9]+\\)\\'" path)
5345 (setq line (string-to-number (match-string 1 path))
5346 path (substring path 0 (match-beginning 0))))
5347 (org-open-file path in-emacs line))
5348
5349 ((string= type "news")
5350 (org-follow-gnus-link path))
5351
5352 ((string= type "bbdb")
5353 (org-follow-bbdb-link path))
5354
5355 ((string= type "gnus")
5356 (let (group article)
5357 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5358 (error "Error in Gnus link"))
5359 (setq group (match-string 1 path)
5360 article (match-string 3 path))
5361 (org-follow-gnus-link group article)))
5362
5363 ((string= type "vm")
5364 (let (folder article)
5365 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5366 (error "Error in VM link"))
5367 (setq folder (match-string 1 path)
5368 article (match-string 3 path))
5369 ;; in-emacs is the prefix arg, will be interpreted as read-only
5370 (org-follow-vm-link folder article in-emacs)))
5371
5372 ((string= type "wl")
5373 (let (folder article)
5374 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5375 (error "Error in Wanderlust link"))
5376 (setq folder (match-string 1 path)
5377 article (match-string 3 path))
5378 (org-follow-wl-link folder article)))
5379
5380 ((string= type "rmail")
5381 (let (folder article)
5382 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5383 (error "Error in RMAIL link"))
5384 (setq folder (match-string 1 path)
5385 article (match-string 3 path))
5386 (org-follow-rmail-link folder article)))
5387
5388 ((string= type "shell")
5389 (let ((cmd path))
5390 (while (string-match "@{" cmd)
5391 (setq cmd (replace-match "<" t t cmd)))
5392 (while (string-match "@}" cmd)
5393 (setq cmd (replace-match ">" t t cmd)))
5394 (if (or (not org-confirm-shell-links)
5395 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5396 (shell-command cmd)
5397 (error "Abort"))))
5398
5399 (t
5400 (browse-url-at-point)))))))
5401
5402 (defun org-follow-bbdb-link (name)
5403 "Follow a BBDB link to NAME."
5404 (require 'bbdb)
5405 (let ((inhibit-redisplay t))
5406 (catch 'exit
5407 ;; Exact match on name
5408 (bbdb-name (concat "\\`" name "\\'") nil)
5409 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5410 ;; Exact match on name
5411 (bbdb-company (concat "\\`" name "\\'") nil)
5412 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5413 ;; Partial match on name
5414 (bbdb-name name nil)
5415 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5416 ;; Partial match on company
5417 (bbdb-company name nil)
5418 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5419 ;; General match including network address and notes
5420 (bbdb name nil)
5421 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5422 (delete-window (get-buffer-window "*BBDB*"))
5423 (error "No matching BBDB record")))))
5424
5425 (defun org-follow-gnus-link (&optional group article)
5426 "Follow a Gnus link to GROUP and ARTICLE."
5427 (require 'gnus)
5428 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5429 (if group (gnus-fetch-group group))
5430 (if article
5431 (or (gnus-summary-goto-article article nil 'force)
5432 (if (fboundp 'gnus-summary-insert-cached-articles)
5433 (progn
5434 (gnus-summary-insert-cached-articles)
5435 (gnus-summary-goto-article article nil 'force))
5436 (message "Message could not be found.")))))
5437
5438 (defun org-follow-vm-link (&optional folder article readonly)
5439 "Follow a VM link to FOLDER and ARTICLE."
5440 (require 'vm)
5441 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5442 ;; ange-ftp or efs or tramp access
5443 (let ((user (or (match-string 1 folder) (user-login-name)))
5444 (host (match-string 2 folder))
5445 (file (match-string 3 folder)))
5446 (cond
5447 ((featurep 'tramp)
5448 ;; use tramp to access the file
5449 (if org-xemacs-p
5450 (setq folder (format "[%s@%s]%s" user host file))
5451 (setq folder (format "/%s@%s:%s" user host file))))
5452 (t
5453 ;; use ange-ftp or efs
5454 (require (if org-xemacs-p 'efs 'ange-ftp))
5455 (setq folder (format "/%s@%s:%s" user host file))))))
5456 (when folder
5457 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5458 (sit-for 0.1)
5459 (when article
5460 (vm-select-folder-buffer)
5461 (widen)
5462 (let ((case-fold-search t))
5463 (goto-char (point-min))
5464 (if (not (re-search-forward
5465 (concat "^" "message-id: *" (regexp-quote article))))
5466 (error "Could not find the specified message in this folder"))
5467 (vm-isearch-update)
5468 (vm-isearch-narrow)
5469 (vm-beginning-of-message)
5470 (vm-summarize)))))
5471
5472 (defun org-follow-wl-link (folder article)
5473 "Follow a Wanderlust link to FOLDER and ARTICLE."
5474 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5475 (if article (wl-summary-jump-to-msg-by-message-id article))
5476 (wl-summary-redisplay))
5477
5478 (defun org-follow-rmail-link (folder article)
5479 "Follow an RMAIL link to FOLDER and ARTICLE."
5480 (let (message-number)
5481 (save-excursion
5482 (save-window-excursion
5483 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5484 (setq message-number
5485 (save-restriction
5486 (widen)
5487 (goto-char (point-max))
5488 (if (re-search-backward
5489 (concat "^Message-ID:\\s-+" (regexp-quote
5490 (or article "")))
5491 nil t)
5492 (rmail-what-message))))))
5493 (if message-number
5494 (progn
5495 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5496 (rmail-show-message message-number)
5497 message-number)
5498 (error "Message not found"))))
5499
5500 (defun org-open-file (path &optional in-emacs line)
5501 "Open the file at PATH.
5502 First, this expands any special file name abbreviations. Then the
5503 configuration variable `org-file-apps' is checked if it contains an
5504 entry for this file type, and if yes, the corresponding command is launched.
5505 If no application is found, Emacs simply visits the file.
5506 With optional argument IN-EMACS, Emacs will visit the file.
5507 If the file does not exist, an error is thrown."
5508 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5509 (dfile (downcase file))
5510 ext cmd apps)
5511 (if (and (not (file-exists-p file))
5512 (not org-open-non-existing-files))
5513 (error "No such file: %s" file))
5514 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5515 (setq ext (match-string 1 dfile))
5516 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5517 (setq ext (match-string 1 dfile))))
5518 (setq apps (append org-file-apps (org-default-apps)))
5519 (if in-emacs
5520 (setq cmd 'emacs)
5521 (setq cmd (or (cdr (assoc ext apps))
5522 (cdr (assoc t apps)))))
5523 (cond
5524 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5525 (setq cmd (format cmd (concat "\"" file "\"")))
5526 (save-window-excursion
5527 (shell-command (concat cmd " & &"))))
5528 ((or (stringp cmd)
5529 (eq cmd 'emacs))
5530 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5531 (if line (goto-line line)))
5532 ((consp cmd)
5533 (eval cmd))
5534 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5535
5536 (defun org-default-apps ()
5537 "Return the default applications for this operating system."
5538 (cond
5539 ((eq system-type 'darwin)
5540 org-file-apps-defaults-macosx)
5541 ((eq system-type 'windows-nt)
5542 org-file-apps-defaults-windowsnt)
5543 (t org-file-apps-defaults-gnu)))
5544
5545 (defun org-expand-file-name (path)
5546 "Replace special path abbreviations and expand the file name."
5547 (expand-file-name path))
5548
5549
5550 (defvar org-insert-link-history nil
5551 "Minibuffer history for links inserted with `org-insert-link'.")
5552
5553 (defvar org-stored-links nil
5554 "Contains the links stored with `org-store-link'.")
5555
5556 ;;;###autoload
5557 (defun org-store-link (arg)
5558 "\\<org-mode-map>Store an org-link to the current location.
5559 This link can later be inserted into an org-buffer with
5560 \\[org-insert-link].
5561 For some link types, a prefix arg is interpreted:
5562 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5563 For file links, arg negates `org-line-numbers-in-file-links'."
5564 (interactive "P")
5565 (let (link cpltxt)
5566 (cond
5567
5568 ((eq major-mode 'bbdb-mode)
5569 (setq cpltxt (concat
5570 "bbdb:"
5571 (or (bbdb-record-name (bbdb-current-record))
5572 (bbdb-record-company (bbdb-current-record))))
5573 link (org-make-link cpltxt)))
5574
5575 ((eq major-mode 'calendar-mode)
5576 (let ((cd (calendar-cursor-to-date)))
5577 (setq link
5578 (format-time-string
5579 (car org-time-stamp-formats)
5580 (apply 'encode-time
5581 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5582 nil nil nil))))))
5583
5584 ((or (eq major-mode 'vm-summary-mode)
5585 (eq major-mode 'vm-presentation-mode))
5586 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5587 (vm-follow-summary-cursor)
5588 (save-excursion
5589 (vm-select-folder-buffer)
5590 (let* ((message (car vm-message-pointer))
5591 (folder (buffer-file-name))
5592 (subject (vm-su-subject message))
5593 (author (vm-su-full-name message))
5594 (message-id (vm-su-message-id message)))
5595 (setq folder (abbreviate-file-name folder))
5596 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5597 folder)
5598 (setq folder (replace-match "" t t folder)))
5599 (setq cpltxt (concat author " on: " subject))
5600 (setq link (concat cpltxt "\n "
5601 (org-make-link
5602 "vm:" folder "#" message-id))))))
5603
5604 ((eq major-mode 'wl-summary-mode)
5605 (let* ((msgnum (wl-summary-message-number))
5606 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5607 msgnum 'message-id))
5608 (wl-message-entity (elmo-msgdb-overview-get-entity
5609 msgnum (wl-summary-buffer-msgdb)))
5610 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5611 (subject "???")) ; FIXME: How to get subject of email?
5612 (setq cpltxt (concat author " on: " subject))
5613 (setq link (concat cpltxt "\n "
5614 (org-make-link
5615 "wl:" wl-summary-buffer-folder-name
5616 "#" message-id)))))
5617
5618 ((eq major-mode 'rmail-mode)
5619 (save-excursion
5620 (save-restriction
5621 (rmail-narrow-to-non-pruned-header)
5622 (let ((folder (buffer-file-name))
5623 (message-id (mail-fetch-field "message-id"))
5624 (author (mail-fetch-field "from"))
5625 (subject (mail-fetch-field "subject")))
5626 (setq cpltxt (concat author " on: " subject))
5627 (setq link (concat cpltxt "\n "
5628 (org-make-link
5629 "rmail:" folder "#" message-id)))))))
5630
5631 ((eq major-mode 'gnus-group-mode)
5632 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5633 (gnus-group-group-name)) ; version
5634 ((fboundp 'gnus-group-name)
5635 (gnus-group-name))
5636 (t "???"))))
5637 (setq cpltxt (concat
5638 (if (org-xor arg org-usenet-links-prefer-google)
5639 "http://groups.google.com/groups?group="
5640 "gnus:")
5641 group)
5642 link (org-make-link cpltxt))))
5643
5644 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5645 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5646 (gnus-summary-beginning-of-article)
5647 (let* ((group (car gnus-article-current))
5648 (article (cdr gnus-article-current))
5649 (header (gnus-summary-article-header article))
5650 (author (mail-header-from header))
5651 (message-id (mail-header-id header))
5652 (date (mail-header-date header))
5653 (subject (gnus-summary-subject-string)))
5654 (setq cpltxt (concat author " on: " subject))
5655 (if (org-xor arg org-usenet-links-prefer-google)
5656 (setq link
5657 (concat
5658 cpltxt "\n "
5659 (format "http://groups.google.com/groups?as_umsgid=%s"
5660 (org-fixup-message-id-for-http message-id))))
5661 (setq link (concat cpltxt "\n"
5662 (org-make-link
5663 "gnus:" group
5664 "#" (number-to-string article)))))))
5665
5666 ((eq major-mode 'w3-mode)
5667 (setq cpltxt (url-view-url t)
5668 link (org-make-link cpltxt)))
5669 ((eq major-mode 'w3m-mode)
5670 (setq cpltxt w3m-current-url
5671 link (org-make-link cpltxt)))
5672
5673 ((buffer-file-name)
5674 ;; Just link to this file here.
5675 (setq cpltxt (concat "file:"
5676 (abbreviate-file-name (buffer-file-name))))
5677 ;; Add the line number?
5678 (if (org-xor org-line-numbers-in-file-links arg)
5679 (setq cpltxt
5680 (concat cpltxt
5681 ":" (int-to-string
5682 (+ (if (bolp) 1 0) (count-lines
5683 (point-min) (point)))))))
5684 (setq link (org-make-link cpltxt)))
5685
5686 ((interactive-p)
5687 (error "Cannot link to a buffer which is not visiting a file"))
5688
5689 (t (setq link nil)))
5690
5691 (if (and (interactive-p) link)
5692 (progn
5693 (setq org-stored-links
5694 (cons (cons (or cpltxt link) link) org-stored-links))
5695 (message "Stored: %s" (or cpltxt link)))
5696 link)))
5697
5698 (defun org-make-link (&rest strings)
5699 "Concatenate STRINGS, format resulting string with `org-link-format'."
5700 (format org-link-format (apply 'concat strings)))
5701
5702 (defun org-xor (a b)
5703 "Exclusive or."
5704 (if a (not b) b))
5705
5706 (defun org-get-header (header)
5707 "Find a header field in the current buffer."
5708 (save-excursion
5709 (goto-char (point-min))
5710 (let ((case-fold-search t) s)
5711 (cond
5712 ((eq header 'from)
5713 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5714 (setq s (match-string 1)))
5715 (while (string-match "\"" s)
5716 (setq s (replace-match "" t t s)))
5717 (if (string-match "[<(].*" s)
5718 (setq s (replace-match "" t t s))))
5719 ((eq header 'message-id)
5720 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5721 (setq s (match-string 1))))
5722 ((eq header 'subject)
5723 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5724 (setq s (match-string 1)))))
5725 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5726 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5727 s)))
5728
5729
5730 (defun org-fixup-message-id-for-http (s)
5731 "Replace special characters in a message id, so it can be used in an http query."
5732 (while (string-match "<" s)
5733 (setq s (replace-match "%3C" t t s)))
5734 (while (string-match ">" s)
5735 (setq s (replace-match "%3E" t t s)))
5736 (while (string-match "@" s)
5737 (setq s (replace-match "%40" t t s)))
5738 s)
5739
5740 (defun org-insert-link (&optional complete-file)
5741 "Insert a link. At the prompt, enter the link.
5742
5743 Completion can be used to select a link previously stored with
5744 `org-store-link'. When the empty string is entered (i.e. if you just
5745 press RET at the prompt), the link defaults to the most recently
5746 stored link. As SPC triggers completion in the minibuffer, you need to
5747 use M-SPC or C-q SPC to force the insertion of a space character.
5748
5749 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5750 selected using completion. The path to the file will be relative to
5751 the current directory if the file is in the current directory or a
5752 subdirectory. Otherwise, the link will be the absolute path as
5753 completed in the minibuffer (i.e. normally ~/path/to/file).
5754
5755 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5756 is in the current directory or below."
5757 (interactive "P")
5758 (let ((link (if complete-file
5759 (read-file-name "File: ")
5760 (completing-read
5761 "Link: " org-stored-links nil nil nil
5762 org-insert-link-history
5763 (or (car (car org-stored-links))))))
5764 linktxt matched)
5765 (if (or (not link) (equal link ""))
5766 (error "No links available"))
5767 (if complete-file
5768 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5769 (cond
5770 ((equal complete-file '(16))
5771 (insert
5772 (org-make-link
5773 "file:" (abbreviate-file-name (expand-file-name link)))))
5774 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5775 (expand-file-name link))
5776 (insert
5777 (org-make-link
5778 "file:" (match-string 1 (expand-file-name link)))))
5779 (t (insert (org-make-link "file:" link)))))
5780 (setq linktxt (cdr (assoc link org-stored-links)))
5781 (if (not org-keep-stored-link-after-insertion)
5782 (setq org-stored-links (delq (assoc link org-stored-links)
5783 org-stored-links)))
5784 (if (not linktxt) (setq link (org-make-link link)))
5785 (let ((lines (org-split-string (or linktxt link) "\n")))
5786 (insert (car lines))
5787 (setq matched (string-match org-link-regexp (car lines)))
5788 (setq lines (cdr lines))
5789 (while lines
5790 (insert "\n")
5791 (if (save-excursion
5792 (beginning-of-line 0)
5793 (looking-at "[ \t]+\\S-"))
5794 (indent-relative))
5795 (setq matched (or matched
5796 (string-match org-link-regexp (car lines))))
5797 (insert (car lines))
5798 (setq lines (cdr lines))))
5799 (unless matched
5800 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5801
5802 ;;; Hooks for remember.el
5803 ;;;###autoload
5804 (defun org-remember-annotation ()
5805 "Return a link to the current location as an annotation for remember.el.
5806 If you are using Org-mode files as target for data storage with
5807 remember.el, then the annotations should include a link compatible with the
5808 conventions in Org-mode. This function returns such a link."
5809 (org-store-link nil))
5810
5811 (defconst org-remember-help
5812 "Select a destination location for the note.
5813 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5814 RET at beg-of-buf -> Append to file as level 2 headline
5815 RET on headline -> Store as sublevel entry to current headline
5816 <left>/<right> -> before/after current headline, same headings level")
5817
5818 ;;;###autoload
5819 (defun org-remember-handler ()
5820 "Store stuff from remember.el into an org file.
5821 First prompts for an org file. If the user just presses return, the value
5822 of `org-default-notes-file' is used.
5823 Then the command offers the headings tree of the selected file in order to
5824 file the text at a specific location.
5825 You can either immediately press RET to get the note appended to the
5826 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5827 find a better place. Then press RET or <left> or <right> in insert the note.
5828
5829 Key Cursor position Note gets inserted
5830 -----------------------------------------------------------------------------
5831 RET buffer-start as level 2 heading at end of file
5832 RET on headline as sublevel of the heading at cursor
5833 RET no heading at cursor position, level taken from context.
5834 Or use prefix arg to specify level manually.
5835 <left> on headline as same level, before current heading
5836 <right> on headline as same level, after current heading
5837
5838 So the fastest way to store the note is to press RET RET to append it to
5839 the default file. This way your current train of thought is not
5840 interrupted, in accordance with the principles of remember.el. But with
5841 little extra effort, you can push it directly to the correct location.
5842
5843 Before being stored away, the function ensures that the text has a
5844 headline, i.e. a first line that starts with a \"*\". If not, a headline
5845 is constructed from the current date and some additional data.
5846
5847 If the variable `org-adapt-indentation' is non-nil, the entire text is
5848 also indented so that it starts in the same column as the headline
5849 \(i.e. after the stars).
5850
5851 See also the variable `org-reverse-note-order'."
5852 (catch 'quit
5853 (let* ((txt (buffer-substring (point-min) (point-max)))
5854 (fastp current-prefix-arg)
5855 (file (if fastp org-default-notes-file (org-get-org-file)))
5856 (visiting (find-buffer-visiting file))
5857 (org-startup-with-deadline-check nil)
5858 (org-startup-folded nil)
5859 spos level indent reversed)
5860 ;; Modify text so that it becomes a nice subtree which can be inserted
5861 ;; into an org tree.
5862 (let* ((lines (split-string txt "\n"))
5863 (first (car lines))
5864 (lines (cdr lines)))
5865 (if (string-match "^\\*+" first)
5866 ;; Is already a headline
5867 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5868 -1) ?\ ))
5869 ;; We need to add a headline: Use time and first buffer line
5870 (setq lines (cons first lines)
5871 first (concat "* " (current-time-string)
5872 " (" (remember-buffer-desc) ")")
5873 indent " "))
5874 (if org-adapt-indentation
5875 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5876 (setq txt (concat first "\n"
5877 (mapconcat 'identity lines "\n"))))
5878 ;; Find the file
5879 (if (not visiting)
5880 (find-file-noselect file))
5881 (with-current-buffer (get-file-buffer file)
5882 (setq reversed (org-notes-order-reversed-p))
5883 (save-excursion
5884 (save-restriction
5885 (widen)
5886 ;; Ask the User for a location
5887 (setq spos (if fastp 1 (org-get-location
5888 (current-buffer)
5889 org-remember-help)))
5890 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5891 ; not handle this note
5892 (goto-char spos)
5893 (cond ((bobp)
5894 ;; Put it at the start or end, as level 2
5895 (save-restriction
5896 (widen)
5897 (goto-char (if reversed (point-min) (point-max)))
5898 (if (not (bolp)) (newline))
5899 (org-paste-subtree (or current-prefix-arg 2) txt)))
5900 ((and (org-on-heading-p nil) (not current-prefix-arg))
5901 ;; Put it below this entry, at the beg/end of the subtree
5902 (org-back-to-heading)
5903 (setq level (outline-level))
5904 (if reversed
5905 (outline-end-of-heading)
5906 (outline-end-of-subtree))
5907 (if (not (bolp)) (newline))
5908 (beginning-of-line 1)
5909 (org-paste-subtree (1+ level) txt))
5910 (t
5911 ;; Put it right there, with automatic level determined by
5912 ;; org-paste-subtree or from prefix arg
5913 (org-paste-subtree current-prefix-arg txt)))
5914 (when remember-save-after-remembering
5915 (save-buffer)
5916 (if (not visiting) (kill-buffer (current-buffer)))))))))
5917 t) ;; return t to indicate that we took care of this note.
5918
5919 (defun org-get-org-file ()
5920 "Read a filename, with default directory `org-directory'."
5921 (let ((default (or org-default-notes-file remember-data-file)))
5922 (read-file-name (format "File name [%s]: " default)
5923 (file-name-as-directory org-directory)
5924 default)))
5925
5926 (defun org-notes-order-reversed-p ()
5927 "Check if the current file should receive notes in reversed order."
5928 (cond
5929 ((not org-reverse-note-order) nil)
5930 ((eq t org-reverse-note-order) t)
5931 ((not (listp org-reverse-note-order)) nil)
5932 (t (catch 'exit
5933 (let ((all org-reverse-note-order)
5934 entry)
5935 (while (setq entry (pop all))
5936 (if (string-match (car entry) (buffer-file-name))
5937 (throw 'exit (cdr entry))))
5938 nil)))))
5939
5940 ;;; Tables
5941
5942 ;; Watch out: Here we are talking about two different kind of tables.
5943 ;; Most of the code is for the tables created with the Org-mode table editor.
5944 ;; Sometimes, we talk about tables created and edited with the table.el
5945 ;; Emacs package. We call the former org-type tables, and the latter
5946 ;; table.el-type tables.
5947
5948
5949 (defun org-before-change-function (beg end)
5950 "Every change indicates that a table might need an update."
5951 (setq org-table-may-need-update t))
5952
5953 (defconst org-table-line-regexp "^[ \t]*|"
5954 "Detects an org-type table line.")
5955 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5956 "Detects an org-type table line.")
5957 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5958 "Detects a table line marked for automatic recalculation.")
5959 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5960 "Detects a table line marked for automatic recalculation.")
5961 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5962 "Detects a table line marked for automatic recalculation.")
5963 (defconst org-table-hline-regexp "^[ \t]*|-"
5964 "Detects an org-type table hline.")
5965 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5966 "Detects a table-type table hline.")
5967 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5968 "Detects an org-type or table-type table.")
5969 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5970 "Searching from within a table (any type) this finds the first line
5971 outside the table.")
5972 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5973 "Searching from within a table (any type) this finds the first line
5974 outside the table.")
5975
5976 (defun org-table-create-with-table.el ()
5977 "Use the table.el package to insert a new table.
5978 If there is already a table at point, convert between Org-mode tables
5979 and table.el tables."
5980 (interactive)
5981 (require 'table)
5982 (cond
5983 ((org-at-table.el-p)
5984 (if (y-or-n-p "Convert table to Org-mode table? ")
5985 (org-table-convert)))
5986 ((org-at-table-p)
5987 (if (y-or-n-p "Convert table to table.el table? ")
5988 (org-table-convert)))
5989 (t (call-interactively 'table-insert))))
5990
5991 (defun org-table-create (&optional size)
5992 "Query for a size and insert a table skeleton.
5993 SIZE is a string Columns x Rows like for example \"3x2\"."
5994 (interactive "P")
5995 (unless size
5996 (setq size (read-string
5997 (concat "Table size Columns x Rows [e.g. "
5998 org-table-default-size "]: ")
5999 "" nil org-table-default-size)))
6000
6001 (let* ((pos (point))
6002 (indent (make-string (current-column) ?\ ))
6003 (split (org-split-string size " *x *"))
6004 (rows (string-to-number (nth 1 split)))
6005 (columns (string-to-number (car split)))
6006 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6007 "\n")))
6008 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6009 (point-at-bol) (point)))
6010 (beginning-of-line 1)
6011 (newline))
6012 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6013 (dotimes (i rows) (insert line))
6014 (goto-char pos)
6015 (if (> rows 1)
6016 ;; Insert a hline after the first row.
6017 (progn
6018 (end-of-line 1)
6019 (insert "\n|-")
6020 (goto-char pos)))
6021 (org-table-align)))
6022
6023 (defun org-table-convert-region (beg0 end0 nspace)
6024 "Convert region to a table.
6025 The region goes from BEG0 to END0, but these borders will be moved
6026 slightly, to make sure a beginning of line in the first line is included.
6027 When NSPACE is non-nil, it indicates the minimum number of spaces that
6028 separate columns (default: just one space)"
6029 (let* ((beg (min beg0 end0))
6030 (end (max beg0 end0))
6031 (tabsep t)
6032 re)
6033 (goto-char beg)
6034 (beginning-of-line 1)
6035 (setq beg (move-marker (make-marker) (point)))
6036 (goto-char end)
6037 (if (bolp) (backward-char 1) (end-of-line 1))
6038 (setq end (move-marker (make-marker) (point)))
6039 ;; Lets see if this is tab-separated material. If every nonempty line
6040 ;; contains a tab, we will assume that it is tab-separated material
6041 (if nspace
6042 (setq tabsep nil)
6043 (goto-char beg)
6044 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6045 (if nspace (setq tabsep nil))
6046 (if tabsep
6047 (setq re "^\\|\t")
6048 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6049 (max 1 (prefix-numeric-value nspace)))))
6050 (goto-char beg)
6051 (while (re-search-forward re end t)
6052 (replace-match "|" t t))
6053 (goto-char beg)
6054 (insert " ")
6055 (org-table-align)))
6056
6057 (defun org-table-import (file arg)
6058 "Import FILE as a table.
6059 The file is assumed to be tab-separated. Such files can be produced by most
6060 spreadsheet and database applications. If no tabs (at least one per line)
6061 are found, lines will be split on whitespace into fields."
6062 (interactive "f\nP")
6063 (or (bolp) (newline))
6064 (let ((beg (point))
6065 (pm (point-max)))
6066 (insert-file-contents file)
6067 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6068
6069 (defun org-table-export ()
6070 "Export table as a tab-separated file.
6071 Such a file can be imported into a spreadsheet program like Excel."
6072 (interactive)
6073 (let* ((beg (org-table-begin))
6074 (end (org-table-end))
6075 (table (buffer-substring beg end))
6076 (file (read-file-name "Export table to: "))
6077 buf)
6078 (unless (or (not (file-exists-p file))
6079 (y-or-n-p (format "Overwrite file %s? " file)))
6080 (error "Abort"))
6081 (with-current-buffer (find-file-noselect file)
6082 (setq buf (current-buffer))
6083 (erase-buffer)
6084 (fundamental-mode)
6085 (insert table)
6086 (goto-char (point-min))
6087 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6088 (replace-match "" t t)
6089 (end-of-line 1))
6090 (goto-char (point-min))
6091 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6092 (replace-match "" t t)
6093 (goto-char (min (1+ (point)) (point-max))))
6094 (goto-char (point-min))
6095 (while (re-search-forward "^-[-+]*$" nil t)
6096 (replace-match "")
6097 (if (looking-at "\n")
6098 (delete-char 1)))
6099 (goto-char (point-min))
6100 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6101 (replace-match "\t" t t))
6102 (save-buffer))
6103 (kill-buffer buf)))
6104
6105 (defvar org-table-aligned-begin-marker (make-marker)
6106 "Marker at the beginning of the table last aligned.
6107 Used to check if cursor still is in that table, to minimize realignment.")
6108 (defvar org-table-aligned-end-marker (make-marker)
6109 "Marker at the end of the table last aligned.
6110 Used to check if cursor still is in that table, to minimize realignment.")
6111 (defvar org-table-last-alignment nil
6112 "List of flags for flushright alignment, from the last re-alignment.
6113 This is being used to correctly align a single field after TAB or RET.")
6114 ;; FIXME: The following is currently not used.
6115 (defvar org-table-last-column-widths nil
6116 "List of max width of fields in each column.
6117 This is being used to correctly align a single field after TAB or RET.")
6118
6119 (defvar org-last-recalc-line nil)
6120
6121 (defun org-table-align ()
6122 "Align the table at point by aligning all vertical bars."
6123 (interactive)
6124 ;; (message "align") (sit-for 2)
6125 (let* (
6126 ;; Limits of table
6127 (beg (org-table-begin))
6128 (end (org-table-end))
6129 ;; Current cursor position
6130 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6131 (colpos (org-table-current-column))
6132 (winstart (window-start))
6133 text lines (new "") lengths l typenums ty fields maxfields i
6134 column
6135 (indent "") cnt frac
6136 rfmt hfmt
6137 (spaces (if (org-in-invisibility-spec-p '(org-table))
6138 org-table-spaces-around-invisible-separators
6139 org-table-spaces-around-separators))
6140 (sp1 (car spaces))
6141 (sp2 (cdr spaces))
6142 (rfmt1 (concat
6143 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6144 (hfmt1 (concat
6145 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6146 emptystrings)
6147 (untabify beg end)
6148 ;; (message "Aligning table...")
6149 ;; Get the rows
6150 (setq lines (org-split-string
6151 (buffer-substring-no-properties beg end) "\n"))
6152 ;; Store the indentation of the first line
6153 (if (string-match "^ *" (car lines))
6154 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6155 ;; Mark the hlines
6156 (setq lines (mapcar (lambda (l)
6157 (if (string-match "^ *|-" l)
6158 nil
6159 (if (string-match "[ \t]+$" l)
6160 (substring l 0 (match-beginning 0))
6161 l)))
6162 lines))
6163 ;; Get the data fields
6164 (setq fields (mapcar
6165 (lambda (l)
6166 (org-split-string l " *| *"))
6167 (delq nil (copy-sequence lines))))
6168 ;; How many fields in the longest line?
6169 (condition-case nil
6170 (setq maxfields (apply 'max (mapcar 'length fields)))
6171 (error
6172 (kill-region beg end)
6173 (org-table-create org-table-default-size)
6174 (error "Empty table - created default table")))
6175 ;; A list of empty string to fill any short rows on output
6176 (setq emptystrings (make-list maxfields ""))
6177 ;; Get the maximum length of a field and the most common datatype
6178 ;; for each column
6179 (setq i -1)
6180 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6181 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6182 ;; maximum length
6183 (push (apply 'max 1 (mapcar 'length column)) lengths)
6184 ;; compute the fraction stepwise, ignoring empty fields
6185 (setq cnt 0 frac 0.0)
6186 (mapcar
6187 (lambda (x)
6188 (if (equal x "")
6189 nil
6190 (setq frac ( / (+ (* frac cnt)
6191 (if (string-match org-table-number-regexp x) 1 0))
6192 (setq cnt (1+ cnt))))))
6193 column)
6194 (push (>= frac org-table-number-fraction) typenums))
6195 (setq lengths (nreverse lengths)
6196 typenums (nreverse typenums))
6197 (setq org-table-last-alignment typenums
6198 org-table-last-column-widths lengths)
6199 ;; Compute the formats needed for output of the table
6200 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6201 (while (setq l (pop lengths))
6202 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6203 (setq rfmt (concat rfmt (format rfmt1 ty l))
6204 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6205 (setq rfmt (concat rfmt "\n")
6206 hfmt (concat (substring hfmt 0 -1) "|\n"))
6207 ;; Produce the new table
6208 ;;(while lines
6209 ;; (setq l (pop lines))
6210 ;; (if l
6211 ;; (setq new (concat new (apply 'format rfmt
6212 ;; (append (pop fields) emptystrings))))
6213 ;; (setq new (concat new hfmt))))
6214 (setq new (mapconcat
6215 (lambda (l)
6216 (if l (apply 'format rfmt
6217 (append (pop fields) emptystrings))
6218 hfmt))
6219 lines ""))
6220 ;; Replace the old one
6221 (delete-region beg end)
6222 (move-marker end nil)
6223 (move-marker org-table-aligned-begin-marker (point))
6224 (insert new)
6225 (move-marker org-table-aligned-end-marker (point))
6226 ;; Try to move to the old location (approximately)
6227 (goto-line linepos)
6228 (set-window-start (selected-window) winstart 'noforce)
6229 (org-table-goto-column colpos)
6230 (setq org-table-may-need-update nil)
6231 (if (org-in-invisibility-spec-p '(org-table))
6232 (org-table-add-invisible-to-vertical-lines))
6233 ))
6234
6235 (defun org-table-begin (&optional table-type)
6236 "Find the beginning of the table and return its position.
6237 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6238 (save-excursion
6239 (if (not (re-search-backward
6240 (if table-type org-table-any-border-regexp
6241 org-table-border-regexp)
6242 nil t))
6243 (error "Can't find beginning of table")
6244 (goto-char (match-beginning 0))
6245 (beginning-of-line 2)
6246 (point))))
6247
6248 (defun org-table-end (&optional table-type)
6249 "Find the end of the table and return its position.
6250 With argument TABLE-TYPE, go to the end of a table.el-type table."
6251 (save-excursion
6252 (if (not (re-search-forward
6253 (if table-type org-table-any-border-regexp
6254 org-table-border-regexp)
6255 nil t))
6256 (goto-char (point-max))
6257 (goto-char (match-beginning 0)))
6258 (point-marker)))
6259
6260 (defun org-table-justify-field-maybe (&optional new)
6261 "Justify the current field, text to left, number to right.
6262 Optional argument NEW may specify text to replace the current field content."
6263 (cond
6264 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6265 ((org-at-table-hline-p)
6266 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6267 ;; (setq org-table-may-need-update t)
6268 )
6269 ((and (not new)
6270 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6271 (current-buffer)))
6272 (< (point) org-table-aligned-begin-marker)
6273 (>= (point) org-table-aligned-end-marker)))
6274 ;; This is not the same table, force a full re-align
6275 (setq org-table-may-need-update t))
6276 (t ;; realign the current field, based on previous full realign
6277 (let* ((pos (point)) s
6278 (col (org-table-current-column))
6279 (num (nth (1- col) org-table-last-alignment))
6280 l f n o e)
6281 (when (> col 0)
6282 (skip-chars-backward "^|\n")
6283 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6284 (progn
6285 (setq s (match-string 1)
6286 o (match-string 0)
6287 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6288 e (not (= (match-beginning 2) (match-end 2))))
6289 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6290 l (if e "|" (setq org-table-may-need-update t) ""))
6291 n (format f s t t))
6292 (if new
6293 (if (<= (length new) l)
6294 (setq n (format f new t t)) ;; FIXME: why t t?????
6295 (setq n (concat new "|") org-table-may-need-update t)))
6296 (or (equal n o)
6297 (let (org-table-may-need-update)
6298 (replace-match n))))
6299 (setq org-table-may-need-update t))
6300 (goto-char pos))))))
6301
6302 (defun org-table-next-field ()
6303 "Go to the next field in the current table.
6304 Before doing so, re-align the table if necessary."
6305 (interactive)
6306 (org-table-maybe-eval-formula)
6307 (org-table-maybe-recalculate-line)
6308 (if (and org-table-automatic-realign
6309 org-table-may-need-update)
6310 (org-table-align))
6311 (if (org-at-table-hline-p)
6312 (end-of-line 1))
6313 (condition-case nil
6314 (progn
6315 (re-search-forward "|" (org-table-end))
6316 (if (looking-at "[ \t]*$")
6317 (re-search-forward "|" (org-table-end)))
6318 (if (looking-at "-")
6319 (progn
6320 (beginning-of-line 0)
6321 (org-table-insert-row 'below))
6322 (if (looking-at " ") (forward-char 1))))
6323 (error
6324 (org-table-insert-row 'below))))
6325
6326 (defun org-table-previous-field ()
6327 "Go to the previous field in the table.
6328 Before doing so, re-align the table if necessary."
6329 (interactive)
6330 (org-table-justify-field-maybe)
6331 (org-table-maybe-recalculate-line)
6332 (if (and org-table-automatic-realign
6333 org-table-may-need-update)
6334 (org-table-align))
6335 (if (org-at-table-hline-p)
6336 (end-of-line 1))
6337 (re-search-backward "|" (org-table-begin))
6338 (re-search-backward "|" (org-table-begin))
6339 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6340 (re-search-backward "|" (org-table-begin)))
6341 (if (looking-at "| ?")
6342 (goto-char (match-end 0))))
6343
6344 (defun org-table-next-row ()
6345 "Go to the next row (same column) in the current table.
6346 Before doing so, re-align the table if necessary."
6347 (interactive)
6348 (org-table-maybe-eval-formula)
6349 (org-table-maybe-recalculate-line)
6350 (if (or (looking-at "[ \t]*$")
6351 (save-excursion (skip-chars-backward " \t") (bolp)))
6352 (newline)
6353 (if (and org-table-automatic-realign
6354 org-table-may-need-update)
6355 (org-table-align))
6356 (let ((col (org-table-current-column)))
6357 (beginning-of-line 2)
6358 (if (or (not (org-at-table-p))
6359 (org-at-table-hline-p))
6360 (progn
6361 (beginning-of-line 0)
6362 (org-table-insert-row 'below)))
6363 (org-table-goto-column col)
6364 (skip-chars-backward "^|\n\r")
6365 (if (looking-at " ") (forward-char 1)))))
6366
6367 (defun org-table-copy-down (n)
6368 "Copy a field down in the current column.
6369 If the field at the cursor is empty, copy into it the content of the nearest
6370 non-empty field above. With argument N, use the Nth non-empty field.
6371 If the current field is not empty, it is copied down to the next row, and
6372 the cursor is moved with it. Therefore, repeating this command causes the
6373 column to be filled row-by-row.
6374 If the variable `org-table-copy-increment' is non-nil and the field is an
6375 integer, it will be incremented while copying."
6376 (interactive "p")
6377 (let* ((colpos (org-table-current-column))
6378 (field (org-table-get-field))
6379 (non-empty (string-match "[^ \t]" field))
6380 (beg (org-table-begin))
6381 txt)
6382 (org-table-check-inside-data-field)
6383 (if non-empty
6384 (progn
6385 (setq txt (org-trim field))
6386 (org-table-next-row)
6387 (org-table-blank-field))
6388 (save-excursion
6389 (setq txt
6390 (catch 'exit
6391 (while (progn (beginning-of-line 1)
6392 (re-search-backward org-table-dataline-regexp
6393 beg t))
6394 (org-table-goto-column colpos t)
6395 (if (and (looking-at
6396 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6397 (= (setq n (1- n)) 0))
6398 (throw 'exit (match-string 1))))))))
6399 (if txt
6400 (progn
6401 (if (and org-table-copy-increment
6402 (string-match "^[0-9]+$" txt))
6403 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6404 (insert txt)
6405 (org-table-maybe-recalculate-line)
6406 (org-table-align))
6407 (error "No non-empty field found"))))
6408
6409 (defun org-table-check-inside-data-field ()
6410 "Is point inside a table data field?
6411 I.e. not on a hline or before the first or after the last column?
6412 This actually throws an error, so it aborts the current command."
6413 (if (or (not (org-at-table-p))
6414 (= (org-table-current-column) 0)
6415 (org-at-table-hline-p)
6416 (looking-at "[ \t]*$"))
6417 (error "Not in table data field")))
6418
6419 (defvar org-table-clip nil
6420 "Clipboard for table regions.")
6421
6422 (defun org-table-blank-field ()
6423 "Blank the current table field or active region."
6424 (interactive)
6425 (org-table-check-inside-data-field)
6426 (if (and (interactive-p) (org-region-active-p))
6427 (let (org-table-clip)
6428 (org-table-cut-region (region-beginning) (region-end)))
6429 (skip-chars-backward "^|")
6430 (backward-char 1)
6431 (if (looking-at "|[^|\n]+")
6432 (let* ((pos (match-beginning 0))
6433 (match (match-string 0))
6434 (len (length match)))
6435 (replace-match (concat "|" (make-string (1- len) ?\ )))
6436 (goto-char (+ 2 pos))
6437 (substring match 1)))))
6438
6439 (defun org-table-get-field (&optional n replace)
6440 "Return the value of the field in column N of current row.
6441 N defaults to current field.
6442 If REPLACE is a string, replace field with this value. The return value
6443 is always the old value."
6444 (and n (org-table-goto-column n))
6445 (skip-chars-backward "^|\n")
6446 (backward-char 1)
6447 (if (looking-at "|[^|\r\n]*")
6448 (let* ((pos (match-beginning 0))
6449 (val (buffer-substring (1+ pos) (match-end 0))))
6450 (if replace
6451 (replace-match (concat "|" replace)))
6452 (goto-char (min (point-at-eol) (+ 2 pos)))
6453 val)
6454 (forward-char 1) ""))
6455
6456 (defun org-table-current-column ()
6457 "Find out which column we are in.
6458 When called interactively, column is also displayed in echo area."
6459 (interactive)
6460 (if (interactive-p) (org-table-check-inside-data-field))
6461 (save-excursion
6462 (let ((cnt 0) (pos (point)))
6463 (beginning-of-line 1)
6464 (while (search-forward "|" pos t)
6465 (setq cnt (1+ cnt)))
6466 (if (interactive-p) (message "This is table column %d" cnt))
6467 cnt)))
6468
6469 (defun org-table-goto-column (n &optional on-delim force)
6470 "Move the cursor to the Nth column in the current table line.
6471 With optional argument ON-DELIM, stop with point before the left delimiter
6472 of the field.
6473 If there are less than N fields, just go to after the last delimiter.
6474 However, when FORCE is non-nil, create new columns if necessary."
6475 (let ((pos (point-at-eol)))
6476 (beginning-of-line 1)
6477 (when (> n 0)
6478 (while (and (> (setq n (1- n)) -1)
6479 (or (search-forward "|" pos t)
6480 (and force
6481 (progn (end-of-line 1)
6482 (skip-chars-backward "^|")
6483 (insert " | "))))))
6484 ; (backward-char 2) t)))))
6485 (when (and force (not (looking-at ".*|")))
6486 (save-excursion (end-of-line 1) (insert " | ")))
6487 (if on-delim
6488 (backward-char 1)
6489 (if (looking-at " ") (forward-char 1))))))
6490
6491 (defun org-at-table-p (&optional table-type)
6492 "Return t if the cursor is inside an org-type table.
6493 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6494 (if org-enable-table-editor
6495 (save-excursion
6496 (beginning-of-line 1)
6497 (looking-at (if table-type org-table-any-line-regexp
6498 org-table-line-regexp)))
6499 nil))
6500
6501 (defun org-table-recognize-table.el ()
6502 "If there is a table.el table nearby, recognize it and move into it."
6503 (if org-table-tab-recognizes-table.el
6504 (if (org-at-table.el-p)
6505 (progn
6506 (beginning-of-line 1)
6507 (if (looking-at org-table-dataline-regexp)
6508 nil
6509 (if (looking-at org-table1-hline-regexp)
6510 (progn
6511 (beginning-of-line 2)
6512 (if (looking-at org-table-any-border-regexp)
6513 (beginning-of-line -1)))))
6514 (if (re-search-forward "|" (org-table-end t) t)
6515 (progn
6516 (require 'table)
6517 (if (table--at-cell-p (point))
6518 t
6519 (message "recognizing table.el table...")
6520 (table-recognize-table)
6521 (message "recognizing table.el table...done")))
6522 (error "This should not happen..."))
6523 t)
6524 nil)
6525 nil))
6526
6527 (defun org-at-table.el-p ()
6528 "Return t if the cursor is inside a table.el-type table."
6529 (save-excursion
6530 (if (org-at-table-p 'any)
6531 (progn
6532 (goto-char (org-table-begin 'any))
6533 (looking-at org-table1-hline-regexp))
6534 nil)))
6535
6536 (defun org-at-table-hline-p ()
6537 "Return t if the cursor is inside a hline in a table."
6538 (if org-enable-table-editor
6539 (save-excursion
6540 (beginning-of-line 1)
6541 (looking-at org-table-hline-regexp))
6542 nil))
6543
6544 (defun org-table-insert-column ()
6545 "Insert a new column into the table."
6546 (interactive)
6547 (if (not (org-at-table-p))
6548 (error "Not at a table"))
6549 (org-table-find-dataline)
6550 (let* ((col (max 1 (org-table-current-column)))
6551 (beg (org-table-begin))
6552 (end (org-table-end))
6553 ;; Current cursor position
6554 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6555 (colpos col))
6556 (goto-char beg)
6557 (while (< (point) end)
6558 (if (org-at-table-hline-p)
6559 nil
6560 (org-table-goto-column col t)
6561 (insert "| "))
6562 (beginning-of-line 2))
6563 (move-marker end nil)
6564 (goto-line linepos)
6565 (org-table-goto-column colpos)
6566 (org-table-align)
6567 (org-table-modify-formulas 'insert col)))
6568
6569 (defun org-table-find-dataline ()
6570 "Find a dataline in the current table, which is needed for column commands."
6571 (if (and (org-at-table-p)
6572 (not (org-at-table-hline-p)))
6573 t
6574 (let ((col (current-column))
6575 (end (org-table-end)))
6576 (move-to-column col)
6577 (while (and (< (point) end)
6578 (or (not (= (current-column) col))
6579 (org-at-table-hline-p)))
6580 (beginning-of-line 2)
6581 (move-to-column col))
6582 (if (and (org-at-table-p)
6583 (not (org-at-table-hline-p)))
6584 t
6585 (error
6586 "Please position cursor in a data line for column operations")))))
6587
6588 (defun org-table-delete-column ()
6589 "Delete a column into the table."
6590 (interactive)
6591 (if (not (org-at-table-p))
6592 (error "Not at a table"))
6593 (org-table-find-dataline)
6594 (org-table-check-inside-data-field)
6595 (let* ((col (org-table-current-column))
6596 (beg (org-table-begin))
6597 (end (org-table-end))
6598 ;; Current cursor position
6599 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6600 (colpos col))
6601 (goto-char beg)
6602 (while (< (point) end)
6603 (if (org-at-table-hline-p)
6604 nil
6605 (org-table-goto-column col t)
6606 (and (looking-at "|[^|\n]+|")
6607 (replace-match "|")))
6608 (beginning-of-line 2))
6609 (move-marker end nil)
6610 (goto-line linepos)
6611 (org-table-goto-column colpos)
6612 (org-table-align)
6613 (org-table-modify-formulas 'remove col)))
6614
6615 (defun org-table-move-column-right ()
6616 "Move column to the right."
6617 (interactive)
6618 (org-table-move-column nil))
6619 (defun org-table-move-column-left ()
6620 "Move column to the left."
6621 (interactive)
6622 (org-table-move-column 'left))
6623
6624 (defun org-table-move-column (&optional left)
6625 "Move the current column to the right. With arg LEFT, move to the left."
6626 (interactive "P")
6627 (if (not (org-at-table-p))
6628 (error "Not at a table"))
6629 (org-table-find-dataline)
6630 (org-table-check-inside-data-field)
6631 (let* ((col (org-table-current-column))
6632 (col1 (if left (1- col) col))
6633 (beg (org-table-begin))
6634 (end (org-table-end))
6635 ;; Current cursor position
6636 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6637 (colpos (if left (1- col) (1+ col))))
6638 (if (and left (= col 1))
6639 (error "Cannot move column further left"))
6640 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6641 (error "Cannot move column further right"))
6642 (goto-char beg)
6643 (while (< (point) end)
6644 (if (org-at-table-hline-p)
6645 nil
6646 (org-table-goto-column col1 t)
6647 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6648 (replace-match "|\\2|\\1|")))
6649 (beginning-of-line 2))
6650 (move-marker end nil)
6651 (goto-line linepos)
6652 (org-table-goto-column colpos)
6653 (org-table-align)
6654 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6655
6656 (defun org-table-move-row-down ()
6657 "move table row down."
6658 (interactive)
6659 (org-table-move-row nil))
6660 (defun org-table-move-row-up ()
6661 "move table row up."
6662 (interactive)
6663 (org-table-move-row 'up))
6664
6665 (defun org-table-move-row (&optional up)
6666 "Move the current table line down. With arg UP, move it up."
6667 (interactive "P")
6668 (let ((col (current-column))
6669 (pos (point))
6670 (tonew (if up 0 2))
6671 txt)
6672 (beginning-of-line tonew)
6673 (if (not (org-at-table-p))
6674 (progn
6675 (goto-char pos)
6676 (error "Cannot move row further")))
6677 (goto-char pos)
6678 (beginning-of-line 1)
6679 (setq pos (point))
6680 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6681 (delete-region (point) (1+ (point-at-eol)))
6682 (beginning-of-line tonew)
6683 (insert txt)
6684 (beginning-of-line 0)
6685 (move-to-column col)))
6686
6687 (defun org-table-insert-row (&optional arg)
6688 "Insert a new row above the current line into the table.
6689 With prefix ARG, insert below the current line."
6690 (interactive "P")
6691 (if (not (org-at-table-p))
6692 (error "Not at a table"))
6693 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6694 new)
6695 (if (string-match "^[ \t]*|-" line)
6696 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6697 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6698 ;; Fix the first field if necessary
6699 (setq new (concat new))
6700 (if (string-match "^[ \t]*| *[#$] *|" line)
6701 (setq new (replace-match (match-string 0 line) t t new)))
6702 (beginning-of-line (if arg 2 1))
6703 (let (org-table-may-need-update)
6704 (insert-before-markers new)
6705 (insert-before-markers "\n"))
6706 (beginning-of-line 0)
6707 (re-search-forward "| ?" (point-at-eol) t)
6708 (and org-table-may-need-update (org-table-align))))
6709
6710 (defun org-table-insert-hline (&optional arg)
6711 "Insert a horizontal-line below the current line into the table.
6712 With prefix ARG, insert above the current line."
6713 (interactive "P")
6714 (if (not (org-at-table-p))
6715 (error "Not at a table"))
6716 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6717 (col (current-column))
6718 start)
6719 (if (string-match "^[ \t]*|-" line)
6720 (setq line
6721 (mapcar (lambda (x) (if (member x '(?| ?+))
6722 (prog1 (if start ?+ ?|) (setq start t))
6723 (if start ?- ?\ )))
6724 line))
6725 (setq line
6726 (mapcar (lambda (x) (if (equal x ?|)
6727 (prog1 (if start ?+ ?|) (setq start t))
6728 (if start ?- ?\ )))
6729 line)))
6730 (beginning-of-line (if arg 1 2))
6731 (apply 'insert line)
6732 (if (equal (char-before (point)) ?+)
6733 (progn (backward-delete-char 1) (insert "|")))
6734 (insert "\n")
6735 (beginning-of-line 0)
6736 (move-to-column col)))
6737
6738 (defun org-table-kill-row ()
6739 "Delete the current row or horizontal line from the table."
6740 (interactive)
6741 (if (not (org-at-table-p))
6742 (error "Not at a table"))
6743 (let ((col (current-column)))
6744 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6745 (if (not (org-at-table-p)) (beginning-of-line 0))
6746 (move-to-column col)))
6747
6748
6749 (defun org-table-cut-region (beg end)
6750 "Copy region in table to the clipboard and blank all relevant fields."
6751 (interactive "r")
6752 (org-table-copy-region beg end 'cut))
6753
6754 (defun org-table-copy-region (beg end &optional cut)
6755 "Copy rectangular region in table to clipboard.
6756 A special clipboard is used which can only be accessed
6757 with `org-table-paste-rectangle'"
6758 (interactive "rP")
6759 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6760 region cols
6761 (rpl (if cut " " nil)))
6762 (goto-char beg)
6763 (org-table-check-inside-data-field)
6764 (setq l01 (count-lines (point-min) (point))
6765 c01 (org-table-current-column))
6766 (goto-char end)
6767 (org-table-check-inside-data-field)
6768 (setq l02 (count-lines (point-min) (point))
6769 c02 (org-table-current-column))
6770 (setq l1 (min l01 l02) l2 (max l01 l02)
6771 c1 (min c01 c02) c2 (max c01 c02))
6772 (catch 'exit
6773 (while t
6774 (catch 'nextline
6775 (if (> l1 l2) (throw 'exit t))
6776 (goto-line l1)
6777 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6778 (setq cols nil ic1 c1 ic2 c2)
6779 (while (< ic1 (1+ ic2))
6780 (push (org-table-get-field ic1 rpl) cols)
6781 (setq ic1 (1+ ic1)))
6782 (push (nreverse cols) region)
6783 (setq l1 (1+ l1)))))
6784 (setq org-table-clip (nreverse region))
6785 (if cut (org-table-align))
6786 org-table-clip))
6787
6788 (defun org-table-paste-rectangle ()
6789 "Paste a rectangular region into a table.
6790 The upper right corner ends up in the current field. All involved fields
6791 will be overwritten. If the rectangle does not fit into the present table,
6792 the table is enlarged as needed. The process ignores horizontal separator
6793 lines."
6794 (interactive)
6795 (unless (and org-table-clip (listp org-table-clip))
6796 (error "First cut/copy a region to paste!"))
6797 (org-table-check-inside-data-field)
6798 (let* ((clip org-table-clip)
6799 (line (count-lines (point-min) (point)))
6800 (col (org-table-current-column))
6801 (org-enable-table-editor t)
6802 (org-table-automatic-realign nil)
6803 c cols field)
6804 (while (setq cols (pop clip))
6805 (while (org-at-table-hline-p) (beginning-of-line 2))
6806 (if (not (org-at-table-p))
6807 (progn (end-of-line 0) (org-table-next-field)))
6808 (setq c col)
6809 (while (setq field (pop cols))
6810 (org-table-goto-column c nil 'force)
6811 (org-table-get-field nil field)
6812 (setq c (1+ c)))
6813 (beginning-of-line 2))
6814 (goto-line line)
6815 (org-table-goto-column col)
6816 (org-table-align)))
6817
6818 (defun org-table-convert ()
6819 "Convert from `org-mode' table to table.el and back.
6820 Obviously, this only works within limits. When an Org-mode table is
6821 converted to table.el, all horizontal separator lines get lost, because
6822 table.el uses these as cell boundaries and has no notion of horizontal lines.
6823 A table.el table can be converted to an Org-mode table only if it does not
6824 do row or column spanning. Multiline cells will become multiple cells.
6825 Beware, Org-mode does not test if the table can be successfully converted - it
6826 blindly applies a recipe that works for simple tables."
6827 (interactive)
6828 (require 'table)
6829 (if (org-at-table.el-p)
6830 ;; convert to Org-mode table
6831 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6832 (end (move-marker (make-marker) (org-table-end t))))
6833 (table-unrecognize-region beg end)
6834 (goto-char beg)
6835 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6836 (replace-match ""))
6837 (goto-char beg))
6838 (if (org-at-table-p)
6839 ;; convert to table.el table
6840 (let ((beg (move-marker (make-marker) (org-table-begin)))
6841 (end (move-marker (make-marker) (org-table-end))))
6842 ;; first, get rid of all horizontal lines
6843 (goto-char beg)
6844 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6845 (replace-match ""))
6846 ;; insert a hline before first
6847 (goto-char beg)
6848 (org-table-insert-hline 'above)
6849 ;; insert a hline after each line
6850 (while (progn (beginning-of-line 2) (< (point) end))
6851 (org-table-insert-hline))
6852 (goto-char beg)
6853 (setq end (move-marker end (org-table-end)))
6854 ;; replace "+" at beginning and ending of hlines
6855 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6856 (replace-match "\\1+-"))
6857 (goto-char beg)
6858 (while (re-search-forward "-|[ \t]*$" end t)
6859 (replace-match "-+"))
6860 (goto-char beg)))))
6861
6862 (defun org-table-wrap-region (arg)
6863 "Wrap several fields in a column like a paragraph.
6864 This is useful if you'd like to spread the contents of a field over several
6865 lines, in order to keep the table compact.
6866
6867 If there is an active region, and both point and mark are in the same column,
6868 the text in the column is wrapped to minimum width for the given number of
6869 lines. Generally, this makes the table more compact. A prefix ARG may be
6870 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6871 formats the selected text to two lines. If the region was longer than 2
6872 lines, the remaining lines remain empty. A negative prefix argument reduces
6873 the current number of lines by that amount. The wrapped text is pasted back
6874 into the table. If you formatted it to more lines than it was before, fields
6875 further down in the table get overwritten - so you might need to make space in
6876 the table first.
6877
6878 If there is no region, the current field is split at the cursor position and
6879 the text fragment to the right of the cursor is prepended to the field one
6880 line down.
6881
6882 If there is no region, but you specify a prefix ARG, the current field gets
6883 blank, and the content is appended to the field above."
6884 (interactive "P")
6885 (org-table-check-inside-data-field)
6886 (if (org-region-active-p)
6887 ;; There is a region: fill as a paragraph
6888 (let ((beg (region-beginning))
6889 nlines)
6890 (org-table-cut-region (region-beginning) (region-end))
6891 (if (> (length (car org-table-clip)) 1)
6892 (error "Region must be limited to single column"))
6893 (setq nlines (if arg
6894 (if (< arg 1)
6895 (+ (length org-table-clip) arg)
6896 arg)
6897 (length org-table-clip)))
6898 (setq org-table-clip
6899 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6900 nil nlines)))
6901 (goto-char beg)
6902 (org-table-paste-rectangle))
6903 ;; No region, split the current field at point
6904 (if arg
6905 ;; combine with field above
6906 (let ((s (org-table-blank-field))
6907 (col (org-table-current-column)))
6908 (beginning-of-line 0)
6909 (while (org-at-table-hline-p) (beginning-of-line 0))
6910 (org-table-goto-column col)
6911 (skip-chars-forward "^|")
6912 (skip-chars-backward " ")
6913 (insert " " (org-trim s))
6914 (org-table-align))
6915 ;; split field
6916 (when (looking-at "\\([^|]+\\)+|")
6917 (let ((s (match-string 1)))
6918 (replace-match " |")
6919 (goto-char (match-beginning 0))
6920 (org-table-next-row)
6921 (insert (org-trim s) " ")
6922 (org-table-align))))))
6923
6924 (defun org-trim (s)
6925 "Remove whitespace at beginning and end of string."
6926 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6927 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6928 s)
6929
6930 (defun org-wrap (string &optional width lines)
6931 "Wrap string to either a number of lines, or a width in characters.
6932 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6933 that costs. If there is a word longer than WIDTH, the text is actually
6934 wrapped to the length of that word.
6935 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6936 many lines, whatever width that takes.
6937 The return value is a list of lines, without newlines at the end."
6938 (let* ((words (org-split-string string "[ \t\n]+"))
6939 (maxword (apply 'max (mapcar 'length words)))
6940 w ll)
6941 (cond (width
6942 (org-do-wrap words (max maxword width)))
6943 (lines
6944 (setq w maxword)
6945 (setq ll (org-do-wrap words maxword))
6946 (if (<= (length ll) lines)
6947 ll
6948 (setq ll words)
6949 (while (> (length ll) lines)
6950 (setq w (1+ w))
6951 (setq ll (org-do-wrap words w)))
6952 ll))
6953 (t (error "Cannot wrap this")))))
6954
6955
6956 (defun org-do-wrap (words width)
6957 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6958 (let (lines line)
6959 (while words
6960 (setq line (pop words))
6961 (while (and words (< (+ (length line) (length (car words))) width))
6962 (setq line (concat line " " (pop words))))
6963 (setq lines (push line lines)))
6964 (nreverse lines)))
6965
6966 ;; FIXME: I think I can make this more efficient
6967 (defun org-split-string (string &optional separators)
6968 "Splits STRING into substrings at SEPARATORS.
6969 No empty strings are returned if there are matches at the beginning
6970 and end of string."
6971 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6972 (start 0)
6973 notfirst
6974 (list nil))
6975 (while (and (string-match rexp string
6976 (if (and notfirst
6977 (= start (match-beginning 0))
6978 (< start (length string)))
6979 (1+ start) start))
6980 (< (match-beginning 0) (length string)))
6981 (setq notfirst t)
6982 (or (eq (match-beginning 0) 0)
6983 (and (eq (match-beginning 0) (match-end 0))
6984 (eq (match-beginning 0) start))
6985 (setq list
6986 (cons (substring string start (match-beginning 0))
6987 list)))
6988 (setq start (match-end 0)))
6989 (or (eq start (length string))
6990 (setq list
6991 (cons (substring string start)
6992 list)))
6993 (nreverse list)))
6994
6995 (defun org-table-add-invisible-to-vertical-lines ()
6996 "Add an `invisible' property to vertical lines of current table."
6997 (interactive)
6998 (let* ((beg (org-table-begin))
6999 (end (org-table-end))
7000 (end1))
7001 (save-excursion
7002 (goto-char beg)
7003 (while (< (point) end)
7004 (setq end1 (point-at-eol))
7005 (if (looking-at org-table-dataline-regexp)
7006 (while (re-search-forward "|" end1 t)
7007 (add-text-properties (1- (point)) (point)
7008 '(invisible org-table)))
7009 (while (re-search-forward "[+|]" end1 t)
7010 (add-text-properties (1- (point)) (point)
7011 '(invisible org-table))))
7012 (beginning-of-line 2)))))
7013
7014 (defun org-table-toggle-vline-visibility (&optional arg)
7015 "Toggle the visibility of table vertical lines.
7016 The effect is immediate and on all tables in the file.
7017 With prefix ARG, make lines invisible when ARG is positive, make lines
7018 visible when ARG is not positive"
7019 (interactive "P")
7020 (let ((action (cond
7021 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
7022 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
7023 (t (if (org-in-invisibility-spec-p '(org-table))
7024 'off
7025 'on)))))
7026 (if (eq action 'off)
7027 (progn
7028 (org-remove-from-invisibility-spec '(org-table))
7029 (org-table-map-tables 'org-table-align)
7030 (message "Vertical table lines visible")
7031 (if (org-at-table-p)
7032 (org-table-align)))
7033 (org-add-to-invisibility-spec '(org-table))
7034 (org-table-map-tables 'org-table-align)
7035 (message "Vertical table lines invisible"))
7036 (redraw-frame (selected-frame))))
7037
7038 (defun org-table-map-tables (function)
7039 "Apply FUNCTION to the start of all tables in the buffer."
7040 (save-excursion
7041 (save-restriction
7042 (widen)
7043 (goto-char (point-min))
7044 (while (re-search-forward org-table-any-line-regexp nil t)
7045 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7046 (beginning-of-line 1)
7047 (if (looking-at org-table-line-regexp)
7048 (save-excursion (funcall function)))
7049 (re-search-forward org-table-any-border-regexp nil 1)))))
7050
7051 (defun org-table-sum (&optional beg end nlast)
7052 "Sum numbers in region of current table column.
7053 The result will be displayed in the echo area, and will be available
7054 as kill to be inserted with \\[yank].
7055
7056 If there is an active region, it is interpreted as a rectangle and all
7057 numbers in that rectangle will be summed. If there is no active
7058 region and point is located in a table column, sum all numbers in that
7059 column.
7060
7061 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7062 numbers are assumed to be times as well (in decimal hours) and the
7063 numbers are added as such.
7064
7065 If NLAST is a number, only the NLAST fields will actually be summed."
7066 (interactive)
7067 (save-excursion
7068 (let (col (timecnt 0) diff h m s org-table-clip)
7069 (cond
7070 ((and beg end)) ; beg and end given explicitly
7071 ((org-region-active-p)
7072 (setq beg (region-beginning) end (region-end)))
7073 (t
7074 (setq col (org-table-current-column))
7075 (goto-char (org-table-begin))
7076 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7077 (error "No table data"))
7078 (org-table-goto-column col)
7079 ;not needed? (skip-chars-backward "^|")
7080 (setq beg (point))
7081 (goto-char (org-table-end))
7082 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7083 (error "No table data"))
7084 (org-table-goto-column col)
7085 ;not needed? (skip-chars-forward "^|")
7086 (setq end (point))))
7087 (let* ((items (apply 'append (org-table-copy-region beg end)))
7088 (items1 (cond ((not nlast) items)
7089 ((>= nlast (length items)) items)
7090 (t (setq items (reverse items))
7091 (setcdr (nthcdr (1- nlast) items) nil)
7092 (nreverse items))))
7093 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7094 items1)))
7095 (res (apply '+ numbers))
7096 (sres (if (= timecnt 0)
7097 (format "%g" res)
7098 (setq diff (* 3600 res)
7099 h (floor (/ diff 3600)) diff (mod diff 3600)
7100 m (floor (/ diff 60)) diff (mod diff 60)
7101 s diff)
7102 (format "%d:%02d:%02d" h m s))))
7103 (kill-new sres)
7104 (if (interactive-p)
7105 (message "%s"
7106 (substitute-command-keys
7107 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7108 (length numbers) sres))))
7109 sres))))
7110
7111 (defun org-table-get-number-for-summing (s)
7112 (let (n)
7113 (if (string-match "^ *|? *" s)
7114 (setq s (replace-match "" nil nil s)))
7115 (if (string-match " *|? *$" s)
7116 (setq s (replace-match "" nil nil s)))
7117 (setq n (string-to-number s))
7118 (cond
7119 ((and (string-match "0" s)
7120 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7121 ((string-match "\\`[ \t]+\\'" s) nil)
7122 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7123 (let ((h (string-to-number (or (match-string 1 s) "0")))
7124 (m (string-to-number (or (match-string 2 s) "0")))
7125 (s (string-to-number (or (match-string 4 s) "0"))))
7126 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7127 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7128 ((equal n 0) nil)
7129 (t n))))
7130
7131 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7132 "Get a calc vector from a column, accorting to desctiptor DESC.
7133 Optional arguments TBEG and COL can give the beginning of the table and
7134 the current column, to avoid unnecessary parsing."
7135 (save-excursion
7136 (or tbeg (setq tbeg (org-table-begin)))
7137 (or col (setq col (org-table-current-column)))
7138 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7139 (cond
7140 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7141 (setq n1 (- (match-end 1) (match-beginning 1)))
7142 (if (match-beginning 3)
7143 (setq n2 (- (match-end 2) (match-beginning 3))))
7144 (setq n (if n2 (max n1 n2) n1))
7145 (setq n1 (if n2 (min n1 n2)))
7146 (setq nn n)
7147 (while (and (> nn 0)
7148 (re-search-backward org-table-hline-regexp tbeg t))
7149 (push (org-current-line) hline-list)
7150 (setq nn (1- nn)))
7151 (setq hline-list (nreverse hline-list))
7152 (goto-line (nth (1- n) hline-list))
7153 (when (re-search-forward org-table-dataline-regexp)
7154 (org-table-goto-column col)
7155 (setq beg (point)))
7156 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7157 (when (re-search-backward org-table-dataline-regexp)
7158 (org-table-goto-column col)
7159 (setq end (point)))
7160 (setq l (apply 'append (org-table-copy-region beg end)))
7161 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7162 (if (equal x "") "0" x))
7163 l ",") "]"))
7164 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7165 (setq n1 (string-to-number (match-string 1 desc))
7166 n2 (string-to-number (match-string 2 desc)))
7167 (beginning-of-line 1)
7168 (save-excursion
7169 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7170 (org-table-goto-column col)
7171 (setq beg (point))))
7172 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7173 (org-table-goto-column col)
7174 (setq end (point)))
7175 (setq l (apply 'append (org-table-copy-region beg end)))
7176 (concat "[" (mapconcat
7177 (lambda (x) (setq x (org-trim x))
7178 (if (equal x "") "0" x))
7179 l ",") "]"))
7180 ((string-match "\\([0-9]+\\)" desc)
7181 (beginning-of-line 1)
7182 (when (re-search-backward org-table-dataline-regexp tbeg t
7183 (string-to-number (match-string 0 desc)))
7184 (org-table-goto-column col)
7185 (org-trim (org-table-get-field))))))))
7186
7187 (defvar org-table-formula-history nil)
7188
7189 (defvar org-table-column-names nil
7190 "Alist with column names, derived from the `!' line.")
7191 (defvar org-table-column-name-regexp nil
7192 "Regular expression matching the current column names.")
7193 (defvar org-table-local-parameters nil
7194 "Alist with parameter names, derived from the `$' line.")
7195 (defvar org-table-named-field-locations nil
7196 "Alist with locations of named fields.")
7197
7198 (defun org-table-get-formula (&optional equation named)
7199 "Read a formula from the minibuffer, offer stored formula as default."
7200 (let* ((name (car (rassoc (list (org-current-line)
7201 (org-table-current-column))
7202 org-table-named-field-locations)))
7203 (scol (if named
7204 (if name name
7205 (error "Not in a named field"))
7206 (int-to-string (org-table-current-column))))
7207 (dummy (and name (not named)
7208 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7209 (error "Abort")))
7210 (org-table-may-need-update nil)
7211 (stored-list (org-table-get-stored-formulas))
7212 (stored (cdr (assoc scol stored-list)))
7213 (eq (cond
7214 ((and stored equation (string-match "^ *=? *$" equation))
7215 stored)
7216 ((stringp equation)
7217 equation)
7218 (t (read-string
7219 (format "%s formula $%s=" (if named "Field" "Column") scol)
7220 (or stored "") 'org-table-formula-history
7221 ;stored
7222 ))))
7223 mustsave)
7224 (when (not (string-match "\\S-" eq))
7225 ;; remove formula
7226 (setq stored-list (delq (assoc scol stored-list) stored-list))
7227 (org-table-store-formulas stored-list)
7228 (error "Formula removed"))
7229 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7230 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7231 (if (and name (not named))
7232 ;; We set the column equation, delete the named one.
7233 (setq stored-list (delq (assoc name stored-list) stored-list)
7234 mustsave t))
7235 (if stored
7236 (setcdr (assoc scol stored-list) eq)
7237 (setq stored-list (cons (cons scol eq) stored-list)))
7238 (if (or mustsave (not (equal stored eq)))
7239 (org-table-store-formulas stored-list))
7240 eq))
7241
7242 (defun org-table-store-formulas (alist)
7243 "Store the list of formulas below the current table."
7244 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7245 (save-excursion
7246 (goto-char (org-table-end))
7247 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7248 (delete-region (point) (match-end 0)))
7249 (insert "#+TBLFM: "
7250 (mapconcat (lambda (x)
7251 (concat "$" (car x) "=" (cdr x)))
7252 alist "::")
7253 "\n")))
7254
7255 (defun org-table-get-stored-formulas ()
7256 "Return an alist with the t=stored formulas directly after current table."
7257 (interactive)
7258 (let (scol eq eq-alist strings string seen)
7259 (save-excursion
7260 (goto-char (org-table-end))
7261 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7262 (setq strings (org-split-string (match-string 2) " *:: *"))
7263 (while (setq string (pop strings))
7264 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7265 (setq scol (match-string 1 string)
7266 eq (match-string 2 string)
7267 eq-alist (cons (cons scol eq) eq-alist))
7268 (if (member scol seen)
7269 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7270 (push scol seen))))))
7271 (nreverse eq-alist)))
7272
7273 (defun org-table-modify-formulas (action &rest columns)
7274 "Modify the formulas stored below the current table.
7275 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7276 expected, for the other action only a single column number is needed."
7277 (let ((list (org-table-get-stored-formulas))
7278 (nmax (length (org-split-string
7279 (buffer-substring (point-at-bol) (point-at-eol))
7280 "|")))
7281 col col1 col2 scol si sc1 sc2)
7282 (cond
7283 ((null list)) ; No action needed if there are no stored formulas
7284 ((eq action 'remove)
7285 (setq col (car columns)
7286 scol (int-to-string col))
7287 (org-table-replace-in-formulas list scol "INVALID")
7288 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7289 (loop for i from (1+ col) upto nmax by 1 do
7290 (setq si (int-to-string i))
7291 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7292 (if (assoc si list) (setcar (assoc si list)
7293 (int-to-string (1- i))))))
7294 ((eq action 'insert)
7295 (setq col (car columns))
7296 (loop for i from nmax downto col by 1 do
7297 (setq si (int-to-string i))
7298 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7299 (if (assoc si list) (setcar (assoc si list)
7300 (int-to-string (1+ i))))))
7301 ((eq action 'swap)
7302 (setq col1 (car columns) col2 (nth 1 columns)
7303 sc1 (int-to-string col1) sc2 (int-to-string col2))
7304 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7305 (org-table-replace-in-formulas list sc1 "ZqZ")
7306 (org-table-replace-in-formulas list sc2 sc1)
7307 (org-table-replace-in-formulas list "ZqZ" sc2)
7308 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7309 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7310 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7311 (t (error "Invalid action in `org-table-modify-formulas'")))
7312 (if list (org-table-store-formulas list))))
7313
7314 (defun org-table-replace-in-formulas (list s1 s2)
7315 (let (elt re s)
7316 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7317 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7318 re (concat (regexp-quote s1) "\\>"))
7319 (while (setq elt (pop list))
7320 (setq s (cdr elt))
7321 (while (string-match re s)
7322 (setq s (replace-match s2 t t s)))
7323 (setcdr elt s))))
7324
7325 (defun org-table-get-specials ()
7326 "Get the column nmaes and local parameters for this table."
7327 (save-excursion
7328 (let ((beg (org-table-begin)) (end (org-table-end))
7329 names name fields fields1 field cnt c v line col)
7330 (setq org-table-column-names nil
7331 org-table-local-parameters nil
7332 org-table-named-field-locations nil)
7333 (goto-char beg)
7334 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7335 (setq names (org-split-string (match-string 1) " *| *")
7336 cnt 1)
7337 (while (setq name (pop names))
7338 (setq cnt (1+ cnt))
7339 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7340 (push (cons name (int-to-string cnt)) org-table-column-names))))
7341 (setq org-table-column-names (nreverse org-table-column-names))
7342 (setq org-table-column-name-regexp
7343 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7344 (goto-char beg)
7345 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7346 (setq fields (org-split-string (match-string 1) " *| *"))
7347 (while (setq field (pop fields))
7348 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7349 (push (cons (match-string 1 field) (match-string 2 field))
7350 org-table-local-parameters))))
7351 (goto-char beg)
7352 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7353 (setq c (match-string 1)
7354 fields (org-split-string (match-string 2) " *| *"))
7355 (save-excursion
7356 (beginning-of-line (if (equal c "_") 2 0))
7357 (setq line (org-current-line) col 1)
7358 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7359 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7360 (while (and fields1 (setq field (pop fields)))
7361 (setq v (pop fields1) col (1+ col))
7362 (when (and (stringp field) (stringp v)
7363 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7364 (push (cons field v) org-table-local-parameters)
7365 (push (list field line col) org-table-named-field-locations)))))))
7366
7367 (defun org-this-word ()
7368 ;; Get the current word
7369 (save-excursion
7370 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7371 (end (progn (skip-chars-forward "^ \t\n") (point))))
7372 (buffer-substring-no-properties beg end))))
7373
7374 (defun org-table-maybe-eval-formula ()
7375 "Check if the current field starts with \"=\" or \":=\".
7376 If yes, store the formula and apply it."
7377 ;; We already know we are in a table. Get field will only return a formula
7378 ;; when appropriate. It might return a separator line, but no problem.
7379 (when org-table-formula-evaluate-inline
7380 (let* ((field (org-trim (or (org-table-get-field) "")))
7381 named eq)
7382 (when (string-match "^:?=\\(.*\\)" field)
7383 (setq named (equal (string-to-char field) ?:)
7384 eq (match-string 1 field))
7385 (if (fboundp 'calc-eval)
7386 (org-table-eval-formula (if named '(4) nil) eq))))))
7387
7388 (defvar org-recalc-commands nil
7389 "List of commands triggering the reccalculation of a line.
7390 Will be filled automatically during use.")
7391
7392 (defvar org-recalc-marks
7393 '((" " . "Unmarked: no special line, no automatic recalculation")
7394 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7395 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7396 ("!" . "Column name definition line. Reference in formula as $name.")
7397 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7398 ("_" . "Names for values in row below this one.")
7399 ("^" . "Names for values in row above this one.")))
7400
7401 (defun org-table-rotate-recalc-marks (&optional newchar)
7402 "Rotate the recalculation mark in the first column.
7403 If in any row, the first field is not consistent with a mark,
7404 insert a new column for the makers.
7405 When there is an active region, change all the lines in the region,
7406 after prompting for the marking character.
7407 After each change, a message will be displayed indication the meaning
7408 of the new mark."
7409 (interactive)
7410 (unless (org-at-table-p) (error "Not at a table"))
7411 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7412 (beg (org-table-begin))
7413 (end (org-table-end))
7414 (l (org-current-line))
7415 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7416 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7417 (have-col
7418 (save-excursion
7419 (goto-char beg)
7420 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7421 (col (org-table-current-column))
7422 (forcenew (car (assoc newchar org-recalc-marks)))
7423 epos new)
7424 (when l1
7425 (message "Change region to what mark? Type # * ! $ or SPC: ")
7426 (setq newchar (char-to-string (read-char-exclusive))
7427 forcenew (car (assoc newchar org-recalc-marks))))
7428 (if (and newchar (not forcenew))
7429 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7430 newchar))
7431 (if l1 (goto-line l1))
7432 (save-excursion
7433 (beginning-of-line 1)
7434 (unless (looking-at org-table-dataline-regexp)
7435 (error "Not at a table data line")))
7436 (unless have-col
7437 (org-table-goto-column 1)
7438 (org-table-insert-column)
7439 (org-table-goto-column (1+ col)))
7440 (setq epos (point-at-eol))
7441 (save-excursion
7442 (beginning-of-line 1)
7443 (org-table-get-field
7444 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7445 (concat " "
7446 (setq new (or forcenew
7447 (cadr (member (match-string 1) marks))))
7448 " ")
7449 " # ")))
7450 (if (and l1 l2)
7451 (progn
7452 (goto-line l1)
7453 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7454 (and (looking-at org-table-dataline-regexp)
7455 (org-table-get-field 1 (concat " " new " "))))
7456 (goto-line l1)))
7457 (if (not (= epos (point-at-eol))) (org-table-align))
7458 (goto-line l)
7459 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7460
7461 (defun org-table-maybe-recalculate-line ()
7462 "Recompute the current line if marked for it, and if we haven't just done it."
7463 (interactive)
7464 (and org-table-allow-automatic-line-recalculation
7465 (not (and (memq last-command org-recalc-commands)
7466 (equal org-last-recalc-line (org-current-line))))
7467 (save-excursion (beginning-of-line 1)
7468 (looking-at org-table-auto-recalculate-regexp))
7469 (fboundp 'calc-eval)
7470 (org-table-recalculate) t))
7471
7472 (defvar org-table-formula-debug nil
7473 "Non-nil means, debug table formulas.
7474 When nil, simply write \"#ERROR\" in corrupted fields.")
7475
7476 (defvar modes)
7477 (defsubst org-set-calc-mode (var &optional value)
7478 (if (stringp var)
7479 (setq var (assoc var '(("D" calc-angle-mode deg)
7480 ("R" calc-angle-mode rad)
7481 ("F" calc-prefer-frac t)
7482 ("S" calc-symbolic-mode t)))
7483 value (nth 2 var) var (nth 1 var)))
7484 (if (memq var modes)
7485 (setcar (cdr (memq var modes)) value)
7486 (cons var (cons value modes)))
7487 modes)
7488
7489 (defun org-table-eval-formula (&optional arg equation
7490 suppress-align suppress-const
7491 suppress-store)
7492 "Replace the table field value at the cursor by the result of a calculation.
7493
7494 This function makes use of Dave Gillespie's calc package, in my view the
7495 most exciting program ever written for GNU Emacs. So you need to have calc
7496 installed in order to use this function.
7497
7498 In a table, this command replaces the value in the current field with the
7499 result of a formula. It also installes the formula as the \"current\" column
7500 formula, by storing it in a special line below the table. When called
7501 with a `C-u' prefix, the current field must ba a named field, and the
7502 formula is installed as valid in only this specific field.
7503
7504 When called, the command first prompts for a formula, which is read in
7505 the minibuffer. Previously entered formulas are available through the
7506 history list, and the last used formula is offered as a default.
7507 These stored formulas are adapted correctly when moving, inserting, or
7508 deleting columns with the corresponding commands.
7509
7510 The formula can be any algebraic expression understood by the calc package.
7511 For details, see the Org-mode manual.
7512
7513 This function can also be called from Lisp programs and offers
7514 additional Arguments: EQUATION can be the formula to apply. If this
7515 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7516 used to speed-up recursive calls by by-passing unnecessary aligns.
7517 SUPPRESS-CONST suppresses the interpretation of constants in the
7518 formula, assuming that this has been done already outside the fuction.
7519 SUPPRESS-STORE means the formula should not be stored, either because
7520 it is already stored, or because it is a modified equation that should
7521 not overwrite the stored one."
7522 (interactive "P")
7523 (require 'calc)
7524 (org-table-check-inside-data-field)
7525 (org-table-get-specials)
7526 (let* (fields
7527 (ndown (if (integerp arg) arg 1))
7528 (org-table-automatic-realign nil)
7529 (case-fold-search nil)
7530 (down (> ndown 1))
7531 (formula (if (and equation suppress-store)
7532 equation
7533 (org-table-get-formula equation (equal arg '(4)))))
7534 (n0 (org-table-current-column))
7535 (modes (copy-sequence org-calc-default-modes))
7536 n form fmt x ev orig c)
7537 ;; Parse the format string. Since we have a lot of modes, this is
7538 ;; a lot of work. However, I think calc still uses most of the time.
7539 (if (string-match ";" formula)
7540 (let ((tmp (org-split-string formula ";")))
7541 (setq formula (car tmp)
7542 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7543 (nth 1 tmp)))
7544 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7545 (setq c (string-to-char (match-string 1 fmt))
7546 n (string-to-number (or (match-string 1 fmt) "")))
7547 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7548 (setq modes (org-set-calc-mode
7549 'calc-float-format
7550 (list (cdr (assoc c '((?n. float) (?f. fix)
7551 (?s. sci) (?e. eng))))
7552 n))))
7553 (setq fmt (replace-match "" t t fmt)))
7554 (while (string-match "[DRFS]" fmt)
7555 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7556 (setq fmt (replace-match "" t t fmt)))
7557 (unless (string-match "\\S-" fmt)
7558 (setq fmt nil))))
7559 (if (and (not suppress-const) org-table-formula-use-constants)
7560 (setq formula (org-table-formula-substitute-names formula)))
7561 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7562 (while (> ndown 0)
7563 (setq fields (org-split-string
7564 (buffer-substring
7565 (point-at-bol) (point-at-eol)) " *| *"))
7566 (if org-table-formula-numbers-only
7567 (setq fields (mapcar
7568 (lambda (x) (number-to-string (string-to-number x)))
7569 fields)))
7570 (setq ndown (1- ndown))
7571 (setq form (copy-sequence formula))
7572 ;; Insert the references to fields in same row
7573 (while (string-match "\\$\\([0-9]+\\)?" form)
7574 (setq n (if (match-beginning 1)
7575 (string-to-number (match-string 1 form))
7576 n0)
7577 x (nth (1- n) fields))
7578 (unless x (error "Invalid field specifier \"%s\""
7579 (match-string 0 form)))
7580 (if (equal x "") (setq x "0"))
7581 (setq form (replace-match (concat "(" x ")") t t form)))
7582 ;; Insert ranges in current column
7583 (while (string-match "\\&[-I0-9]+" form)
7584 (setq form (replace-match
7585 (save-match-data
7586 (org-table-get-vertical-vector (match-string 0 form)
7587 nil n0))
7588 t t form)))
7589 (setq ev (calc-eval (cons form modes)
7590 (if org-table-formula-numbers-only 'num)))
7591
7592 (when org-table-formula-debug
7593 (with-output-to-temp-buffer "*Help*"
7594 (princ (format "Substitution history of formula
7595 Orig: %s
7596 $xyz-> %s
7597 $1-> %s\n" orig formula form))
7598 (if (listp ev)
7599 (princ (format " %s^\nError: %s"
7600 (make-string (car ev) ?\-) (nth 1 ev)))
7601 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7602 ev (or fmt "NONE")
7603 (if fmt (format fmt (string-to-number ev)) ev)))))
7604 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7605 (unless (and (interactive-p) (not ndown))
7606 (unless (let (inhibit-redisplay)
7607 (y-or-n-p "Debugging Formula. Continue to next? "))
7608 (org-table-align)
7609 (error "Abort"))
7610 (delete-window (get-buffer-window "*Help*"))
7611 (message "")))
7612 (if (listp ev) (setq fmt nil ev "#ERROR"))
7613 (org-table-justify-field-maybe
7614 (if fmt (format fmt (string-to-number ev)) ev))
7615 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7616 (call-interactively 'org-return)
7617 (setq ndown 0)))
7618 (and down (org-table-maybe-recalculate-line))
7619 (or suppress-align (and org-table-may-need-update
7620 (org-table-align)))))
7621
7622 (defun org-table-recalculate (&optional all noalign)
7623 "Recalculate the current table line by applying all stored formulas."
7624 (interactive "P")
7625 (or (memq this-command org-recalc-commands)
7626 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7627 (unless (org-at-table-p) (error "Not at a table"))
7628 (org-table-get-specials)
7629 (let* ((eqlist (sort (org-table-get-stored-formulas)
7630 (lambda (a b) (string< (car a) (car b)))))
7631 (inhibit-redisplay t)
7632 (line-re org-table-dataline-regexp)
7633 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7634 (thiscol (org-table-current-column))
7635 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7636 ;; Insert constants in all formulas
7637 (setq eqlist
7638 (mapcar (lambda (x)
7639 (setcdr x (org-table-formula-substitute-names (cdr x)))
7640 x)
7641 eqlist))
7642 ;; Split the equation list
7643 (while (setq eq (pop eqlist))
7644 (if (<= (string-to-char (car eq)) ?9)
7645 (push eq eqlnum)
7646 (push eq eqlname)))
7647 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7648 (if all
7649 (progn
7650 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7651 (goto-char (setq beg (org-table-begin)))
7652 (if (re-search-forward org-table-calculate-mark-regexp end t)
7653 ;; This is a table with marked lines, only compute selected lines
7654 (setq line-re org-table-recalculate-regexp)
7655 ;; Move forward to the first non-header line
7656 (if (and (re-search-forward org-table-dataline-regexp end t)
7657 (re-search-forward org-table-hline-regexp end t)
7658 (re-search-forward org-table-dataline-regexp end t))
7659 (setq beg (match-beginning 0))
7660 nil))) ;; just leave beg where it is
7661 (setq beg (point-at-bol)
7662 end (move-marker (make-marker) (1+ (point-at-eol)))))
7663 (goto-char beg)
7664 (and all (message "Re-applying formulas to full table..."))
7665 (while (re-search-forward line-re end t)
7666 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7667 ;; Unprotected line, recalculate
7668 (and all (message "Re-applying formulas to full table...(line %d)"
7669 (setq cnt (1+ cnt))))
7670 (setq org-last-recalc-line (org-current-line))
7671 (setq eql eqlnum)
7672 (while (setq entry (pop eql))
7673 (goto-line org-last-recalc-line)
7674 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7675 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7676 (goto-line thisline)
7677 (org-table-goto-column thiscol)
7678 (or noalign (and org-table-may-need-update (org-table-align))
7679 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7680 ;; Now do the names fields
7681 (while (setq eq (pop eqlname))
7682 (setq name (car eq)
7683 a (assoc name org-table-named-field-locations))
7684 (when a
7685 (message "Re-applying formula to named field: %s" name)
7686 (goto-line (nth 1 a))
7687 (org-table-goto-column (nth 2 a))
7688 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7689 ;; back to initial position
7690 (goto-line thisline)
7691 (org-table-goto-column thiscol)
7692 (or noalign (and org-table-may-need-update (org-table-align))
7693 (and all (message "Re-applying formulas...done")))))
7694
7695 (defun org-table-formula-substitute-names (f)
7696 "Replace $const with values in string F."
7697 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7698 ;; First, check for column names
7699 (while (setq start (string-match org-table-column-name-regexp f start))
7700 (setq start (1+ start))
7701 (setq a (assoc (match-string 1 f) org-table-column-names))
7702 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7703 ;; Expand ranges to vectors
7704 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7705 (setq n1 (string-to-number (match-string 1 f))
7706 n2 (string-to-number (match-string 2 f))
7707 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7708 s (concat "[($" (number-to-string (1- nn1)) ")"))
7709 (loop for i from nn1 upto nn2 do
7710 (setq s (concat s ",($" (int-to-string i) ")")))
7711 (setq s (concat s "]"))
7712 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7713 (setq f (replace-match s t t f)))
7714 ;; Parameters and constants
7715 (setq start 0)
7716 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7717 (setq start (1+ start))
7718 (if (setq a (save-match-data
7719 (org-table-get-constant (match-string 1 f))))
7720 (setq f (replace-match (concat "(" a ")") t t f))))
7721 (if org-table-formula-debug
7722 (put-text-property 0 (length f) :orig-formula f1 f))
7723 f))
7724
7725 (defun org-table-get-constant (const)
7726 "Find the value for a parameter or constant in a formula.
7727 Parameters get priority."
7728 (or (cdr (assoc const org-table-local-parameters))
7729 (cdr (assoc const org-table-formula-constants))
7730 (and (fboundp 'constants-get) (constants-get const))
7731 "#UNDEFINED_NAME"))
7732
7733 (defvar org-edit-formulas-map (make-sparse-keymap))
7734 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7735 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7736 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7737
7738 (defvar org-pos)
7739 (defvar org-window-configuration)
7740
7741 (defun org-table-edit-formulas ()
7742 "Edit the formulas of the current table in a separate buffer."
7743 (interactive)
7744 (unless (org-at-table-p)
7745 (error "Not at a table"))
7746 (org-table-get-specials)
7747 (let ((eql (org-table-get-stored-formulas))
7748 (pos (move-marker (make-marker) (point)))
7749 (wc (current-window-configuration))
7750 entry loc s)
7751 (switch-to-buffer-other-window "*Edit Formulas*")
7752 (erase-buffer)
7753 (fundamental-mode)
7754 (set (make-local-variable 'org-pos) pos)
7755 (set (make-local-variable 'org-window-configuration) wc)
7756 (use-local-map org-edit-formulas-map)
7757 (setq s "# Edit formulas and finish with `C-c C-c'.
7758 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7759 # Use `C-c ?' to get information about $name at point.
7760 # To cancel editing, press `C-c C-q'.\n")
7761 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7762 (insert s)
7763 (while (setq entry (pop eql))
7764 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7765 (setq s (format "# Named formula, referring to column %d in line %d\n"
7766 (nth 2 loc) (nth 1 loc)))
7767 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7768 (insert s))
7769 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7770 (remove-text-properties 0 (length s) '(face nil) s)
7771 (insert s))
7772 (goto-char (point-min))
7773 (message "Edit formulas and finish with `C-c C-c'.")))
7774
7775 (defun org-show-variable ()
7776 "Show the location/value of the $ expression at point."
7777 (interactive)
7778 (let (var (pos org-pos) (win (selected-window)) e)
7779 (save-excursion
7780 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7781 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7782 (setq var (match-string 1))
7783 (error "No variable at point")))
7784 (cond
7785 ((setq e (assoc var org-table-named-field-locations))
7786 (switch-to-buffer-other-window (marker-buffer pos))
7787 (goto-line (nth 1 e))
7788 (org-table-goto-column (nth 2 e))
7789 (select-window win)
7790 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7791 ((setq e (assoc var org-table-column-names))
7792 (switch-to-buffer-other-window (marker-buffer pos))
7793 (goto-char pos)
7794 (goto-char (org-table-begin))
7795 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7796 (org-table-end) t)
7797 (progn
7798 (goto-char (match-beginning 1))
7799 (message "Named column (column %s)" (cdr e)))
7800 (error "Column name not found"))
7801 (select-window win))
7802 ((string-match "^[0-9]$" var)
7803 ;; column number
7804 (switch-to-buffer-other-window (marker-buffer pos))
7805 (goto-char pos)
7806 (goto-char (org-table-begin))
7807 (recenter 1)
7808 (if (re-search-forward org-table-dataline-regexp
7809 (org-table-end) t)
7810 (progn
7811 (goto-char (match-beginning 0))
7812 (org-table-goto-column (string-to-number var))
7813 (message "Column %s" var))
7814 (error "Column name not found"))
7815 (select-window win))
7816 ((setq e (assoc var org-table-local-parameters))
7817 (switch-to-buffer-other-window (marker-buffer pos))
7818 (goto-char pos)
7819 (goto-char (org-table-begin))
7820 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7821 (progn
7822 (goto-char (match-beginning 1))
7823 (message "Local parameter."))
7824 (error "Parameter not found"))
7825 (select-window win))
7826 (t
7827 (cond
7828 ((setq e (assoc var org-table-formula-constants))
7829 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7830 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7831 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7832 (t (error "Undefined name $%s" var)))))))
7833
7834 (defun org-finish-edit-formulas (&optional arg)
7835 "Parse the buffer for formula definitions and install them.
7836 With prefix ARG, apply the new formulas to the table."
7837 (interactive "P")
7838 (let ((pos org-pos) eql)
7839 (goto-char (point-min))
7840 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7841 (push (cons (match-string 1) (match-string 2)) eql))
7842 (set-window-configuration org-window-configuration)
7843 (select-window (get-buffer-window (marker-buffer pos)))
7844 (goto-char pos)
7845 (unless (org-at-table-p)
7846 (error "Lost table position - cannot install formulae"))
7847 (org-table-store-formulas eql)
7848 (move-marker pos nil)
7849 (kill-buffer "*Edit Formulas*")
7850 (if arg
7851 (org-table-recalculate 'all)
7852 (message "New formulas installed - press C-u C-c C-c to apply."))))
7853
7854 (defun org-abort-edit-formulas ()
7855 "Abort editing formulas, without installing the changes."
7856 (interactive)
7857 (let ((pos org-pos))
7858 (set-window-configuration org-window-configuration)
7859 (select-window (get-buffer-window (marker-buffer pos)))
7860 (goto-char pos)
7861 (message "Formula editing aborted without installing changes")))
7862
7863 ;;; The orgtbl minor mode
7864
7865 ;; Define a minor mode which can be used in other modes in order to
7866 ;; integrate the org-mode table editor.
7867
7868 ;; This is really a hack, because the org-mode table editor uses several
7869 ;; keys which normally belong to the major mode, for example the TAB and
7870 ;; RET keys. Here is how it works: The minor mode defines all the keys
7871 ;; necessary to operate the table editor, but wraps the commands into a
7872 ;; function which tests if the cursor is currently inside a table. If that
7873 ;; is the case, the table editor command is executed. However, when any of
7874 ;; those keys is used outside a table, the function uses `key-binding' to
7875 ;; look up if the key has an associated command in another currently active
7876 ;; keymap (minor modes, major mode, global), and executes that command.
7877 ;; There might be problems if any of the keys used by the table editor is
7878 ;; otherwise used as a prefix key.
7879
7880 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7881 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7882 ;; addresses this by checking explicitly for both bindings.
7883
7884 ;; The optimized version (see variable `orgtbl-optimized') takes over
7885 ;; all keys which are bound to `self-insert-command' in the *global map*.
7886 ;; Some modes bind other commands to simple characters, for example
7887 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7888 ;; active, this binding is ignored inside tables and replaced with a
7889 ;; modified self-insert.
7890
7891 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7892 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7893 In the optimized version, the table editor takes over all simple keys that
7894 normally just insert a character. In tables, the characters are inserted
7895 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7896 for empty fields). Outside tables, the correct binding of the keys is
7897 restored.
7898
7899 The default for this option is t if the optimized version is also used in
7900 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7901 this variable requires a restart of Emacs to become effective."
7902 :group 'org-table
7903 :type 'boolean)
7904
7905 (defvar orgtbl-mode nil
7906 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7907 table editor in arbitrary modes.")
7908 (make-variable-buffer-local 'orgtbl-mode)
7909
7910 (defvar orgtbl-mode-map (make-keymap)
7911 "Keymap for `orgtbl-mode'.")
7912
7913 ;;;###autoload
7914 (defun turn-on-orgtbl ()
7915 "Unconditionally turn on `orgtbl-mode'."
7916 (orgtbl-mode 1))
7917
7918 ;;;###autoload
7919 (defun orgtbl-mode (&optional arg)
7920 "The `org-mode' table editor as a minor mode for use in other modes."
7921 (interactive)
7922 (if (eq major-mode 'org-mode)
7923 ;; Exit without error, in case some hook functions calls this
7924 ;; by accident in org-mode.
7925 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7926 (setq orgtbl-mode
7927 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7928 (if orgtbl-mode
7929 (progn
7930 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7931 ;; Make sure we are first in minor-mode-map-alist
7932 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7933 (and c (setq minor-mode-map-alist
7934 (cons c (delq c minor-mode-map-alist)))))
7935 (set (make-local-variable (quote org-table-may-need-update)) t)
7936 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
7937 (add-hook 'before-change-functions 'org-before-change-function
7938 nil 'local)
7939 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7940 auto-fill-inhibit-regexp)
7941 (set (make-local-variable 'auto-fill-inhibit-regexp)
7942 (if auto-fill-inhibit-regexp
7943 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7944 "[ \t]*|"))
7945 (easy-menu-add orgtbl-mode-menu)
7946 (run-hooks 'orgtbl-mode-hook))
7947 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7948 (remove-hook 'before-change-functions 'org-before-change-function t)
7949 (easy-menu-remove orgtbl-mode-menu)
7950 (force-mode-line-update 'all))))
7951
7952 ;; Install it as a minor mode.
7953 (put 'orgtbl-mode :included t)
7954 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7955 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7956
7957 (defun orgtbl-make-binding (fun n &rest keys)
7958 "Create a function for binding in the table minor mode.
7959 FUN is the command to call inside a table. N is used to create a unique
7960 command name. KEYS are keys that should be checked in for a command
7961 to execute outside of tables."
7962 (eval
7963 (list 'defun
7964 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7965 '(arg)
7966 (concat "In tables, run `" (symbol-name fun) "'.\n"
7967 "Outside of tables, run the binding of `"
7968 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7969 "'.")
7970 '(interactive "p")
7971 (list 'if
7972 '(org-at-table-p)
7973 (list 'call-interactively (list 'quote fun))
7974 (list 'let '(orgtbl-mode)
7975 (list 'call-interactively
7976 (append '(or)
7977 (mapcar (lambda (k)
7978 (list 'key-binding k))
7979 keys)
7980 '('orgtbl-error))))))))
7981
7982 (defun orgtbl-error ()
7983 "Error when there is no default binding for a table key."
7984 (interactive)
7985 (error "This key is has no function outside tables"))
7986
7987 (defun orgtbl-setup ()
7988 "Setup orgtbl keymaps."
7989 (let ((nfunc 0)
7990 (bindings
7991 (list
7992 '([(meta shift left)] org-table-delete-column)
7993 '([(meta left)] org-table-move-column-left)
7994 '([(meta right)] org-table-move-column-right)
7995 '([(meta shift right)] org-table-insert-column)
7996 '([(meta shift up)] org-table-kill-row)
7997 '([(meta shift down)] org-table-insert-row)
7998 '([(meta up)] org-table-move-row-up)
7999 '([(meta down)] org-table-move-row-down)
8000 '("\C-c\C-w" org-table-cut-region)
8001 '("\C-c\M-w" org-table-copy-region)
8002 '("\C-c\C-y" org-table-paste-rectangle)
8003 '("\C-c-" org-table-insert-hline)
8004 ; '([(shift tab)] org-table-previous-field)
8005 '("\C-m" org-table-next-row)
8006 (list (org-key 'S-return) 'org-table-copy-down)
8007 '([(meta return)] org-table-wrap-region)
8008 '("\C-c\C-q" org-table-wrap-region)
8009 '("\C-c?" org-table-current-column)
8010 '("\C-c " org-table-blank-field)
8011 '("\C-c+" org-table-sum)
8012 '("\C-c|" org-table-toggle-vline-visibility)
8013 '("\C-c=" org-table-eval-formula)
8014 '("\C-c'" org-table-edit-formulas)
8015 '("\C-c*" org-table-recalculate)
8016 '([(control ?#)] org-table-rotate-recalc-marks)))
8017 elt key fun cmd)
8018 (while (setq elt (pop bindings))
8019 (setq nfunc (1+ nfunc))
8020 (setq key (car elt)
8021 fun (nth 1 elt)
8022 cmd (orgtbl-make-binding fun nfunc key))
8023 (define-key orgtbl-mode-map key cmd))
8024 ;; Special treatment needed for TAB and RET
8025 (define-key orgtbl-mode-map [(return)]
8026 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8027 (define-key orgtbl-mode-map "\C-m"
8028 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8029 (define-key orgtbl-mode-map [(tab)]
8030 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8031 (define-key orgtbl-mode-map "\C-i"
8032 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
8033 (define-key orgtbl-mode-map "\C-i"
8034 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8035 (define-key orgtbl-mode-map "\C-c\C-c"
8036 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8037 (when orgtbl-optimized
8038 ;; If the user wants maximum table support, we need to hijack
8039 ;; some standard editing functions
8040 (org-remap orgtbl-mode-map
8041 'self-insert-command 'orgtbl-self-insert-command
8042 'delete-char 'orgtbl-delete-char
8043 'delete-backward-char 'orgtbl-delete-backward-char)
8044 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8045 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8046 '("OrgTbl"
8047 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8048 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8049 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8050 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8051 "--"
8052 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8053 ["Copy Field from Above"
8054 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8055 "--"
8056 ("Column"
8057 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8058 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8059 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8060 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8061 ("Row"
8062 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8063 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8064 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8065 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8066 "--"
8067 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8068 ("Rectangle"
8069 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8070 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8071 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8072 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8073 "--"
8074 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8075 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8076 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8077 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8078 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8079 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8080 ["Sum Column/Rectangle" org-table-sum
8081 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8082 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8083 ["Debug Formulas"
8084 (setq org-table-formula-debug (not org-table-formula-debug))
8085 :style toggle :selected org-table-formula-debug]
8086 ))
8087 t)
8088
8089 (defun orgtbl-tab ()
8090 "Justification and field motion for `orgtbl-mode'."
8091 (interactive)
8092 (org-table-justify-field-maybe)
8093 (org-table-next-field))
8094
8095 (defun orgtbl-ret ()
8096 "Justification and field motion for `orgtbl-mode'."
8097 (interactive)
8098 (org-table-justify-field-maybe)
8099 (org-table-next-row))
8100
8101 (defun orgtbl-self-insert-command (N)
8102 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8103 If the cursor is in a table looking at whitespace, the whitespace is
8104 overwritten, and the table is not marked as requiring realignment."
8105 (interactive "p")
8106 (if (and (org-at-table-p)
8107 (or
8108 (and org-table-auto-blank-field
8109 (member last-command
8110 '(orgtbl-hijacker-command-100
8111 orgtbl-hijacker-command-101
8112 orgtbl-hijacker-command-102
8113 orgtbl-hijacker-command-103
8114 orgtbl-hijacker-command-104
8115 orgtbl-hijacker-command-105))
8116 (org-table-blank-field))
8117 t)
8118 (eq N 1)
8119 (looking-at "[^|\n]* +|"))
8120 (let (org-table-may-need-update)
8121 (goto-char (1- (match-end 0)))
8122 (delete-backward-char 1)
8123 (goto-char (match-beginning 0))
8124 (self-insert-command N))
8125 (setq org-table-may-need-update t)
8126 (let (orgtbl-mode)
8127 (call-interactively (key-binding (vector last-input-event))))))
8128
8129 (defun org-force-self-insert (N)
8130 "Needed to enforce self-insert under remapping."
8131 (interactive "p")
8132 (self-insert-command N))
8133
8134 (defun orgtbl-delete-backward-char (N)
8135 "Like `delete-backward-char', insert whitespace at field end in tables.
8136 When deleting backwards, in tables this function will insert whitespace in
8137 front of the next \"|\" separator, to keep the table aligned. The table will
8138 still be marked for re-alignment, because a narrow field may lead to a
8139 reduced column width."
8140 (interactive "p")
8141 (if (and (org-at-table-p)
8142 (eq N 1)
8143 (string-match "|" (buffer-substring (point-at-bol) (point)))
8144 (looking-at ".*?|"))
8145 (let ((pos (point)))
8146 (backward-delete-char N)
8147 (skip-chars-forward "^|")
8148 (insert " ")
8149 (goto-char (1- pos)))
8150 (delete-backward-char N)))
8151
8152 (defun orgtbl-delete-char (N)
8153 "Like `delete-char', but insert whitespace at field end in tables.
8154 When deleting characters, in tables this function will insert whitespace in
8155 front of the next \"|\" separator, to keep the table aligned. The table
8156 will still be marked for re-alignment, because a narrow field may lead to
8157 a reduced column width."
8158 (interactive "p")
8159 (if (and (org-at-table-p)
8160 (not (bolp))
8161 (not (= (char-after) ?|))
8162 (eq N 1))
8163 (if (looking-at ".*?|")
8164 (let ((pos (point)))
8165 (replace-match (concat
8166 (substring (match-string 0) 1 -1)
8167 " |"))
8168 (goto-char pos)))
8169 (delete-char N)))
8170
8171 ;;; Exporting
8172
8173 (defconst org-level-max 20)
8174
8175 (defun org-export-find-first-heading-line (list)
8176 "Remove all lines from LIST which are before the first headline."
8177 (let ((orig-list list)
8178 (re (concat "^" outline-regexp)))
8179 (while (and list
8180 (not (string-match re (car list))))
8181 (pop list))
8182 (or list orig-list)))
8183
8184 (defun org-skip-comments (lines)
8185 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8186 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8187 (re2 "^\\(\\*+\\)[ \t\n\r]")
8188 rtn line level)
8189 (while (setq line (pop lines))
8190 (cond
8191 ((and (string-match re1 line)
8192 (setq level (- (match-end 1) (match-beginning 1))))
8193 ;; Beginning of a COMMENT subtree. Skip it.
8194 (while (and (setq line (pop lines))
8195 (or (not (string-match re2 line))
8196 (> (- (match-end 1) (match-beginning 1)) level))))
8197 (setq lines (cons line lines)))
8198 ((string-match "^#" line)
8199 ;; an ordinary comment line
8200 )
8201 (t (setq rtn (cons line rtn)))))
8202 (nreverse rtn)))
8203
8204 ;; ASCII
8205
8206 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8207 "Characters for underlining headings in ASCII export.")
8208
8209 (defconst org-html-entities
8210 '(("nbsp")
8211 ("iexcl")
8212 ("cent")
8213 ("pound")
8214 ("curren")
8215 ("yen")
8216 ("brvbar")
8217 ("sect")
8218 ("uml")
8219 ("copy")
8220 ("ordf")
8221 ("laquo")
8222 ("not")
8223 ("shy")
8224 ("reg")
8225 ("macr")
8226 ("deg")
8227 ("plusmn")
8228 ("sup2")
8229 ("sup3")
8230 ("acute")
8231 ("micro")
8232 ("para")
8233 ("middot")
8234 ("odot"."o")
8235 ("star"."*")
8236 ("cedil")
8237 ("sup1")
8238 ("ordm")
8239 ("raquo")
8240 ("frac14")
8241 ("frac12")
8242 ("frac34")
8243 ("iquest")
8244 ("Agrave")
8245 ("Aacute")
8246 ("Acirc")
8247 ("Atilde")
8248 ("Auml")
8249 ("Aring") ("AA"."&Aring;")
8250 ("AElig")
8251 ("Ccedil")
8252 ("Egrave")
8253 ("Eacute")
8254 ("Ecirc")
8255 ("Euml")
8256 ("Igrave")
8257 ("Iacute")
8258 ("Icirc")
8259 ("Iuml")
8260 ("ETH")
8261 ("Ntilde")
8262 ("Ograve")
8263 ("Oacute")
8264 ("Ocirc")
8265 ("Otilde")
8266 ("Ouml")
8267 ("times")
8268 ("Oslash")
8269 ("Ugrave")
8270 ("Uacute")
8271 ("Ucirc")
8272 ("Uuml")
8273 ("Yacute")
8274 ("THORN")
8275 ("szlig")
8276 ("agrave")
8277 ("aacute")
8278 ("acirc")
8279 ("atilde")
8280 ("auml")
8281 ("aring")
8282 ("aelig")
8283 ("ccedil")
8284 ("egrave")
8285 ("eacute")
8286 ("ecirc")
8287 ("euml")
8288 ("igrave")
8289 ("iacute")
8290 ("icirc")
8291 ("iuml")
8292 ("eth")
8293 ("ntilde")
8294 ("ograve")
8295 ("oacute")
8296 ("ocirc")
8297 ("otilde")
8298 ("ouml")
8299 ("divide")
8300 ("oslash")
8301 ("ugrave")
8302 ("uacute")
8303 ("ucirc")
8304 ("uuml")
8305 ("yacute")
8306 ("thorn")
8307 ("yuml")
8308 ("fnof")
8309 ("Alpha")
8310 ("Beta")
8311 ("Gamma")
8312 ("Delta")
8313 ("Epsilon")
8314 ("Zeta")
8315 ("Eta")
8316 ("Theta")
8317 ("Iota")
8318 ("Kappa")
8319 ("Lambda")
8320 ("Mu")
8321 ("Nu")
8322 ("Xi")
8323 ("Omicron")
8324 ("Pi")
8325 ("Rho")
8326 ("Sigma")
8327 ("Tau")
8328 ("Upsilon")
8329 ("Phi")
8330 ("Chi")
8331 ("Psi")
8332 ("Omega")
8333 ("alpha")
8334 ("beta")
8335 ("gamma")
8336 ("delta")
8337 ("epsilon")
8338 ("varepsilon"."&epsilon;")
8339 ("zeta")
8340 ("eta")
8341 ("theta")
8342 ("iota")
8343 ("kappa")
8344 ("lambda")
8345 ("mu")
8346 ("nu")
8347 ("xi")
8348 ("omicron")
8349 ("pi")
8350 ("rho")
8351 ("sigmaf") ("varsigma"."&sigmaf;")
8352 ("sigma")
8353 ("tau")
8354 ("upsilon")
8355 ("phi")
8356 ("chi")
8357 ("psi")
8358 ("omega")
8359 ("thetasym") ("vartheta"."&thetasym;")
8360 ("upsih")
8361 ("piv")
8362 ("bull") ("bullet"."&bull;")
8363 ("hellip") ("dots"."&hellip;")
8364 ("prime")
8365 ("Prime")
8366 ("oline")
8367 ("frasl")
8368 ("weierp")
8369 ("image")
8370 ("real")
8371 ("trade")
8372 ("alefsym")
8373 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8374 ("uarr") ("uparrow"."&uarr;")
8375 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8376 ("darr")("downarrow"."&darr;")
8377 ("harr") ("leftrightarrow"."&harr;")
8378 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8379 ("lArr") ("Leftarrow"."&lArr;")
8380 ("uArr") ("Uparrow"."&uArr;")
8381 ("rArr") ("Rightarrow"."&rArr;")
8382 ("dArr") ("Downarrow"."&dArr;")
8383 ("hArr") ("Leftrightarrow"."&hArr;")
8384 ("forall")
8385 ("part") ("partial"."&part;")
8386 ("exist") ("exists"."&exist;")
8387 ("empty") ("emptyset"."&empty;")
8388 ("nabla")
8389 ("isin") ("in"."&isin;")
8390 ("notin")
8391 ("ni")
8392 ("prod")
8393 ("sum")
8394 ("minus")
8395 ("lowast") ("ast"."&lowast;")
8396 ("radic")
8397 ("prop") ("proptp"."&prop;")
8398 ("infin") ("infty"."&infin;")
8399 ("ang") ("angle"."&ang;")
8400 ("and") ("vee"."&and;")
8401 ("or") ("wedge"."&or;")
8402 ("cap")
8403 ("cup")
8404 ("int")
8405 ("there4")
8406 ("sim")
8407 ("cong") ("simeq"."&cong;")
8408 ("asymp")("approx"."&asymp;")
8409 ("ne") ("neq"."&ne;")
8410 ("equiv")
8411 ("le")
8412 ("ge")
8413 ("sub") ("subset"."&sub;")
8414 ("sup") ("supset"."&sup;")
8415 ("nsub")
8416 ("sube")
8417 ("supe")
8418 ("oplus")
8419 ("otimes")
8420 ("perp")
8421 ("sdot") ("cdot"."&sdot;")
8422 ("lceil")
8423 ("rceil")
8424 ("lfloor")
8425 ("rfloor")
8426 ("lang")
8427 ("rang")
8428 ("loz") ("Diamond"."&loz;")
8429 ("spades") ("spadesuit"."&spades;")
8430 ("clubs") ("clubsuit"."&clubs;")
8431 ("hearts") ("diamondsuit"."&hearts;")
8432 ("diams") ("diamondsuit"."&diams;")
8433 ("quot")
8434 ("amp")
8435 ("lt")
8436 ("gt")
8437 ("OElig")
8438 ("oelig")
8439 ("Scaron")
8440 ("scaron")
8441 ("Yuml")
8442 ("circ")
8443 ("tilde")
8444 ("ensp")
8445 ("emsp")
8446 ("thinsp")
8447 ("zwnj")
8448 ("zwj")
8449 ("lrm")
8450 ("rlm")
8451 ("ndash")
8452 ("mdash")
8453 ("lsquo")
8454 ("rsquo")
8455 ("sbquo")
8456 ("ldquo")
8457 ("rdquo")
8458 ("bdquo")
8459 ("dagger")
8460 ("Dagger")
8461 ("permil")
8462 ("lsaquo")
8463 ("rsaquo")
8464 ("euro")
8465
8466 ("arccos"."arccos")
8467 ("arcsin"."arcsin")
8468 ("arctan"."arctan")
8469 ("arg"."arg")
8470 ("cos"."cos")
8471 ("cosh"."cosh")
8472 ("cot"."cot")
8473 ("coth"."coth")
8474 ("csc"."csc")
8475 ("deg"."deg")
8476 ("det"."det")
8477 ("dim"."dim")
8478 ("exp"."exp")
8479 ("gcd"."gcd")
8480 ("hom"."hom")
8481 ("inf"."inf")
8482 ("ker"."ker")
8483 ("lg"."lg")
8484 ("lim"."lim")
8485 ("liminf"."liminf")
8486 ("limsup"."limsup")
8487 ("ln"."ln")
8488 ("log"."log")
8489 ("max"."max")
8490 ("min"."min")
8491 ("Pr"."Pr")
8492 ("sec"."sec")
8493 ("sin"."sin")
8494 ("sinh"."sinh")
8495 ("sup"."sup")
8496 ("tan"."tan")
8497 ("tanh"."tanh")
8498 )
8499 "Entities for TeX->HTML translation.
8500 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8501 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8502 In that case, \"\\ent\" will be translated to \"&other;\".
8503 The list contains HTML entities for Latin-1, Greek and other symbols.
8504 It is supplemented by a number of commonly used TeX macros with appropriate
8505 translations. There is currently no way for users to extend this.")
8506
8507 (defvar org-last-level nil) ; dynamically scoped variable
8508
8509 (defun org-export-as-ascii (arg)
8510 "Export the outline as a pretty ASCII file.
8511 If there is an active region, export only the region.
8512 The prefix ARG specifies how many levels of the outline should become
8513 underlined headlines. The default is 3."
8514 (interactive "P")
8515 (setq-default org-todo-line-regexp org-todo-line-regexp)
8516 (let* ((region
8517 (buffer-substring
8518 (if (org-region-active-p) (region-beginning) (point-min))
8519 (if (org-region-active-p) (region-end) (point-max))))
8520 (lines (org-export-find-first-heading-line
8521 (org-skip-comments (org-split-string region "[\r\n]"))))
8522 (org-startup-with-deadline-check nil)
8523 (level 0) line txt
8524 (umax nil)
8525 (case-fold-search nil)
8526 (filename (concat (file-name-sans-extension (buffer-file-name))
8527 ".txt"))
8528 (buffer (find-file-noselect filename))
8529 (levels-open (make-vector org-level-max nil))
8530 (date (format-time-string "%Y/%m/%d" (current-time)))
8531 (time (format-time-string "%X" (current-time)))
8532 (author user-full-name)
8533 (title (buffer-name))
8534 (options nil)
8535 (email user-mail-address)
8536 (language org-export-default-language)
8537 (text nil)
8538 (todo nil)
8539 (lang-words nil))
8540
8541 (setq org-last-level 1)
8542 (org-init-section-numbers)
8543
8544 (find-file-noselect filename)
8545
8546 ;; Search for the export key lines
8547 (org-parse-key-lines)
8548
8549 (setq lang-words (or (assoc language org-export-language-setup)
8550 (assoc "en" org-export-language-setup)))
8551 (if org-export-ascii-show-new-buffer
8552 (switch-to-buffer-other-window buffer)
8553 (set-buffer buffer))
8554 (erase-buffer)
8555 (fundamental-mode)
8556 (if options (org-parse-export-options options))
8557 (setq umax (if arg (prefix-numeric-value arg)
8558 org-export-headline-levels))
8559
8560 ;; File header
8561 (if title (org-insert-centered title ?=))
8562 (insert "\n")
8563 (if (or author email)
8564 (insert (concat (nth 1 lang-words) ": " (or author "")
8565 (if email (concat " <" email ">") "")
8566 "\n")))
8567 (if (and date time)
8568 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8569 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8570
8571 (insert "\n\n")
8572
8573 (if org-export-with-toc
8574 (progn
8575 (insert (nth 3 lang-words) "\n"
8576 (make-string (length (nth 3 lang-words)) ?=) "\n")
8577 (mapcar '(lambda (line)
8578 (if (string-match org-todo-line-regexp
8579 line)
8580 ;; This is a headline
8581 (progn
8582 (setq level (- (match-end 1) (match-beginning 1))
8583 txt (match-string 3 line)
8584 todo
8585 (or (and (match-beginning 2)
8586 (not (equal (match-string 2 line)
8587 org-done-string)))
8588 ; TODO, not DONE
8589 (and (= level umax)
8590 (org-search-todo-below
8591 line lines level))))
8592 (setq txt (org-html-expand-for-ascii txt))
8593
8594 (if org-export-with-section-numbers
8595 (setq txt (concat (org-section-number level)
8596 " " txt)))
8597 (if (<= level umax)
8598 (progn
8599 (insert
8600 (make-string (* (1- level) 4) ?\ )
8601 (format (if todo "%s (*)\n" "%s\n") txt))
8602 (setq org-last-level level))
8603 ))))
8604 lines)))
8605
8606 (org-init-section-numbers)
8607 (while (setq line (pop lines))
8608 ;; Remove the quoted HTML tags.
8609 (setq line (org-html-expand-for-ascii line))
8610 (cond
8611 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8612 ;; a Headline
8613 (setq level (- (match-end 1) (match-beginning 1))
8614 txt (match-string 2 line))
8615 (org-ascii-level-start level txt umax))
8616 (t (insert line "\n"))))
8617 (normal-mode)
8618 (save-buffer)
8619 (goto-char (point-min))))
8620
8621 (defun org-search-todo-below (line lines level)
8622 "Search the subtree below LINE for any TODO entries."
8623 (let ((rest (cdr (memq line lines)))
8624 (re org-todo-line-regexp)
8625 line lv todo)
8626 (catch 'exit
8627 (while (setq line (pop rest))
8628 (if (string-match re line)
8629 (progn
8630 (setq lv (- (match-end 1) (match-beginning 1))
8631 todo (and (match-beginning 2)
8632 (not (equal (match-string 2 line)
8633 org-done-string))))
8634 ; TODO, not DONE
8635 (if (<= lv level) (throw 'exit nil))
8636 (if todo (throw 'exit t))))))))
8637
8638 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8639 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8640 (defun org-html-expand-for-ascii (line)
8641 "Handle quoted HTML for ASCII export."
8642 (if org-export-html-expand
8643 (while (string-match "@<[^<>\n]*>" line)
8644 ;; We just remove the tags for now.
8645 (setq line (replace-match "" nil nil line))))
8646 line)
8647
8648 (defun org-insert-centered (s &optional underline)
8649 "Insert the string S centered and underline it with character UNDERLINE."
8650 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8651 (insert (make-string ind ?\ ) s "\n")
8652 (if underline
8653 (insert (make-string ind ?\ )
8654 (make-string (length s) underline)
8655 "\n"))))
8656
8657 (defun org-ascii-level-start (level title umax)
8658 "Insert a new level in ASCII export."
8659 (let (char)
8660 (if (> level umax)
8661 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8662 (if (or (not (equal (char-before) ?\n))
8663 (not (equal (char-before (1- (point))) ?\n)))
8664 (insert "\n"))
8665 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8666 (if org-export-with-section-numbers
8667 (setq title (concat (org-section-number level) " " title)))
8668 (insert title "\n" (make-string (string-width title) char) "\n"))))
8669
8670 (defun org-export-copy-visible ()
8671 "Copy the visible part of the buffer to another buffer, for printing.
8672 Also removes the first line of the buffer if it specifies a mode,
8673 and all options lines."
8674 (interactive)
8675 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8676 ".txt"))
8677 (buffer (find-file-noselect filename))
8678 (ore (concat
8679 (org-make-options-regexp
8680 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8681 "STARTUP" "ARCHIVE"
8682 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8683 (if org-noutline-p "\\(\n\\|$\\)" "")))
8684 s e)
8685 (with-current-buffer buffer
8686 (erase-buffer)
8687 (text-mode))
8688 (save-excursion
8689 (setq s (goto-char (point-min)))
8690 (while (not (= (point) (point-max)))
8691 (goto-char (org-find-invisible))
8692 (append-to-buffer buffer s (point))
8693 (setq s (goto-char (org-find-visible)))))
8694 (switch-to-buffer-other-window buffer)
8695 (newline)
8696 (goto-char (point-min))
8697 (if (looking-at ".*-\\*- mode:.*\n")
8698 (replace-match ""))
8699 (while (re-search-forward ore nil t)
8700 (replace-match ""))
8701 (goto-char (point-min))))
8702
8703 (defun org-find-visible ()
8704 (if (featurep 'noutline)
8705 (let ((s (point)))
8706 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8707 (get-char-property s 'invisible)))
8708 s)
8709 (skip-chars-forward "^\n")
8710 (point)))
8711 (defun org-find-invisible ()
8712 (if (featurep 'noutline)
8713 (let ((s (point)))
8714 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8715 (not (get-char-property s 'invisible))))
8716 s)
8717 (skip-chars-forward "^\r")
8718 (point)))
8719
8720 ;; HTML
8721
8722 (defun org-get-current-options ()
8723 "Return a string with current options as keyword options.
8724 Does include HTML export options as well as TODO and CATEGORY stuff."
8725 (format
8726 "#+TITLE: %s
8727 #+AUTHOR: %s
8728 #+EMAIL: %s
8729 #+LANGUAGE: %s
8730 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8731 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8732 #+CATEGORY: %s
8733 #+SEQ_TODO: %s
8734 #+TYP_TODO: %s
8735 #+STARTUP: %s %s
8736 #+ARCHIVE: %s
8737 "
8738 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8739 org-export-headline-levels
8740 org-export-with-section-numbers
8741 org-export-with-toc
8742 org-export-preserve-breaks
8743 org-export-html-expand
8744 org-export-with-fixed-width
8745 org-export-with-tables
8746 org-export-with-sub-superscripts
8747 org-export-with-emphasize
8748 org-export-with-TeX-macros
8749 (file-name-nondirectory (buffer-file-name))
8750 (if (equal org-todo-interpretation 'sequence)
8751 (mapconcat 'identity org-todo-keywords " ")
8752 "TODO FEEDBACK VERIFY DONE")
8753 (if (equal org-todo-interpretation 'type)
8754 (mapconcat 'identity org-todo-keywords " ")
8755 "Me Jason Marie DONE")
8756 (cdr (assoc org-startup-folded
8757 '((nil . "nofold")(t . "fold")(content . "content"))))
8758 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8759 org-archive-location
8760 ))
8761
8762 (defun org-insert-export-options-template ()
8763 "Insert into the buffer a template with information for exporting."
8764 (interactive)
8765 (if (not (bolp)) (newline))
8766 (let ((s (org-get-current-options)))
8767 (and (string-match "#\\+CATEGORY" s)
8768 (setq s (substring s 0 (match-beginning 0))))
8769 (insert s)))
8770
8771 (defun org-toggle-fixed-width-section (arg)
8772 "Toggle the fixed-width export.
8773 If there is no active region, the QUOTE keyword at the current headline is
8774 inserted or removed. When present, it causes the text between this headline
8775 and the next to be exported as fixed-width text, and unmodified.
8776 If there is an active region, this command adds or removes a colon as the
8777 first character of this line. If the first character of a line is a colon,
8778 this line is also exported in fixed-width font."
8779 (interactive "P")
8780 (let* ((cc 0)
8781 (regionp (org-region-active-p))
8782 (beg (if regionp (region-beginning) (point)))
8783 (end (if regionp (region-end)))
8784 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8785 (re "[ \t]*\\(:\\)")
8786 off)
8787 (if regionp
8788 (save-excursion
8789 (goto-char beg)
8790 (setq cc (current-column))
8791 (beginning-of-line 1)
8792 (setq off (looking-at re))
8793 (while (> nlines 0)
8794 (setq nlines (1- nlines))
8795 (beginning-of-line 1)
8796 (cond
8797 (arg
8798 (move-to-column cc t)
8799 (insert ":\n")
8800 (forward-line -1))
8801 ((and off (looking-at re))
8802 (replace-match "" t t nil 1))
8803 ((not off) (move-to-column cc t) (insert ":")))
8804 (forward-line 1)))
8805 (save-excursion
8806 (org-back-to-heading)
8807 (if (looking-at (concat outline-regexp
8808 "\\( +\\<" org-quote-string "\\>\\)"))
8809 (replace-match "" t t nil 1)
8810 (if (looking-at outline-regexp)
8811 (progn
8812 (goto-char (match-end 0))
8813 (insert " " org-quote-string))))))))
8814
8815 (defun org-export-as-html-and-open (arg)
8816 "Export the outline as HTML and immediately open it with a browser.
8817 If there is an active region, export only the region.
8818 The prefix ARG specifies how many levels of the outline should become
8819 headlines. The default is 3. Lower levels will become bulleted lists."
8820 (interactive "P")
8821 (org-export-as-html arg 'hidden)
8822 (org-open-file (buffer-file-name)))
8823
8824 (defun org-export-as-html-batch ()
8825 "Call `org-export-as-html', may be used in batch processing as
8826 emacs --batch
8827 --load=$HOME/lib/emacs/org.el
8828 --eval \"(setq org-export-headline-levels 2)\"
8829 --visit=MyFile --funcall org-export-as-html-batch"
8830 (org-export-as-html org-export-headline-levels 'hidden))
8831
8832 (defun org-export-as-html (arg &optional hidden)
8833 "Export the outline as a pretty HTML file.
8834 If there is an active region, export only the region.
8835 The prefix ARG specifies how many levels of the outline should become
8836 headlines. The default is 3. Lower levels will become bulleted lists."
8837 (interactive "P")
8838 (setq-default org-todo-line-regexp org-todo-line-regexp)
8839 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8840 (setq-default org-done-string org-done-string)
8841 (let* ((region-p (org-region-active-p))
8842 (region
8843 (buffer-substring
8844 (if region-p (region-beginning) (point-min))
8845 (if region-p (region-end) (point-max))))
8846 (all_lines
8847 (org-skip-comments (org-split-string region "[\r\n]")))
8848 (lines (org-export-find-first-heading-line all_lines))
8849 (level 0) (line "") (origline "") txt todo
8850 (umax nil)
8851 (filename (concat (file-name-sans-extension (buffer-file-name))
8852 ".html"))
8853 (buffer (find-file-noselect filename))
8854 (levels-open (make-vector org-level-max nil))
8855 (date (format-time-string "%Y/%m/%d" (current-time)))
8856 (time (format-time-string "%X" (current-time)))
8857 (author user-full-name)
8858 (title (buffer-name))
8859 (options nil)
8860 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
8861 (inquote nil)
8862 (email user-mail-address)
8863 (language org-export-default-language)
8864 (text nil)
8865 (lang-words nil)
8866 (head-count 0) cnt
8867 (start 0)
8868 ;; FIXME: The following returns always nil under XEmacs
8869 (coding-system (and (fboundp 'coding-system-get)
8870 (boundp 'buffer-file-coding-system)
8871 buffer-file-coding-system))
8872 (coding-system-for-write (or coding-system coding-system-for-write))
8873 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
8874 (charset (and coding-system
8875 (coding-system-get coding-system 'mime-charset)))
8876 table-open type
8877 table-buffer table-orig-buffer
8878 )
8879 (message "Exporting...")
8880
8881 (setq org-last-level 1)
8882 (org-init-section-numbers)
8883
8884 ;; Search for the export key lines
8885 (org-parse-key-lines)
8886 (setq lang-words (or (assoc language org-export-language-setup)
8887 (assoc "en" org-export-language-setup)))
8888
8889 ;; Switch to the output buffer
8890 (if (or hidden (not org-export-html-show-new-buffer))
8891 (set-buffer buffer)
8892 (switch-to-buffer-other-window buffer))
8893 (erase-buffer)
8894 (fundamental-mode)
8895 (let ((case-fold-search nil))
8896 (if options (org-parse-export-options options))
8897 (setq umax (if arg (prefix-numeric-value arg)
8898 org-export-headline-levels))
8899
8900 ;; File header
8901 (insert (format
8902 "<html lang=\"%s\"><head>
8903 <title>%s</title>
8904 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
8905 <meta name=generator content=\"Org-mode\">
8906 <meta name=generated content=\"%s %s\">
8907 <meta name=author content=\"%s\">
8908 </head><body>
8909 "
8910 language (org-html-expand title) (or charset "iso-8859-1")
8911 date time author))
8912 (if title (insert (concat "<H1 align=\"center\">"
8913 (org-html-expand title) "</H1>\n")))
8914 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8915 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8916 email "&gt;</a>\n")))
8917 (if (or author email) (insert "<br>\n"))
8918 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8919 date " " time "<br>\n")))
8920 (if text (insert (concat "<p>\n" (org-html-expand text))))
8921 (if org-export-with-toc
8922 (progn
8923 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8924 (insert "<ul>\n")
8925 (mapcar '(lambda (line)
8926 (if (string-match org-todo-line-regexp line)
8927 ;; This is a headline
8928 (progn
8929 (setq level (- (match-end 1) (match-beginning 1))
8930 txt (save-match-data
8931 (org-html-expand
8932 (match-string 3 line)))
8933 todo
8934 (or (and (match-beginning 2)
8935 (not (equal (match-string 2 line)
8936 org-done-string)))
8937 ; TODO, not DONE
8938 (and (= level umax)
8939 (org-search-todo-below
8940 line lines level))))
8941 (if org-export-with-section-numbers
8942 (setq txt (concat (org-section-number level)
8943 " " txt)))
8944 (if (<= level umax)
8945 (progn
8946 (setq head-count (+ head-count 1))
8947 (if (> level org-last-level)
8948 (progn
8949 (setq cnt (- level org-last-level))
8950 (while (>= (setq cnt (1- cnt)) 0)
8951 (insert "<ul>"))
8952 (insert "\n")))
8953 (if (< level org-last-level)
8954 (progn
8955 (setq cnt (- org-last-level level))
8956 (while (>= (setq cnt (1- cnt)) 0)
8957 (insert "</ul>"))
8958 (insert "\n")))
8959 (insert
8960 (format
8961 (if todo
8962 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8963 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8964 head-count txt))
8965 (setq org-last-level level))
8966 ))))
8967 lines)
8968 (while (> org-last-level 0)
8969 (setq org-last-level (1- org-last-level))
8970 (insert "</ul>\n"))
8971 ))
8972 (setq head-count 0)
8973 (org-init-section-numbers)
8974
8975 (while (setq line (pop lines) origline line)
8976 ;; end of quote?
8977 (when (and inquote (string-match "^\\*+" line))
8978 (insert "</pre>\n")
8979 (setq inquote nil))
8980 ;; inquote
8981 (if inquote
8982 (progn
8983 (insert line "\n")
8984 (setq line (org-html-expand line))) ;;????? FIXME: not needed?
8985
8986 ;; Protect the links
8987 (setq start 0)
8988 (while (string-match org-link-maybe-angles-regexp line start)
8989 (setq start (match-end 0))
8990 (setq line (replace-match
8991 (concat "\000" (match-string 1 line) "\000")
8992 t t line)))
8993
8994 ;; replace "<" and ">" by "&lt;" and "&gt;"
8995 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8996 (setq line (org-html-expand line))
8997
8998 ;; Verbatim lines
8999 (if (and org-export-with-fixed-width
9000 (string-match "^[ \t]*:\\(.*\\)" line))
9001 (progn
9002 (let ((l (match-string 1 line)))
9003 (while (string-match " " l)
9004 (setq l (replace-match "&nbsp;" t t l)))
9005 (insert "\n<span style='font-family:Courier'>"
9006 l "</span>"
9007 (if (and lines
9008 (not (string-match "^[ \t]+\\(:.*\\)"
9009 (car lines))))
9010 "<br>\n" "\n"))))
9011
9012 (setq start 0)
9013 (while (string-match org-protected-link-regexp line start)
9014 (setq start (- (match-end 0) 2))
9015 (setq type (match-string 1 line))
9016 (cond
9017 ((member type '("http" "https" "ftp" "mailto" "news"))
9018 ;; standard URL
9019 (setq line (replace-match
9020 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
9021 "<a href=\"\\1:\\2\">\\1:\\2</a>"
9022 nil nil line)))
9023 ((string= type "file")
9024 ;; FILE link
9025 (let* ((filename (match-string 2 line))
9026 (abs-p (file-name-absolute-p filename))
9027 (thefile (if abs-p (expand-file-name filename) filename))
9028 (thefile (save-match-data
9029 (if (string-match ":[0-9]+$" thefile)
9030 (replace-match "" t t thefile)
9031 thefile)))
9032 (file-is-image-p
9033 (save-match-data
9034 (string-match (org-image-file-name-regexp) thefile))))
9035 (setq line (replace-match
9036 (if (and org-export-html-inline-images
9037 file-is-image-p)
9038 (concat "<img src=\"" thefile "\"/>")
9039 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
9040 nil nil line))))
9041
9042 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
9043 (setq line (replace-match
9044 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
9045
9046 ;; TODO items
9047 (if (and (string-match org-todo-line-regexp line)
9048 (match-beginning 2))
9049 (if (equal (match-string 2 line) org-done-string)
9050 (setq line (replace-match
9051 "<span style='color:green'>\\2</span>"
9052 nil nil line 2))
9053 (setq line (replace-match "<span style='color:red'>\\2</span>"
9054 nil nil line 2))))
9055
9056 ;; DEADLINES
9057 (if (string-match org-deadline-line-regexp line)
9058 (progn
9059 (if (save-match-data
9060 (string-match "<a href"
9061 (substring line 0 (match-beginning 0))))
9062 nil ; Don't do the replacement - it is inside a link
9063 (setq line (replace-match "<span style='color:red'>\\&</span>"
9064 nil nil line 1)))))
9065
9066
9067 (cond
9068 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9069 ;; This is a headline
9070 (setq level (- (match-end 1) (match-beginning 1))
9071 txt (match-string 2 line))
9072 (if (<= level umax) (setq head-count (+ head-count 1)))
9073 (org-html-level-start level txt umax
9074 (and org-export-with-toc (<= level umax))
9075 head-count)
9076 ;; QUOTES
9077 (when (string-match quote-re line)
9078 (insert "<pre>")
9079 (setq inquote t)))
9080
9081 ((and org-export-with-tables
9082 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9083 (if (not table-open)
9084 ;; New table starts
9085 (setq table-open t table-buffer nil table-orig-buffer nil))
9086 ;; Accumulate lines
9087 (setq table-buffer (cons line table-buffer)
9088 table-orig-buffer (cons origline table-orig-buffer))
9089 (when (or (not lines)
9090 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9091 (car lines))))
9092 (setq table-open nil
9093 table-buffer (nreverse table-buffer)
9094 table-orig-buffer (nreverse table-orig-buffer))
9095 (insert (org-format-table-html table-buffer table-orig-buffer))))
9096 (t
9097 ;; Normal lines
9098 ;; Lines starting with "-", and empty lines make new paragraph.
9099 ;; FIXME: Should we add + and *?
9100 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
9101 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9102 )))
9103 (if org-export-html-with-timestamp
9104 (insert org-export-html-html-helper-timestamp))
9105 (insert "</body>\n</html>\n")
9106 (debug)
9107 (normal-mode)
9108 (save-buffer)
9109 (goto-char (point-min)))))
9110
9111 (defun org-format-table-html (lines olines)
9112 "Find out which HTML converter to use and return the HTML code."
9113 (if (string-match "^[ \t]*|" (car lines))
9114 ;; A normal org table
9115 (org-format-org-table-html lines)
9116 ;; Table made by table.el - test for spanning
9117 (let* ((hlines (delq nil (mapcar
9118 (lambda (x)
9119 (if (string-match "^[ \t]*\\+-" x) x
9120 nil))
9121 lines)))
9122 (first (car hlines))
9123 (ll (and (string-match "\\S-+" first)
9124 (match-string 0 first)))
9125 (re (concat "^[ \t]*" (regexp-quote ll)))
9126 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9127 hlines))))
9128 (if (and (not spanning)
9129 (not org-export-prefer-native-exporter-for-tables))
9130 ;; We can use my own converter with HTML conversions
9131 (org-format-table-table-html lines)
9132 ;; Need to use the code generator in table.el, with the original text.
9133 (org-format-table-table-html-using-table-generate-source olines)))))
9134
9135 (defun org-format-org-table-html (lines)
9136 "Format a table into html."
9137 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9138 (setq lines (nreverse lines))
9139 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9140 (setq lines (nreverse lines))
9141 (let ((head (and org-export-highlight-first-table-line
9142 (delq nil (mapcar
9143 (lambda (x) (string-match "^[ \t]*|-" x))
9144 (cdr lines)))))
9145 line fields html)
9146 (setq html (concat org-export-html-table-tag "\n"))
9147 (while (setq line (pop lines))
9148 (catch 'next-line
9149 (if (string-match "^[ \t]*|-" line)
9150 (progn
9151 (setq head nil) ;; head ends here, first time around
9152 ;; ignore this line
9153 (throw 'next-line t)))
9154 ;; Break the line into fields
9155 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9156 (setq html (concat
9157 html
9158 "<tr>"
9159 (mapconcat (lambda (x)
9160 (if head
9161 (concat "<th>" x "</th>")
9162 (concat "<td valign=\"top\">" x "</td>")))
9163 fields "")
9164 "</tr>\n"))))
9165 (setq html (concat html "</table>\n"))
9166 html))
9167
9168 (defun org-fake-empty-table-line (line)
9169 "Replace everything except \"|\" with spaces."
9170 (let ((i (length line))
9171 (newstr (copy-sequence line)))
9172 (while (> i 0)
9173 (setq i (1- i))
9174 (if (not (eq (aref newstr i) ?|))
9175 (aset newstr i ?\ )))
9176 newstr))
9177
9178 (defun org-format-table-table-html (lines)
9179 "Format a table generated by table.el into html.
9180 This conversion does *not* use `table-generate-source' from table.el.
9181 This has the advantage that Org-mode's HTML conversions can be used.
9182 But it has the disadvantage, that no cell- or row-spanning is allowed."
9183 (let (line field-buffer
9184 (head org-export-highlight-first-table-line)
9185 fields html empty)
9186 (setq html (concat org-export-html-table-tag "\n"))
9187 (while (setq line (pop lines))
9188 (setq empty "&nbsp")
9189 (catch 'next-line
9190 (if (string-match "^[ \t]*\\+-" line)
9191 (progn
9192 (if field-buffer
9193 (progn
9194 (setq html (concat
9195 html
9196 "<tr>"
9197 (mapconcat
9198 (lambda (x)
9199 (if (equal x "") (setq x empty))
9200 (if head
9201 (concat "<th valign=\"top\">" x
9202 "</th>\n")
9203 (concat "<td valign=\"top\">" x
9204 "</td>\n")))
9205 field-buffer "\n")
9206 "</tr>\n"))
9207 (setq head nil)
9208 (setq field-buffer nil)))
9209 ;; Ignore this line
9210 (throw 'next-line t)))
9211 ;; Break the line into fields and store the fields
9212 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9213 (if field-buffer
9214 (setq field-buffer (mapcar
9215 (lambda (x)
9216 (concat x "<br>" (pop fields)))
9217 field-buffer))
9218 (setq field-buffer fields))))
9219 (setq html (concat html "</table>\n"))
9220 html))
9221
9222 (defun org-format-table-table-html-using-table-generate-source (lines)
9223 "Format a table into html, using `table-generate-source' from table.el.
9224 This has the advantage that cell- or row-spanning is allowed.
9225 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9226 (require 'table)
9227 (with-current-buffer (get-buffer-create " org-tmp1 ")
9228 (erase-buffer)
9229 (insert (mapconcat 'identity lines "\n"))
9230 (goto-char (point-min))
9231 (if (not (re-search-forward "|[^+]" nil t))
9232 (error "Error processing table"))
9233 (table-recognize-table)
9234 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9235 (table-generate-source 'html " org-tmp2 ")
9236 (set-buffer " org-tmp2 ")
9237 (buffer-substring (point-min) (point-max))))
9238
9239 (defun org-html-expand (string)
9240 "Prepare STRING for HTML export. Applies all active conversions."
9241 ;; First check if there is a link in the line - if yes, apply conversions
9242 ;; only before the start of the link.
9243 (let* ((m (string-match org-link-regexp string))
9244 (s (if m (substring string 0 m) string))
9245 (r (if m (substring string m) "")))
9246 ;; convert < to &lt; and > to &gt;
9247 (while (string-match "<" s)
9248 (setq s (replace-match "&lt;" t t s)))
9249 (while (string-match ">" s)
9250 (setq s (replace-match "&gt;" t t s)))
9251 (if org-export-html-expand
9252 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9253 (setq s (replace-match "<\\1>" nil nil s))))
9254 (if org-export-with-emphasize
9255 (setq s (org-export-html-convert-emphasize s)))
9256 (if org-export-with-sub-superscripts
9257 (setq s (org-export-html-convert-sub-super s)))
9258 (if org-export-with-TeX-macros
9259 (let ((start 0) wd ass)
9260 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9261 (setq wd (match-string 1 s))
9262 (if (setq ass (assoc wd org-html-entities))
9263 (setq s (replace-match (or (cdr ass)
9264 (concat "&" (car ass) ";"))
9265 t t s))
9266 (setq start (+ start (length wd)))))))
9267 (concat s r)))
9268
9269 (defun org-create-multibrace-regexp (left right n)
9270 "Create a regular expression which will match a balanced sexp.
9271 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9272 as single character strings.
9273 The regexp returned will match the entire expression including the
9274 delimiters. It will also define a single group which contains the
9275 match except for the outermost delimiters. The maximum depth of
9276 stacked delimiters is N. Escaping delimiters is not possible."
9277 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9278 (or "\\|")
9279 (re nothing)
9280 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9281 (while (> n 1)
9282 (setq n (1- n)
9283 re (concat re or next)
9284 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9285 (concat left "\\(" re "\\)" right)))
9286
9287 (defvar org-match-substring-regexp
9288 (concat
9289 "\\([^\\]\\)\\([_^]\\)\\("
9290 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9291 "\\|"
9292 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9293 "\\|"
9294 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9295 "The regular expression matching a sub- or superscript.")
9296
9297 (defun org-export-html-convert-sub-super (string)
9298 "Convert sub- and superscripts in STRING to HTML."
9299 (let (key c)
9300 (while (string-match org-match-substring-regexp string)
9301 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9302 (setq c (or (match-string 8 string)
9303 (match-string 6 string)
9304 (match-string 5 string)))
9305 (setq string (replace-match
9306 (concat (match-string 1 string)
9307 "<" key ">" c "</" key ">")
9308 t t string)))
9309 (while (string-match "\\\\\\([_^]\\)" string)
9310 (setq string (replace-match (match-string 1 string) t t string))))
9311 string)
9312
9313 (defun org-export-html-convert-emphasize (string)
9314 (while (string-match
9315 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9316 string)
9317 (setq string (replace-match
9318 (concat "<b>" (match-string 3 string) "</b>")
9319 t t string 2)))
9320 (while (string-match
9321 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9322 string)
9323 (setq string (replace-match
9324 (concat "<i>" (match-string 3 string) "</i>")
9325 t t string 2)))
9326 (while (string-match
9327 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9328 string)
9329 (setq string (replace-match
9330 (concat "<u>" (match-string 3 string) "</u>")
9331 t t string 2)))
9332 string)
9333
9334 (defun org-parse-key-lines ()
9335 "Find the special key lines with the information for exporters."
9336 (save-excursion
9337 (goto-char 0)
9338 (let ((re (org-make-options-regexp
9339 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9340 key)
9341 (while (re-search-forward re nil t)
9342 (setq key (match-string 1))
9343 (cond ((string-equal key "TITLE")
9344 (setq title (match-string 2)))
9345 ((string-equal key "AUTHOR")
9346 (setq author (match-string 2)))
9347 ((string-equal key "EMAIL")
9348 (setq email (match-string 2)))
9349 ((string-equal key "LANGUAGE")
9350 (setq language (match-string 2)))
9351 ((string-equal key "TEXT")
9352 (setq text (concat text "\n" (match-string 2))))
9353 ((string-equal key "OPTIONS")
9354 (setq options (match-string 2))))))))
9355
9356 (defun org-parse-export-options (s)
9357 "Parse the export options line."
9358 (let ((op '(("H" . org-export-headline-levels)
9359 ("num" . org-export-with-section-numbers)
9360 ("toc" . org-export-with-toc)
9361 ("\\n" . org-export-preserve-breaks)
9362 ("@" . org-export-html-expand)
9363 (":" . org-export-with-fixed-width)
9364 ("|" . org-export-with-tables)
9365 ("^" . org-export-with-sub-superscripts)
9366 ("*" . org-export-with-emphasize)
9367 ("TeX" . org-export-with-TeX-macros)))
9368 o)
9369 (while (setq o (pop op))
9370 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9371 s)
9372 (set (make-local-variable (cdr o))
9373 (car (read-from-string (match-string 1 s))))))))
9374
9375 (defun org-html-level-start (level title umax with-toc head-count)
9376 "Insert a new level in HTML export."
9377 (let ((l (1+ (max level umax))))
9378 (while (<= l org-level-max)
9379 (if (aref levels-open (1- l))
9380 (progn
9381 (org-html-level-close l)
9382 (aset levels-open (1- l) nil)))
9383 (setq l (1+ l)))
9384 (if (> level umax)
9385 (progn
9386 (if (aref levels-open (1- level))
9387 (insert "<li>" title "<p>\n")
9388 (aset levels-open (1- level) t)
9389 (insert "<ul><li>" title "<p>\n")))
9390 (if org-export-with-section-numbers
9391 (setq title (concat (org-section-number level) " " title)))
9392 (setq level (+ level 1))
9393 (if with-toc
9394 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9395 level head-count title level))
9396 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9397
9398 (defun org-html-level-close (&rest args)
9399 "Terminate one level in HTML export."
9400 (insert "</ul>"))
9401
9402
9403 ;; Variable holding the vector with section numbers
9404 (defvar org-section-numbers (make-vector org-level-max 0))
9405
9406 (defun org-init-section-numbers ()
9407 "Initialize the vector for the section numbers."
9408 (let* ((level -1)
9409 (numbers (nreverse (org-split-string "" "\\.")))
9410 (depth (1- (length org-section-numbers)))
9411 (i depth) number-string)
9412 (while (>= i 0)
9413 (if (> i level)
9414 (aset org-section-numbers i 0)
9415 (setq number-string (or (car numbers) "0"))
9416 (if (string-match "\\`[A-Z]\\'" number-string)
9417 (aset org-section-numbers i
9418 (- (string-to-char number-string) ?A -1))
9419 (aset org-section-numbers i (string-to-number number-string)))
9420 (pop numbers))
9421 (setq i (1- i)))))
9422
9423 (defun org-section-number (&optional level)
9424 "Return a string with the current section number.
9425 When LEVEL is non-nil, increase section numbers on that level."
9426 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9427 (when level
9428 (when (> level -1)
9429 (aset org-section-numbers
9430 level (1+ (aref org-section-numbers level))))
9431 (setq idx (1+ level))
9432 (while (<= idx depth)
9433 (if (not (= idx 1))
9434 (aset org-section-numbers idx 0))
9435 (setq idx (1+ idx))))
9436 (setq idx 0)
9437 (while (<= idx depth)
9438 (setq n (aref org-section-numbers idx))
9439 (setq string (concat string (if (not (string= string "")) "." "")
9440 (int-to-string n)))
9441 (setq idx (1+ idx)))
9442 (save-match-data
9443 (if (string-match "\\`\\([@0]\\.\\)+" string)
9444 (setq string (replace-match "" nil nil string)))
9445 (if (string-match "\\(\\.0\\)+\\'" string)
9446 (setq string (replace-match "" nil nil string))))
9447 string))
9448
9449
9450
9451
9452
9453 (defun org-export-icalendar-this-file ()
9454 "Export current file as an iCalendar file.
9455 The iCalendar file will be located in the same directory as the Org-mode
9456 file, but with extension `.ics'."
9457 (interactive)
9458 (org-export-icalendar nil (buffer-file-name)))
9459
9460 ;;;###autoload
9461 (defun org-export-icalendar-all-agenda-files ()
9462 "Export all files in `org-agenda-files' to iCalendar .ics files.
9463 Each iCalendar file will be located in the same directory as the Org-mode
9464 file, but with extension `.ics'."
9465 (interactive)
9466 (apply 'org-export-icalendar nil org-agenda-files))
9467
9468 ;;;###autoload
9469 (defun org-export-icalendar-combine-agenda-files ()
9470 "Export all files in `org-agenda-files' to a single combined iCalendar file.
9471 The file is stored under the name `org-combined-agenda-icalendar-file'."
9472 (interactive)
9473 (apply 'org-export-icalendar t org-agenda-files))
9474
9475 (defun org-export-icalendar (combine &rest files)
9476 "Create iCalendar files for all elements of FILES.
9477 If COMBINE is non-nil, combine all calendar entries into a single large
9478 file and store it under the name `org-combined-agenda-icalendar-file'."
9479 (save-excursion
9480 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
9481 (when combine
9482 (setq ical-file org-combined-agenda-icalendar-file
9483 ical-buffer (org-get-agenda-file-buffer ical-file))
9484 (set-buffer ical-buffer) (erase-buffer))
9485 (while (setq file (pop files))
9486 (catch 'nextfile
9487 (org-check-agenda-file file)
9488 (unless combine
9489 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
9490 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
9491 (set-buffer ical-buffer) (erase-buffer))
9492 (set-buffer (org-get-agenda-file-buffer file))
9493 (setq category (or org-category
9494 (file-name-sans-extension
9495 (file-name-nondirectory (buffer-file-name)))))
9496 (if (symbolp category) (setq category (symbol-name category)))
9497 (let ((standard-output ical-buffer))
9498 (if combine
9499 (and (not started) (setq started t)
9500 (org-start-icalendar-file "OrgMode"))
9501 (org-start-icalendar-file category))
9502 (org-print-icalendar-entries combine category)
9503 (when (or (and combine (not files)) (not combine))
9504 (org-finish-icalendar-file)
9505 (set-buffer ical-buffer)
9506 (save-buffer)
9507 (run-hooks 'org-after-save-iCalendar-file-hook)))))
9508 (org-release-buffers org-agenda-new-buffers))))
9509
9510 (defvar org-after-save-iCalendar-file-hook nil
9511 "Hook run after an iCalendar file has been saved.
9512 The iCalendar buffer is still current when this hook is run.
9513 A good way to use this is to tell a desktop calenndar application to re-read
9514 the iCalendar file.")
9515
9516 (defun org-print-icalendar-entries (&optional combine category)
9517 "Print iCalendar entries for the current Org-mode file to `standard-output'.
9518 When COMBINE is non nil, add the category to each line."
9519 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
9520 (dts (org-ical-ts-to-string
9521 (format-time-string (cdr org-time-stamp-formats) (current-time))
9522 "DTSTART"))
9523 hd ts ts2 state (inc t) pos scheduledp deadlinep donep tmp pri)
9524 (save-excursion
9525 (goto-char (point-min))
9526 (while (re-search-forward org-ts-regexp nil t)
9527 (setq pos (match-beginning 0)
9528 ts (match-string 0)
9529 inc t
9530 hd (org-get-heading))
9531 (if (looking-at re2)
9532 (progn
9533 (goto-char (match-end 0))
9534 (setq ts2 (match-string 1) inc nil))
9535 (setq ts2 ts
9536 tmp (buffer-substring (max (point-min)
9537 (- pos org-ds-keyword-length))
9538 pos)
9539 deadlinep (string-match org-deadline-regexp tmp)
9540 scheduledp (string-match org-scheduled-regexp tmp)
9541 donep (org-entry-is-done-p)))
9542 (if (or (string-match org-tr-regexp hd)
9543 (string-match org-ts-regexp hd))
9544 (setq hd (replace-match "" t t hd)))
9545 (if combine
9546 (setq hd (concat hd " (category " category ")")))
9547 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
9548 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
9549 (princ (format "BEGIN:VEVENT
9550 %s
9551 %s
9552 SUMMARY:%s
9553 END:VEVENT\n"
9554 (org-ical-ts-to-string ts "DTSTART")
9555 (org-ical-ts-to-string ts2 "DTEND" inc)
9556 hd)))
9557 (when org-icalendar-include-todo
9558 (goto-char (point-min))
9559 (while (re-search-forward org-todo-line-regexp nil t)
9560 (setq state (match-string 1))
9561 (unless (equal state org-done-string)
9562 (setq hd (match-string 3))
9563 (if (string-match org-priority-regexp hd)
9564 (setq pri (string-to-char (match-string 2 hd))
9565 hd (concat (substring hd 0 (match-beginning 1))
9566 (substring hd (- (match-end 1)))))
9567 (setq pri org-default-priority))
9568 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
9569 (- org-lowest-priority ?A))))))
9570
9571 (princ (format "BEGIN:VTODO
9572 %s
9573 SUMMARY:%s
9574 SEQUENCE:1
9575 PRIORITY:%d
9576 END:VTODO\n"
9577 dts hd pri))))))))
9578
9579 (defun org-start-icalendar-file (name)
9580 "Start an iCalendar file by inserting the header."
9581 (let ((user user-full-name)
9582 (calname "something")
9583 (name (or name "unknown"))
9584 (timezone "FIXME"))
9585 (princ
9586 (format "BEGIN:VCALENDAR
9587 VERSION:2.0
9588 X-WR-CALNAME:%s
9589 PRODID:-//%s//Emacs with Org-mode//EN
9590 X-WR-TIMEZONE:Europe/Amsterdam
9591 CALSCALE:GREGORIAN\n" name user timezone))))
9592
9593 (defun org-finish-icalendar-file ()
9594 "Finish an iCalendar file by inserting the END statement."
9595 (princ "END:VCALENDAR\n"))
9596
9597 (defun org-ical-ts-to-string (s keyword &optional inc)
9598 "Take a time string S and convert it to iCalendar format.
9599 KEYWORD is added in front, to make a complete line like DTSTART....
9600 When INC is non-nil, increase the hour by two (if time string contains
9601 a time), or the day by one (if it does not contain a time)."
9602 (let ((t1 (org-parse-time-string s 'nodefault))
9603 t2 fmt have-time time)
9604 (if (and (car t1) (nth 1 t1) (nth 2 t1))
9605 (setq t2 t1 have-time t)
9606 (setq t2 (org-parse-time-string s)))
9607 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
9608 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
9609 (when inc
9610 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
9611 (setq time (encode-time s mi h d m y)))
9612 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
9613 (concat keyword (format-time-string fmt time))))
9614
9615
9616 ;;; Key bindings
9617
9618 ;; - Bindings in Org-mode map are currently
9619 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9620 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9621 ;; e (?) useful from outline-mode
9622 ;; i k @ expendable from outline-mode
9623 ;; 0123456789 ! %^& ()_{} " `' free
9624
9625 ;; Make `C-c C-x' a prefix key
9626 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
9627
9628 ;; TAB key with modifiers
9629 (define-key org-mode-map "\C-i" 'org-cycle)
9630 (define-key org-mode-map [(meta tab)] 'org-complete)
9631 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
9632 ;; The following line is necessary under Suse GNU/Linux
9633 (unless org-xemacs-p
9634 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9635 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9636
9637 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9638 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
9639 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9640 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
9641 (define-key org-mode-map [(meta return)] 'org-meta-return)
9642 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
9643 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
9644
9645 ;; Cursor keys with modifiers
9646 (define-key org-mode-map [(meta left)] 'org-metaleft)
9647 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
9648 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
9649 (define-key org-mode-map [(meta right)] 'org-metaright)
9650 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
9651 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
9652 (define-key org-mode-map [(meta up)] 'org-metaup)
9653 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
9654 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
9655 (define-key org-mode-map [(meta down)] 'org-metadown)
9656 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
9657 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
9658
9659 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9660 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
9661 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9662 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
9663 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9664 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
9665 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9666 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
9667 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9668 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
9669 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9670 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
9671 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9672 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-timestamp-down-day)
9673 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9674 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-timestamp-up-day)
9675
9676 ;; All the other keys
9677 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9678 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9679 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9680 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9681 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9682 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9683 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9684 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9685 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9686 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9687 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9688 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9689 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9690 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9691 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9692 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
9693 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9694 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9695 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9696 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9697 (define-key org-mode-map "\C-c[" 'org-add-file)
9698 (define-key org-mode-map "\C-c]" 'org-remove-file)
9699 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9700 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9701 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9702 (define-key org-mode-map "\C-m" 'org-return)
9703 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9704 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9705 (define-key org-mode-map "\C-c+" 'org-table-sum)
9706 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9707 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9708 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9709 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9710 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9711 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9712 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9713 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9714 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9715 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9716 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9717 ;; OPML support is only an option for the future
9718 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9719 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9720 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
9721 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
9722 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
9723 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
9724 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9725 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9726 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9727 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
9728 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
9729
9730 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
9731 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
9732 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
9733
9734 (defsubst org-table-p () (org-at-table-p))
9735
9736 (defun org-self-insert-command (N)
9737 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9738 If the cursor is in a table looking at whitespace, the whitespace is
9739 overwritten, and the table is not marked as requiring realignment."
9740 (interactive "p")
9741 (if (and (org-table-p)
9742 (or
9743 (and org-table-auto-blank-field
9744 (member last-command
9745 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
9746 (org-table-blank-field))
9747 t)
9748 (eq N 1)
9749 (looking-at "[^|\n]* +|"))
9750 (let (org-table-may-need-update)
9751 (goto-char (1- (match-end 0)))
9752 (delete-backward-char 1)
9753 (goto-char (match-beginning 0))
9754 (self-insert-command N))
9755 (setq org-table-may-need-update t)
9756 (self-insert-command N)))
9757
9758 ;; FIXME:
9759 ;; The following two functions might still be optimized to trigger
9760 ;; re-alignment less frequently.
9761
9762 (defun org-delete-backward-char (N)
9763 "Like `delete-backward-char', insert whitespace at field end in tables.
9764 When deleting backwards, in tables this function will insert whitespace in
9765 front of the next \"|\" separator, to keep the table aligned. The table will
9766 still be marked for re-alignment, because a narrow field may lead to a
9767 reduced column width."
9768 (interactive "p")
9769 (if (and (org-table-p)
9770 (eq N 1)
9771 (string-match "|" (buffer-substring (point-at-bol) (point)))
9772 (looking-at ".*?|"))
9773 (let ((pos (point)))
9774 (backward-delete-char N)
9775 (skip-chars-forward "^|")
9776 (insert " ")
9777 (goto-char (1- pos)))
9778 (backward-delete-char N)))
9779
9780 (defun org-delete-char (N)
9781 "Like `delete-char', but insert whitespace at field end in tables.
9782 When deleting characters, in tables this function will insert whitespace in
9783 front of the next \"|\" separator, to keep the table aligned. The table
9784 will still be marked for re-alignment, because a narrow field may lead to
9785 a reduced column width."
9786 (interactive "p")
9787 (if (and (org-table-p)
9788 (not (bolp))
9789 (not (= (char-after) ?|))
9790 (eq N 1))
9791 (if (looking-at ".*?|")
9792 (let ((pos (point)))
9793 (replace-match (concat
9794 (substring (match-string 0) 1 -1)
9795 " |"))
9796 (goto-char pos)))
9797 (delete-char N)))
9798
9799 ;; How to do this: Measure non-white length of current string
9800 ;; If equal to column width, we should realign.
9801
9802 (defun org-remap (map &rest commands)
9803 "In MAP, remap the functions given in COMMANDS.
9804 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
9805 (let (new old)
9806 (while commands
9807 (setq old (pop commands) new (pop commands))
9808 (if (fboundp 'command-remapping)
9809 (define-key map (vector 'remap old) new)
9810 (substitute-key-definition old new map global-map)))))
9811
9812 (when (eq org-enable-table-editor 'optimized)
9813 ;; If the user wants maximum table support, we need to hijack
9814 ;; some standard editing functions
9815 (org-remap org-mode-map
9816 'self-insert-command 'org-self-insert-command
9817 'delete-char 'org-delete-char
9818 'delete-backward-char 'org-delete-backward-char)
9819 (define-key org-mode-map "|" 'org-force-self-insert))
9820
9821 (defun org-shiftcursor-error ()
9822 "Throw an error because Shift-Cursor command was applied in wrong context."
9823 (error "This command is only active in tables and on headlines"))
9824
9825 (defun org-shifttab ()
9826 "Global visibility cycling or move to previous table field.
9827 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
9828 See the individual commands for more information."
9829 (interactive)
9830 (cond
9831 ((org-at-table-p) (org-table-previous-field))
9832 (t (org-cycle '(4)))))
9833
9834 (defun org-shiftmetaleft ()
9835 "Promote subtree or delete table column.
9836 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
9837 See the individual commands for more information."
9838 (interactive)
9839 (cond
9840 ((org-at-table-p) (org-table-delete-column))
9841 ((org-on-heading-p) (org-promote-subtree))
9842 (t (org-shiftcursor-error))))
9843
9844 (defun org-shiftmetaright ()
9845 "Demote subtree or insert table column.
9846 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
9847 See the individual commands for more information."
9848 (interactive)
9849 (cond
9850 ((org-at-table-p) (org-table-insert-column))
9851 ((org-on-heading-p) (org-demote-subtree))
9852 (t (org-shiftcursor-error))))
9853
9854 (defun org-shiftmetaup (&optional arg)
9855 "Move subtree up or kill table row.
9856 Calls `org-move-subtree-up' or `org-table-kill-row', depending on context.
9857 See the individual commands for more information."
9858 (interactive "P")
9859 (cond
9860 ((org-at-table-p) (org-table-kill-row))
9861 ((org-on-heading-p) (org-move-subtree-up arg))
9862 (t (org-shiftcursor-error))))
9863 (defun org-shiftmetadown (&optional arg)
9864 "Move subtree down or insert table row.
9865 Calls `org-move-subtree-down' or `org-table-insert-row', depending on context.
9866 See the individual commands for more information."
9867 (interactive "P")
9868 (cond
9869 ((org-at-table-p) (org-table-insert-row arg))
9870 ((org-on-heading-p) (org-move-subtree-down arg))
9871 (t (org-shiftcursor-error))))
9872
9873 (defun org-metaleft (&optional arg)
9874 "Promote heading or move table column to left.
9875 Calls `org-do-promote' or `org-table-move-column', depending on context.
9876 See the individual commands for more information."
9877 (interactive "P")
9878 (cond
9879 ((org-at-table-p) (org-table-move-column 'left))
9880 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9881 (t (backward-word (prefix-numeric-value arg)))))
9882
9883 (defun org-metaright (&optional arg)
9884 "Demote subtree or move table column to right.
9885 Calls `org-do-demote' or `org-table-move-column', depending on context.
9886 See the individual commands for more information."
9887 (interactive "P")
9888 (cond
9889 ((org-at-table-p) (org-table-move-column nil))
9890 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9891 (t (forward-word (prefix-numeric-value arg)))))
9892
9893 (defun org-metaup (&optional arg)
9894 "Move subtree up or move table row up.
9895 Calls `org-move-subtree-up' or `org-table-move-row', depending on context.
9896 See the individual commands for more information."
9897 (interactive "P")
9898 (cond
9899 ((org-at-table-p) (org-table-move-row 'up))
9900 ((org-on-heading-p) (org-move-subtree-up arg))
9901 (t (org-shiftcursor-error))))
9902
9903 (defun org-metadown (&optional arg)
9904 "Move subtree down or move table row down.
9905 Calls `org-move-subtree-down' or `org-table-move-row', depending on context.
9906 See the individual commands for more information."
9907 (interactive "P")
9908 (cond
9909 ((org-at-table-p) (org-table-move-row nil))
9910 ((org-on-heading-p) (org-move-subtree-down arg))
9911 (t (org-shiftcursor-error))))
9912
9913 (defun org-shiftup (&optional arg)
9914 "Increase item in timestamp or increase priority of current item.
9915 Calls `org-timestamp-up' or `org-priority-up', depending on context.
9916 See the individual commands for more information."
9917 (interactive "P")
9918 (cond
9919 ((org-at-timestamp-p) (org-timestamp-up arg))
9920 (t (org-priority-up))))
9921
9922 (defun org-shiftdown (&optional arg)
9923 "Decrease item in timestamp or decrease priority of current item.
9924 Calls `org-timestamp-down' or `org-priority-down', depending on context.
9925 See the individual commands for more information."
9926 (interactive "P")
9927 (cond
9928 ((org-at-timestamp-p) (org-timestamp-down arg))
9929 (t (org-priority-down))))
9930
9931 (defun org-copy-special ()
9932 "Copy region in table or copy current subtree.
9933 Calls `org-table-copy' or `org-copy-subtree', depending on context.
9934 See the individual commands for more information."
9935 (interactive)
9936 (call-interactively
9937 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9938
9939 (defun org-cut-special ()
9940 "Cut region in table or cut current subtree.
9941 Calls `org-table-copy' or `org-cut-subtree', depending on context.
9942 See the individual commands for more information."
9943 (interactive)
9944 (call-interactively
9945 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9946
9947 (defun org-paste-special (arg)
9948 "Paste rectangular region into table, or past subtree relative to level.
9949 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
9950 See the individual commands for more information."
9951 (interactive "P")
9952 (if (org-at-table-p)
9953 (org-table-paste-rectangle)
9954 (org-paste-subtree arg)))
9955
9956 (defun org-ctrl-c-ctrl-c (&optional arg)
9957 "Call realign table, or recognize a table.el table, or update keywords.
9958 When the cursor is inside a table created by the table.el package,
9959 activate that table. Otherwise, if the cursor is at a normal table
9960 created with org.el, re-align that table. This command works even if
9961 the automatic table editor has been turned off.
9962 If the cursor is in one of the special #+KEYWORD lines, this triggers
9963 scanning the buffer for these lines and updating the information.
9964 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
9965 (interactive "P")
9966 (let ((org-enable-table-editor t))
9967 (cond
9968 ((org-at-table.el-p)
9969 (require 'table)
9970 (beginning-of-line 1)
9971 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9972 (table-recognize-table))
9973 ((org-at-table-p)
9974 (org-table-maybe-eval-formula)
9975 (if arg
9976 (org-table-recalculate t)
9977 (org-table-maybe-recalculate-line))
9978 (org-table-align))
9979 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9980 (cond
9981 ((equal (match-string 1) "TBLFM")
9982 ;; Recalculate the table before this line
9983 (save-excursion
9984 (beginning-of-line 1)
9985 (skip-chars-backward " \r\n\t")
9986 (if (org-at-table-p) (org-table-recalculate t))))
9987 (t
9988 (org-mode-restart))))
9989 ((org-region-active-p)
9990 (org-table-convert-region (region-beginning) (region-end) arg))
9991 ((and (region-beginning) (region-end))
9992 (if (y-or-n-p "Convert inactive region to table? ")
9993 (org-table-convert-region (region-beginning) (region-end) arg)
9994 (error "Abort")))
9995 (t (error "No table at point, and no region to make one")))))
9996
9997 (defun org-mode-restart ()
9998 "Restart Org-mode, to scan again for special lines.
9999 Also updates the keyword regular expressions."
10000 (interactive)
10001 (let ((org-inhibit-startup t)) (org-mode))
10002 (message "Org-mode restarted to refresh keyword and special line setup"))
10003
10004 (defun org-return ()
10005 "Goto next table row or insert a newline.
10006 Calls `org-table-next-row' or `newline', depending on context.
10007 See the individual commands for more information."
10008 (interactive)
10009 (cond
10010 ((org-at-table-p)
10011 (org-table-justify-field-maybe)
10012 (org-table-next-row))
10013 (t (newline))))
10014
10015 (defun org-meta-return (&optional arg)
10016 "Insert a new heading or wrap a region in a table.
10017 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
10018 See the individual commands for more information."
10019 (interactive "P")
10020 (cond
10021 ((org-at-table-p)
10022 (org-table-wrap-region arg))
10023 (t (org-insert-heading))))
10024
10025 ;;; Menu entries
10026
10027 ;; Define the Org-mode menus
10028 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
10029 '("Tbl"
10030 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
10031 ["Next Field" org-cycle (org-at-table-p)]
10032 ["Previous Field" org-shifttab (org-at-table-p)]
10033 ["Next Row" org-return (org-at-table-p)]
10034 "--"
10035 ["Blank Field" org-table-blank-field (org-at-table-p)]
10036 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
10037 "--"
10038 ("Column"
10039 ["Move Column Left" org-metaleft (org-at-table-p)]
10040 ["Move Column Right" org-metaright (org-at-table-p)]
10041 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
10042 ["Insert Column" org-shiftmetaright (org-at-table-p)])
10043 ("Row"
10044 ["Move Row Up" org-metaup (org-at-table-p)]
10045 ["Move Row Down" org-metadown (org-at-table-p)]
10046 ["Delete Row" org-shiftmetaup (org-at-table-p)]
10047 ["Insert Row" org-shiftmetadown (org-at-table-p)]
10048 "--"
10049 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
10050 ("Rectangle"
10051 ["Copy Rectangle" org-copy-special (org-at-table-p)]
10052 ["Cut Rectangle" org-cut-special (org-at-table-p)]
10053 ["Paste Rectangle" org-paste-special (org-at-table-p)]
10054 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
10055 "--"
10056 ("Calculate"
10057 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
10058 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10059 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
10060 "--"
10061 ["Recalculate line" org-table-recalculate (org-at-table-p)]
10062 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
10063 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
10064 "--"
10065 ["Sum Column/Rectangle" org-table-sum
10066 (or (org-at-table-p) (org-region-active-p))]
10067 ["Which Column?" org-table-current-column (org-at-table-p)])
10068 ["Debug Formulas"
10069 (setq org-table-formula-debug (not org-table-formula-debug))
10070 :style toggle :selected org-table-formula-debug]
10071 "--"
10072 ["Invisible Vlines" org-table-toggle-vline-visibility
10073 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
10074 "--"
10075 ["Create" org-table-create (and (not (org-at-table-p))
10076 org-enable-table-editor)]
10077 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
10078 ["Import from File" org-table-import (not (org-at-table-p))]
10079 ["Export to File" org-table-export (org-at-table-p)]
10080 "--"
10081 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
10082
10083 (easy-menu-define org-org-menu org-mode-map "Org menu"
10084 '("Org"
10085 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
10086 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
10087 ["Sparse Tree" org-occur t]
10088 ["Show All" show-all t]
10089 "--"
10090 ["New Heading" org-insert-heading t]
10091 ("Navigate Headings"
10092 ["Up" outline-up-heading t]
10093 ["Next" outline-next-visible-heading t]
10094 ["Previous" outline-previous-visible-heading t]
10095 ["Next Same Level" outline-forward-same-level t]
10096 ["Previous Same Level" outline-backward-same-level t]
10097 "--"
10098 ["Jump" org-goto t])
10099 ("Edit Structure"
10100 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
10101 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
10102 "--"
10103 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
10104 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
10105 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
10106 "--"
10107 ["Promote Heading" org-metaleft (not (org-at-table-p))]
10108 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
10109 ["Demote Heading" org-metaright (not (org-at-table-p))]
10110 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
10111 "--"
10112 ["Archive Subtree" org-archive-subtree t])
10113 "--"
10114 ("TODO Lists"
10115 ["TODO/DONE/-" org-todo t]
10116 ["Show TODO Tree" org-show-todo-tree t]
10117 "--"
10118 ["Set Priority" org-priority t]
10119 ["Priority Up" org-shiftup t]
10120 ["Priority Down" org-shiftdown t])
10121 ("Dates and Scheduling"
10122 ["Timestamp" org-time-stamp t]
10123 ["Timestamp (inactive)" org-time-stamp-inactive t]
10124 ("Change Date"
10125 ["1 Day Later" org-timestamp-up-day t]
10126 ["1 Day Earlier" org-timestamp-down-day t]
10127 ["1 ... Later" org-shiftup t]
10128 ["1 ... Earlier" org-shiftdown t])
10129 ["Compute Time Range" org-evaluate-time-range t]
10130 ["Schedule Item" org-schedule t]
10131 ["Deadline" org-deadline t]
10132 "--"
10133 ["Goto Calendar" org-goto-calendar t]
10134 ["Date from Calendar" org-date-from-calendar t])
10135 "--"
10136 ("Timeline/Agenda"
10137 ["Show TODO Tree this File" org-show-todo-tree t]
10138 ["Check Deadlines this File" org-check-deadlines t]
10139 ["Timeline Current File" org-timeline t]
10140 "--"
10141 ["Agenda" org-agenda t])
10142 ("File List for Agenda")
10143 "--"
10144 ("Hyperlinks"
10145 ["Store Link (Global)" org-store-link t]
10146 ["Insert Link" org-insert-link t]
10147 ["Follow Link" org-open-at-point t])
10148 "--"
10149 ("Export"
10150 ["ASCII" org-export-as-ascii t]
10151 ["Extract Visible Text" org-export-copy-visible t]
10152 ["HTML" org-export-as-html t]
10153 ["HTML and Open" org-export-as-html-and-open t]
10154 ; ["OPML" org-export-as-opml nil]
10155 "--"
10156 ["iCalendar this file" org-export-icalendar-this-file t]
10157 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
10158 :active t :keys "C-c C-x C-i"]
10159 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
10160 "--"
10161 ["Option Template" org-insert-export-options-template t]
10162 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
10163 "--"
10164 ("Documentation"
10165 ["Show Version" org-version t]
10166 ["Info Documentation" org-info t])
10167 ("Customize"
10168 ["Browse Org Group" org-customize t]
10169 "--"
10170 ["Build Full Customize Menu" org-create-customize-menu
10171 (fboundp 'customize-menu-create)])
10172 "--"
10173 ["Refresh setup" org-mode-restart t]
10174 ))
10175
10176 (defun org-info (&optional node)
10177 "Read documentation for Org-mode in the info system.
10178 With optional NODE, go directly to that node."
10179 (interactive)
10180 (require 'info)
10181 (Info-goto-node (format "(org)%s" (or node ""))))
10182
10183 (defun org-install-agenda-files-menu ()
10184 (easy-menu-change
10185 '("Org") "File List for Agenda"
10186 (append
10187 (list
10188 ["Edit File List" (customize-variable 'org-agenda-files) t]
10189 ["Add Current File to List" org-add-file t]
10190 ["Remove Current File from List" org-remove-file t]
10191 "--")
10192 (mapcar 'org-file-menu-entry org-agenda-files))))
10193
10194 ;;; Documentation
10195
10196 (defun org-customize ()
10197 "Call the customize function with org as argument."
10198 (interactive)
10199 (customize-browse 'org))
10200
10201 (defun org-create-customize-menu ()
10202 "Create a full customization menu for Org-mode, insert it into the menu."
10203 (interactive)
10204 (if (fboundp 'customize-menu-create)
10205 (progn
10206 (easy-menu-change
10207 '("Org") "Customize"
10208 `(["Browse Org group" org-customize t]
10209 "--"
10210 ,(customize-menu-create 'org)
10211 ["Set" Custom-set t]
10212 ["Save" Custom-save t]
10213 ["Reset to Current" Custom-reset-current t]
10214 ["Reset to Saved" Custom-reset-saved t]
10215 ["Reset to Standard Settings" Custom-reset-standard t]))
10216 (message "\"Org\"-menu now contains full customization menu"))
10217 (error "Cannot expand menu (outdated version of cus-edit.el)")))
10218
10219 ;;; Miscellaneous stuff
10220
10221 (defun org-move-line-down (arg)
10222 "Move the current line down. With prefix argument, move it past ARG lines."
10223 (interactive "p")
10224 (let ((col (current-column))
10225 beg end pos)
10226 (beginning-of-line 1) (setq beg (point))
10227 (beginning-of-line 2) (setq end (point))
10228 (beginning-of-line (+ 1 arg))
10229 (setq pos (move-marker (make-marker) (point)))
10230 (insert (delete-and-extract-region beg end))
10231 (goto-char pos)
10232 (move-to-column col)))
10233
10234 (defun org-move-line-up (arg)
10235 "Move the current line up. With prefix argument, move it past ARG lines."
10236 (interactive "p")
10237 (let ((col (current-column))
10238 beg end pos)
10239 (beginning-of-line 1) (setq beg (point))
10240 (beginning-of-line 2) (setq end (point))
10241 (beginning-of-line (- arg))
10242 (setq pos (move-marker (make-marker) (point)))
10243 (insert (delete-and-extract-region beg end))
10244 (goto-char pos)
10245 (move-to-column col)))
10246
10247 ;; Functions needed for Emacs/XEmacs region compatibility
10248
10249 (defun org-region-active-p ()
10250 "Is `transient-mark-mode' on and the region active?
10251 Works on both Emacs and XEmacs."
10252 (if org-ignore-region
10253 nil
10254 (if org-xemacs-p
10255 (and zmacs-regions (region-active-p))
10256 (and transient-mark-mode mark-active))))
10257
10258 (defun org-add-to-invisibility-spec (arg)
10259 "Add elements to `buffer-invisibility-spec'.
10260 See documentation for `buffer-invisibility-spec' for the kind of elements
10261 that can be added."
10262 (cond
10263 ((fboundp 'add-to-invisibility-spec)
10264 (add-to-invisibility-spec arg))
10265 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
10266 (setq buffer-invisibility-spec (list arg)))
10267 (t
10268 (setq buffer-invisibility-spec
10269 (cons arg buffer-invisibility-spec)))))
10270
10271 (defun org-remove-from-invisibility-spec (arg)
10272 "Remove elements from `buffer-invisibility-spec'."
10273 (if (fboundp 'remove-from-invisibility-spec)
10274 (remove-from-invisibility-spec arg)
10275 (if (consp buffer-invisibility-spec)
10276 (setq buffer-invisibility-spec
10277 (delete arg buffer-invisibility-spec)))))
10278
10279 (defun org-in-invisibility-spec-p (arg)
10280 "Is ARG a member of `buffer-invisibility-spec'?."
10281 (if (consp buffer-invisibility-spec)
10282 (member arg buffer-invisibility-spec)
10283 nil))
10284
10285 (defun org-image-file-name-regexp ()
10286 "Return regexp matching the file names of images."
10287 (if (fboundp 'image-file-name-regexp)
10288 (image-file-name-regexp)
10289 (let ((image-file-name-extensions
10290 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
10291 "xbm" "xpm" "pbm" "pgm" "ppm")))
10292 (concat "\\."
10293 (regexp-opt (nconc (mapcar 'upcase
10294 image-file-name-extensions)
10295 image-file-name-extensions)
10296 t)
10297 "\\'"))))
10298
10299 ;; Functions needed for compatibility with old outline.el
10300
10301 ;; The following functions capture almost the entire compatibility code
10302 ;; between the different versions of outline-mode. The only other place
10303 ;; where this is important are the font-lock-keywords. Search for
10304 ;; `org-noutline-p' to find it.
10305
10306 ;; C-a should go to the beginning of a *visible* line, also in the
10307 ;; new outline.el. I guess this should be patched into Emacs?
10308 (defun org-beginning-of-line ()
10309 "Go to the beginning of the current line. If that is invisible, continue
10310 to a visible line beginning. This makes the function of C-a more intuitive."
10311 (interactive)
10312 (beginning-of-line 1)
10313 (if (bobp)
10314 nil
10315 (backward-char 1)
10316 (if (org-invisible-p)
10317 (while (and (not (bobp)) (org-invisible-p))
10318 (backward-char 1)
10319 (beginning-of-line 1))
10320 (forward-char 1))))
10321 (when org-noutline-p
10322 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
10323
10324 (defun org-invisible-p ()
10325 "Check if point is at a character currently not visible."
10326 (if org-noutline-p
10327 ;; Early versions of noutline don't have `outline-invisible-p'.
10328 (if (fboundp 'outline-invisible-p)
10329 (outline-invisible-p)
10330 (get-char-property (point) 'invisible))
10331 (save-excursion
10332 (skip-chars-backward "^\r\n")
10333 (equal (char-before) ?\r))))
10334
10335 (defun org-back-to-heading (&optional invisible-ok)
10336 "Move to previous heading line, or beg of this line if it's a heading.
10337 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
10338 (if org-noutline-p
10339 (outline-back-to-heading invisible-ok)
10340 (if (looking-at outline-regexp)
10341 t
10342 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
10343 outline-regexp)
10344 nil t)
10345 (if invisible-ok
10346 (progn (goto-char (match-end 1))
10347 (looking-at outline-regexp)))
10348 (error "Before first heading")))))
10349
10350 (defun org-on-heading-p (&optional invisible-ok)
10351 "Return t if point is on a (visible) heading line.
10352 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
10353 (if org-noutline-p
10354 (outline-on-heading-p 'invisible-ok)
10355 (save-excursion
10356 (skip-chars-backward "^\n\r")
10357 (and (looking-at outline-regexp)
10358 (or invisible-ok
10359 (bobp)
10360 (equal (char-before) ?\n))))))
10361
10362 (defun org-up-heading-all (arg)
10363 "Move to the heading line of which the present line is a subheading.
10364 This function considers both visible and invisible heading lines.
10365 With argument, move up ARG levels."
10366 (if org-noutline-p
10367 (if (fboundp 'outline-up-heading-all)
10368 (outline-up-heading-all arg) ; emacs 21 version of outline.el
10369 (outline-up-heading arg t)) ; emacs 22 version of outline.el
10370 (org-back-to-heading t)
10371 (looking-at outline-regexp)
10372 (if (<= (- (match-end 0) (match-beginning 0)) arg)
10373 (error "Cannot move up %d levels" arg)
10374 (re-search-backward
10375 (concat "[\n\r]" (regexp-quote
10376 (make-string (- (match-end 0) (match-beginning 0) arg)
10377 ?*))
10378 "[^*]"))
10379 (forward-char 1))))
10380
10381 (defun org-show-hidden-entry ()
10382 "Show an entry where even the heading is hidden."
10383 (save-excursion
10384 (if (not org-noutline-p)
10385 (progn
10386 (org-back-to-heading t)
10387 (org-flag-heading nil)))
10388 (org-show-entry)))
10389
10390 (defun org-check-occur-regexp (regexp)
10391 "If REGEXP starts with \"^\", modify it to check for \\r as well.
10392 Of course, only for the old outline mode."
10393 (if org-noutline-p
10394 regexp
10395 (if (string-match "^\\^" regexp)
10396 (concat "[\n\r]" (substring regexp 1))
10397 regexp)))
10398
10399 (defun org-flag-heading (flag &optional entry)
10400 "Flag the current heading. FLAG non-nil means make invisible.
10401 When ENTRY is non-nil, show the entire entry."
10402 (save-excursion
10403 (org-back-to-heading t)
10404 (if (not org-noutline-p)
10405 ;; Make the current headline visible
10406 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
10407 ;; Check if we should show the entire entry
10408 (if entry
10409 (progn
10410 (org-show-entry)
10411 (save-excursion ;; FIXME: Is this the fix for points in the -|
10412 ;; middle of text? |
10413 (and (outline-next-heading) ;; |
10414 (org-flag-heading nil)))) ; show the next heading _|
10415 (outline-flag-region (max 1 (1- (point)))
10416 (save-excursion (outline-end-of-heading) (point))
10417 (if org-noutline-p
10418 flag
10419 (if flag ?\r ?\n))))))
10420
10421 (defun org-show-subtree ()
10422 "Show everything after this heading at deeper levels."
10423 (outline-flag-region
10424 (point)
10425 (save-excursion
10426 (outline-end-of-subtree) (outline-next-heading) (point))
10427 (if org-noutline-p nil ?\n)))
10428
10429 (defun org-show-entry ()
10430 "Show the body directly following this heading.
10431 Show the heading too, if it is currently invisible."
10432 (interactive)
10433 (save-excursion
10434 (org-back-to-heading t)
10435 (outline-flag-region
10436 (1- (point))
10437 (save-excursion
10438 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
10439 (or (match-beginning 1) (point-max)))
10440 (if org-noutline-p nil ?\n))))
10441
10442
10443 (defun org-make-options-regexp (kwds)
10444 "Make a regular expression for keyword lines."
10445 (concat
10446 (if org-noutline-p "^" "[\n\r]")
10447 "#?[ \t]*\\+\\("
10448 (mapconcat 'regexp-quote kwds "\\|")
10449 "\\):[ \t]*"
10450 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10451
10452 ;; Make `bookmark-jump' show the jump location if it was hidden.
10453 (eval-after-load "bookmark"
10454 '(if (boundp 'bookmark-after-jump-hook)
10455 ;; We can use the hook
10456 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
10457 ;; Hook not available, use advice
10458 (defadvice bookmark-jump (after org-make-visible activate)
10459 "Make the position visible."
10460 (org-bookmark-jump-unhide))))
10461
10462 (defun org-bookmark-jump-unhide ()
10463 "Unhide the current position, to show the bookmark location."
10464 (and (eq major-mode 'org-mode)
10465 (or (org-invisible-p)
10466 (save-excursion (goto-char (max (point-min) (1- (point))))
10467 (org-invisible-p)))
10468 (org-show-hierarchy-above)))
10469
10470 ;;; Finish up
10471
10472 (provide 'org)
10473
10474 (run-hooks 'org-load-hook)
10475
10476 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10477 ;;; org.el ends here