]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
* textmodes/org.el (org-combined-agenda-icalendar-file)
[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.18
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.18
84 ;; - Export of calendar information in the standard iCalendar format.
85 ;; - Some bug fixes.
86 ;;
87 ;; Version 3.17
88 ;; - HTML export specifies character set depending on coding-system.
89 ;;
90 ;; Version 3.16
91 ;; - In tables, directly after the field motion commands like TAB and RET,
92 ;; typing a character will blank the field. Can be turned off with
93 ;; variable `org-table-auto-blank-field'.
94 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
95 ;; and are not linked to the calendar.
96 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
97 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
98 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
99 ;; standard meaning of C-h after a prefix key (show prefix bindings).
100 ;;
101 ;; Version 3.15
102 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
103 ;; of unmodified entry text. `C-c :' toggles this keyword.
104 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
105 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
106 ;; color, to reduce the amount of aggressive color in the buffer.
107 ;;
108 ;; Version 3.14
109 ;; - Formulas for individual fields in table.
110 ;; - Automatic recalculation in calculating tables.
111 ;; - Named fields and columns in tables.
112 ;; - Fixed bug with calling `org-archive' several times in a row.
113 ;;
114 ;; Version 3.13
115 ;; - Efficiency improvements: Fewer table re-alignments needed.
116 ;; - New special lines in tables, for defining names for individual cells.
117 ;;
118 ;; Version 3.12
119 ;; - Tables can store formulas (one per column) and compute fields.
120 ;; Not quite like a full spreadsheet, but very powerful.
121 ;; - table.el keybinding is now `C-c ~'.
122 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
123 ;; - Small changes to keys in agenda buffer. Affected keys:
124 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
125 ;; - Bug fixes.
126 ;;
127 ;; Version 3.11
128 ;; - Links inserted with C-c C-l are now by default enclosed in angle
129 ;; brackets. See the new variable `org-link-format'.
130 ;; - ">" terminates a link, this is a way to have several links in a line.
131 ;; Both "<" and ">" are no longer allowed as characters in a link.
132 ;; - Archiving of finished tasks.
133 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
134 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
135 ;; - Compatibility problems with viper-mode fixed.
136 ;; - Improved html export of tables.
137 ;; - Various clean-up changes.
138 ;;
139 ;; Version 3.10
140 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
141 ;;
142 ;; Version 3.09
143 ;; - Time-of-day specifications in agenda are extracted and placed
144 ;; into the prefix. Timed entries can be placed into a time grid for
145 ;; day.
146 ;;
147 ;; Version 3.08
148 ;; - "|" no longer allowed as part of a link, to allow links in tables.
149 ;; - The prefix of items in the agenda buffer can be configured.
150 ;; - Cleanup.
151 ;;
152 ;; Version 3.07
153 ;; - Some folding incinsistencies removed.
154 ;; - BBDB links to company-only entries.
155 ;; - Bug fixes and global cleanup.
156 ;;
157 ;; Version 3.06
158 ;; - M-S-RET inserts a new TODO heading.
159 ;; - New startup option `content'.
160 ;; - Better visual response when TODO items in agenda change status.
161 ;; - Window positioning after visibility state changes optimized and made
162 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
163 ;;
164 ;; Version 3.05
165 ;; - Agenda entries from the diary are linked to the diary file, so
166 ;; adding and editing diary entries can be done directly from the agenda.
167 ;; - Many calendar/diary commands available directly from agenda.
168 ;; - Field copying in tables with S-RET does increment.
169 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
170 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
171 ;;
172 ;; Version 3.04
173 ;; - Table editor optimized to need fewer realignments, and to keep
174 ;; table shape when typing in fields.
175 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
176 ;; into arbitrary major modes.
177 ;; - Fixed bug with realignment in XEmacs.
178 ;; - Startup options can be set with special #+STARTUP line.
179 ;; - Heading following a match in org-occur can be suppressed.
180 ;;
181 ;; Version 3.03
182 ;; - Copyright transfer to the FSF.
183 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
184 ;; - Timeline now always contains today, and `.' jumps to it.
185 ;; - Table editor:
186 ;; - cut and paste of rectangular regions in tables
187 ;; - command to convert org-mode table to table.el table and back
188 ;; - command to treat several cells like a paragraph and fill it
189 ;; - command to convert a buffer region to a table
190 ;; - import/export tables as tab-separated files (exchange with Excel)
191 ;; - Agenda:
192 ;; - Sorting mechanism for agenda items rewritten from scratch.
193 ;; - Sorting fully configurable.
194 ;; - Entries specifying a time are sorted together.
195 ;; - Completion also covers option keywords after `#-'.
196 ;; - Bug fixes.
197 ;;
198 ;; Version 3.01
199 ;; - New reference card, thanks to Philip Rooke for creating it.
200 ;; - Single file agenda renamed to "Timeline". It no longer shows
201 ;; warnings about upcoming deadlines/overdue scheduled items.
202 ;; That functionality is now limited to the (multifile) agenda.
203 ;; - When reading a date, the calendar can be manipulated with keys.
204 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
205 ;; - Minor bug fixes and documentation improvements.
206
207 ;;; Code:
208
209 (eval-when-compile (require 'cl) (require 'calendar))
210 (require 'outline)
211 (require 'time-date)
212 (require 'easymenu)
213
214 (defvar calc-embedded-close-formula)
215 (defvar calc-embedded-open-formula)
216 (defvar font-lock-unfontify-region-function)
217
218 ;;; Customization variables
219
220 (defvar org-version "3.18"
221 "The version number of the file org.el.")
222 (defun org-version ()
223 (interactive)
224 (message "Org-mode version %s" org-version))
225
226 ;; The following two constants are for compatibility with different Emacs
227 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
228 ;; The compatibility code in org.el is based on these two constants.
229 (defconst org-xemacs-p (featurep 'xemacs)
230 "Are we running xemacs?")
231 (defconst org-noutline-p (featurep 'noutline)
232 "Are we using the new outline mode?")
233
234 (defgroup org nil
235 "Outline-based notes management and organizer "
236 :tag "Org"
237 :group 'outlines
238 :group 'hypermedia
239 :group 'calendar)
240
241 (defgroup org-startup nil
242 "Options concerning startup of Org-mode."
243 :tag "Org Startup"
244 :group 'org)
245
246 (defcustom org-CUA-compatible nil
247 "Non-nil means use alternative key bindings for S-<cursor movement>.
248 Org-mode used S-<cursor movement> for changing timestamps and priorities.
249 S-<cursor movement> is also used for example by `CUA-mode' to select text.
250 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
251 alternative bindings. Setting this variable to t will replace the following
252 keys both in Org-mode and in the Org-agenda buffer.
253
254 S-RET -> C-S-RET
255 S-up -> M-p
256 S-down -> M-n
257 S-left -> M--
258 S-right -> M-+
259
260 If you do not like the alternative keys, take a look at the variable
261 `org-disputed-keys'.
262
263 This option is only relevant at load-time of Org-mode. Changing it requires
264 a restart of Emacs to become effective."
265 :group 'org-startup
266 :type 'boolean)
267
268 (defvar org-disputed-keys
269 '((S-up [(shift up)] [(meta ?p)])
270 (S-down [(shift down)] [(meta ?n)])
271 (S-left [(shift left)] [(meta ?-)])
272 (S-right [(shift right)] [(meta ?+)])
273 (S-return [(shift return)] [(control shift return)]))
274 "Keys for which Org-mode and other modes compete.
275 This is an alist, cars are symbols for lookup, 1st element is the default key,
276 second element will be used when `org-CUA-compatible' is t.")
277
278 (defun org-key (key)
279 "Select a key according to `org-CUA-compatible'."
280 (nth (if org-CUA-compatible 2 1)
281 (or (assq key org-disputed-keys)
282 (error "Invalid Key %s in `org-key'" key))))
283
284 (defcustom org-startup-folded t
285 "Non-nil means, entering Org-mode will switch to OVERVIEW.
286 This can also be configured on a per-file basis by adding one of
287 the following lines anywhere in the buffer:
288
289 #+STARTUP: fold
290 #+STARTUP: nofold
291 #+STARTUP: content"
292 :group 'org-startup
293 :type '(choice
294 (const :tag "nofold: show all" nil)
295 (const :tag "fold: overview" t)
296 (const :tag "content: all headlines" content)))
297
298 (defcustom org-startup-truncated t
299 "Non-nil means, entering Org-mode will set `truncate-lines'.
300 This is useful since some lines containing links can be very long and
301 uninteresting. Also tables look terrible when wrapped."
302 :group 'org-startup
303 :type 'boolean)
304
305 (defcustom org-startup-with-deadline-check nil
306 "Non-nil means, entering Org-mode will run the deadline check.
307 This means, if you start editing an org file, you will get an
308 immediate reminder of any due deadlines.
309 This can also be configured on a per-file basis by adding one of
310 the following lines anywhere in the buffer:
311
312 #+STARTUP: dlcheck
313 #+STARTUP: nodlcheck"
314 :group 'org-startup
315 :type 'boolean)
316
317 (defcustom org-insert-mode-line-in-empty-file nil
318 "Non-nil means insert the first line setting Org-mode in empty files.
319 When the function `org-mode' is called interactively in an empty file, this
320 normally means that the file name does not automatically trigger Org-mode.
321 To ensure that the file will always be in Org-mode in the future, a
322 line enforcing Org-mode will be inserted into the buffer, if this option
323 has been set."
324 :group 'org-startup
325 :type 'boolean)
326
327 (defgroup org-keywords nil
328 "Options concerning TODO items in Org-mode."
329 :tag "Org Keywords"
330 :group 'org)
331
332 (defcustom org-todo-keywords '("TODO" "DONE")
333 "List of TODO entry keywords.
334 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
335 considered to mean that the entry is \"done\". All the other mean that
336 action is required, and will make the entry show up in todo lists, diaries
337 etc.
338 The command \\[org-todo] cycles an entry through these states, and an
339 additional state where no keyword is present. For details about this
340 cycling, see also the variable `org-todo-interpretation'
341 Changes become only effective after restarting Emacs."
342 :group 'org-keywords
343 :type '(repeat (string :tag "Keyword")))
344
345 (defcustom org-todo-interpretation 'sequence
346 "Controls how TODO keywords are interpreted.
347 \\<org-mode-map>Possible values are `sequence' and `type'.
348 This variable is only relevant if `org-todo-keywords' contains more than two
349 states. There are two ways how these keywords can be used:
350
351 - As a sequence in the process of working on a TODO item, for example
352 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
353 org-todo-interpretation 'sequence)
354
355 - As different types of TODO items, for example
356 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
357 org-todo-interpretation 'type)
358
359 When the states are interpreted as a sequence, \\[org-todo] always cycles
360 to the next state, in order to walk through all different states. So with
361 \\[org-todo], you turn an empty entry into the state TODO. When you started
362 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
363 later to VERIFY and finally to DONE.
364
365 When the states are interpreted as types, \\[org-todo] still cycles through
366 when it is called several times in direct succession, in order to initially
367 select the type. However, if not called immediately after a previous
368 \\[org-todo], it switches from each type directly to DONE. So with the
369 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
370 RELAXED. If you later return to this entry and press \\[org-todo] again,
371 RELAXED will not be changed REMIND, but directly to DONE.
372
373 You can create a large number of types. To initially select a
374 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
375 type with completion. Of course, you can also type the keyword
376 directly into the buffer. M-TAB completes TODO keywords at the
377 beginning of a headline."
378 :group 'org-keywords
379 :type '(choice (const sequence)
380 (const type)))
381
382 (defcustom org-default-priority ?B
383 "The default priority of TODO items.
384 This is the priority an item get if no explicit priority is given."
385 :group 'org-keywords
386 :type 'character)
387
388 (defcustom org-lowest-priority ?C
389 "The lowest priority of TODO items. A character like ?A, ?B etc."
390 :group 'org-keywords
391 :type 'character)
392
393 (defcustom org-deadline-string "DEADLINE:"
394 "String to mark deadline entries.
395 A deadline is this string, followed by a time stamp. Should be a word,
396 terminated by a colon. You can insert a schedule keyword and
397 a timestamp with \\[org-deadline].
398 Changes become only effective after restarting Emacs."
399 :group 'org-keywords
400 :type 'string)
401
402 (defcustom org-scheduled-string "SCHEDULED:"
403 "String to mark scheduled TODO entries.
404 A schedule is this string, followed by a time stamp. Should be a word,
405 terminated by a colon. You can insert a schedule keyword and
406 a timestamp with \\[org-schedule].
407 Changes become only effective after restarting Emacs."
408 :group 'org-keywords
409 :type 'string)
410
411 (defcustom org-comment-string "COMMENT"
412 "Entries starting with this keyword will never be exported.
413 An entry can be toggled between COMMENT and normal with
414 \\[org-toggle-comment].
415 Changes become only effective after restarting Emacs."
416 :group 'org-keywords
417 :type 'string)
418
419 (defcustom org-quote-string "QUOTE"
420 "Entries starting with this keyword will be exported in fixed-width font.
421 Quoting applies only to the text in the entry following the headline, and does
422 not extend beyond the next headline, even if that is lower level.
423 An entry can be toggled between QUOTE and normal with
424 \\[org-toggle-fixed-width-section]"
425 :group 'org-keywords
426 :type 'string)
427
428 (defcustom org-after-todo-state-change-hook nil
429 "Hook which is run after the state of a TODO item was changed.
430 The new state (a string with a todo keyword, or nil) is available in the
431 Lisp variable `state'."
432 :group 'org-keywords
433 :type 'hook)
434
435 ;; Variables for pre-computed regular expressions, all buffer local
436 (defvar org-todo-kwd-priority-p nil
437 "Do TODO items have priorities?")
438 (make-variable-buffer-local 'org-todo-kwd-priority-p)
439 (defvar org-todo-kwd-max-priority nil
440 "Maximum priority of TODO items.")
441 (make-variable-buffer-local 'org-todo-kwd-max-priority)
442 (defvar org-ds-keyword-length 12
443 "Maximum length of the Deadline and SCHEDULED keywords.")
444 (make-variable-buffer-local 'org-ds-keyword-length)
445 (defvar org-done-string nil
446 "The last string in `org-todo-keywords', indicating an item is DONE.")
447 (make-variable-buffer-local 'org-done-string)
448 (defvar org-todo-regexp nil
449 "Matches any of the TODO state keywords.")
450 (make-variable-buffer-local 'org-todo-regexp)
451 (defvar org-not-done-regexp nil
452 "Matches any of the TODO state keywords except the last one.")
453 (make-variable-buffer-local 'org-not-done-regexp)
454 (defvar org-todo-line-regexp nil
455 "Matches a headline and puts TODO state into group 2 if present.")
456 (make-variable-buffer-local 'org-todo-line-regexp)
457 (defvar org-nl-done-regexp nil
458 "Matches newline followed by a headline with the DONE keyword.")
459 (make-variable-buffer-local 'org-nl-done-regexp)
460 (defvar org-looking-at-done-regexp nil
461 "Matches the DONE keyword a point.")
462 (make-variable-buffer-local 'org-looking-at-done-regexp)
463 (defvar org-deadline-regexp nil
464 "Matches the DEADLINE keyword.")
465 (make-variable-buffer-local 'org-deadline-regexp)
466 (defvar org-deadline-time-regexp nil
467 "Matches the DEADLINE keyword together with a time stamp.")
468 (make-variable-buffer-local 'org-deadline-time-regexp)
469 (defvar org-deadline-line-regexp nil
470 "Matches the DEADLINE keyword and the rest of the line.")
471 (make-variable-buffer-local 'org-deadline-line-regexp)
472 (defvar org-scheduled-regexp nil
473 "Matches the SCHEDULED keyword.")
474 (make-variable-buffer-local 'org-scheduled-regexp)
475 (defvar org-scheduled-time-regexp nil
476 "Matches the SCHEDULED keyword together with a time stamp.")
477 (make-variable-buffer-local 'org-scheduled-time-regexp)
478
479 (defvar org-category nil
480 "Variable used by org files to set a category for agenda display.
481 Such files should use a file variable to set it, for example
482
483 -*- mode: org; org-category: \"ELisp\"
484
485 or contain a special line
486
487 #+CATEGORY: ELisp
488
489 If the file does not specify a category, then file's base name
490 is used instead.")
491
492 (defgroup org-time nil
493 "Options concerning time stamps and deadlines in Org-mode."
494 :tag "Org Time"
495 :group 'org)
496
497 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
498 "Formats for `format-time-string' which are used for time stamps.
499 It is not recommended to change this constant.")
500
501
502 (defcustom org-deadline-warning-days 30
503 "No. of days before expiration during which a deadline becomes active.
504 This variable governs the display in the org file."
505 :group 'org-time
506 :type 'number)
507
508 (defcustom org-popup-calendar-for-date-prompt t
509 "Non-nil means, pop up a calendar when prompting for a date.
510 In the calendar, the date can be selected with mouse-1. However, the
511 minibuffer will also be active, and you can simply enter the date as well.
512 When nil, only the minibuffer will be available."
513 :group 'org-time
514 :type 'number)
515
516 (defcustom org-calendar-follow-timestamp-change t
517 "Non-nil means, make the calendar window follow timestamp changes.
518 When a timestamp is modified and the calendar window is visible, it will be
519 moved to the new date."
520 :group 'org-time
521 :type 'boolean)
522
523 (defgroup org-agenda nil
524 "Options concerning agenda display Org-mode."
525 :tag "Org Agenda"
526 :group 'org)
527
528 (defcustom org-agenda-files nil
529 "A list of org files for agenda/diary display.
530 Entries are added to this list with \\[org-add-file] and removed with
531 \\[org-remove-file]. You can also use customize to edit the list."
532 :group 'org-agenda
533 :type '(repeat file))
534
535 (defcustom org-select-timeline-window t
536 "Non-nil means, after creating a timeline, move cursor into Timeline window.
537 When nil, cursor will remain in the current window."
538 :group 'org-agenda
539 :type 'boolean)
540
541 (defcustom org-select-agenda-window t
542 "Non-nil means, after creating an agenda, move cursor into Agenda window.
543 When nil, cursor will remain in the current window."
544 :group 'org-agenda
545 :type 'boolean)
546
547 (defcustom org-fit-agenda-window t
548 "Non-nil means, change window size of agenda to fit content."
549 :group 'org-agenda
550 :type 'boolean)
551
552 (defcustom org-agenda-show-all-dates t
553 "Non-nil means, `org-agenda' shows every day in the selected range.
554 When nil, only the days which actually have entries are shown."
555 :group 'org-agenda
556 :type 'boolean)
557
558 ;; FIXME: First day of month works only for current month because it would
559 ;; require a variable ndays treatment.
560 (defcustom org-agenda-start-on-weekday 1
561 "Non-nil means, start the overview always on the specified weekday.
562 0 Denotes Sunday, 1 denotes Monday etc.
563 When nil, always start on the current day."
564 :group 'org-agenda
565 :type '(choice (const :tag "Today" nil)
566 (const :tag "First day of month" t)
567 (number :tag "Weekday No.")))
568
569 (defcustom org-agenda-ndays 7
570 "Number of days to include in overview display."
571 :group 'org-agenda
572 :type 'number)
573
574 (defcustom org-agenda-include-all-todo t
575 "Non-nil means, the agenda will always contain all TODO entries.
576 When nil, date-less entries will only be shown if `org-agenda' is called
577 with a prefix argument.
578 When non-nil, the TODO entries will be listed at the top of the agenda, before
579 the entries for specific days."
580 :group 'org-agenda
581 :type 'boolean)
582
583 (defcustom org-agenda-include-diary nil
584 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
585 :group 'org-agenda
586 :type 'boolean)
587
588 (defcustom org-calendar-to-agenda-key [?c]
589 "The key to be installed in `calendar-mode-map' for switching to the agenda.
590 The command `org-calendar-goto-agenda' will be bound to this key. The
591 default is the character `c' because then`c' can be used to switch back and
592 force between agenda and calendar."
593 :group 'org-agenda
594 :type 'sexp)
595
596 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
597 "Sorting structure for the agenda items of a single day.
598 This is a list of symbols which will be used in sequence to determine
599 if an entry should be listed before another entry. The following
600 symbols are recognized.
601
602 time-up Put entries with time-of-day indications first, early first
603 time-down Put entries with time-of-day indications first, late first
604 category-keep Keep the default order of categories, corresponding to the
605 sequence in `org-agenda-files'.
606 category-up Sort alphabetically by category, A-Z.
607 category-down Sort alphabetically by category, Z-A.
608 priority-up Sort numerically by priority, high priority last.
609 priority-down Sort numerically by priority, high priority first.
610
611 The different possibilities will be tried in sequence, and testing stops
612 if one comparison returns a \"not-equal\". For example, the default
613 '(time-up category-keep priority-down)
614 means: Pull out all entries having a specified time of day and sort them,
615 in order to make a time schedule for the current day the first thing in the
616 agenda listing for the day. Of the entries without a time indication, keep
617 the grouped in categories, don't sort the categories, but keep them in
618 the sequence given in `org-agenda-files'. Within each category sort by
619 priority.
620
621 Leaving out `category-keep' would mean that items will be sorted across
622 categories by priority."
623 :group 'org-agenda
624 :type '(repeat
625 (choice
626 (const time-up)
627 (const time-down)
628 (const category-keep)
629 (const category-up)
630 (const category-down)
631 (const priority-up)
632 (const priority-down))))
633
634 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
635 "Format specification for the prefix of items in the agenda buffer.
636 This format works similar to a printf format, with the following meaning:
637
638 %c the category of the item, \"Diary\" for entries from the diary, or
639 as given by the CATEGORY keyword or derived from the file name.
640 %t the time-of-day specification if one applies to the entry, in the
641 format HH:MM
642 %s Scheduling/Deadline information, a short string
643
644 All specifiers work basically like the standard `%s' of printf, but may
645 contain two additional characters: A question mark just after the `%' and
646 a whitespace/punctuation character just before the final letter.
647
648 If the first character after `%' is a question mark, the entire field
649 will only be included if the corresponding value applies to the
650 current entry. This is useful for fields which should have fixed
651 width when present, but zero width when absent. For example,
652 \"%?-12t\" will result in a 12 character time field if a time of the
653 day is specified, but will completely disappear in entries which do
654 not contain a time.
655
656 If there is punctuation or whitespace character just before the final
657 format letter, this character will be appended to the field value if
658 the value is not empty. For example, the format \"%-12:c\" leads to
659 \"Diary: \" if the category is \"Diary\". If the category were be
660 empty, no additional colon would be interted.
661
662 The default value of this option is \" %-12:c%?-12t% s\", meaning:
663 - Indent the line with two space characters
664 - Give the category in a 12 chars wide field, padded with whitespace on
665 the right (because of `-'). Append a colon if there is a category
666 (because of `:').
667 - If there is a time-of-day, put it into a 12 chars wide field. If no
668 time, don't put in an empty field, just skip it (because of '?').
669 - Finally, put the scheduling information and append a whitespace.
670
671 As another example, if you don't want the time-of-day of entries in
672 the prefix, you could use:
673
674 (setq org-agenda-prefix-format \" %-11:c% s\")
675
676 See also the variable `org-agenda-remove-times-when-in-prefix'."
677 :type 'string
678 :group 'org-agenda)
679
680 (defcustom org-timeline-prefix-format " % s"
681 "Like `org-agenda-prefix-format', but for the timeline of a single file."
682 :type 'string
683 :group 'org-agenda)
684
685 (defvar org-prefix-format-compiled nil
686 "The compiled version of the most recently used prefix format.
687 Depending on which command was used last, this may be the compiled version
688 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
689
690 (defcustom org-agenda-use-time-grid t
691 "Non-nil means, show a time grid in the agenda schedule.
692 A time grid is a set of lines for specific times (like every two hours between
693 8:00 and 20:00. The items scheduled for a day at specific times are
694 sorted in between these lines.
695 For deails about when the grid will be shown, and what it will look like, see
696 the variable `org-agenda-time-grid'."
697 :group 'org-agenda
698 :type 'boolean)
699
700 (defcustom org-agenda-time-grid
701 '((daily today require-timed)
702 "----------------"
703 (800 1000 1200 1400 1600 1800 2000))
704
705 "The settings for time grid for agenda display.
706 This is a list of three items. The first item is again a list. It contains
707 symbols specifying conditions when the grid should be displayed:
708
709 daily if the agenda shows a single day
710 weekly if the agenda shows an entire week
711 today show grid on current date, independent of daily/weekly display
712 require-timed show grid only if at least on item has a time specification
713
714 The second item is a string which will be places behing the grid time.
715
716 The third item is a list of integers, indicating the times that should have
717 a grid line."
718 :group 'org-agenda
719 :type
720 '(list
721 (set :greedy t :tag "Grid Display Options"
722 (const :tag "Show grid in single day agenda display" daily)
723 (const :tag "Show grid in weekly agenda display" weekly)
724 (const :tag "Always show grid for today" today)
725 (const :tag "Show grid only if any timed entries are present"
726 require-timed)
727 (const :tag "Skip grid times already present in an entry"
728 remove-match))
729 (string :tag "Grid String")
730 (repeat :tag "Grid Times" (integer :tag "Time"))))
731
732 (defcustom org-agenda-remove-times-when-in-prefix t
733 "Non-nil means, remove duplicate time specifications in agenda items.
734 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
735 time-of-day specification in a headline or diary entry is extracted and
736 placed into the prefix. If this option is non-nil, the original specification
737 \(a timestamp or -range, or just a plain time(range) specification like
738 11:30-4pm) will be removed for agenda display. This makes the agenda less
739 cluttered.
740 The option can be t or nil. It may also be the symbol `beg', indicating
741 that the time should only be removed what it is located at the beginning of
742 the headline/diary entry."
743 :group 'org-agenda
744 :type '(choice
745 (const :tag "Always" t)
746 (const :tag "Never" nil)
747 (const :tag "When at beginning of entry" beg)))
748
749 (defcustom org-sort-agenda-notime-is-late t
750 "Non-nil means, items without time are considered late.
751 This is only relevant for sorting. When t, items which have no explicit
752 time like 15:30 will be considered as 24:01, i.e. later than any items which
753 do have a time. When nil, the default time is before 0:00. You can use this
754 option to decide if the schedule for today should come before or after timeless
755 agenda entries."
756 :group 'org-agenda
757 :type 'boolean)
758
759 (defgroup org-structure nil
760 "Options concerning structure editing in Org-mode."
761 :tag "Org Structure"
762 :group 'org)
763
764 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
765 "Hook that is run after `org-cycle' has changed the buffer visibility.
766 The function(s) in this hook must accept a single argument which indicates
767 the new state that was set by the most recent `org-cycle' command. The
768 argument is a symbol. After a global state change, it can have the values
769 `overview', `content', or `all'. After a local state change, it can have
770 the values `folded', `children', or `subtree'."
771 :group 'org-structure
772 :type 'hook)
773
774 (defcustom org-occur-hook '(org-first-headline-recenter)
775 "Hook that is run after `org-occur' has constructed a sparse tree.
776 This can be used to recenter the window to show as much of the structure
777 as possible."
778 :group 'org-structure
779 :type 'hook)
780
781 (defcustom org-level-color-stars-only nil
782 "Non-nil means fontify only the stars in each headline.
783 When nil, the entire headline is fontified.
784 After changing this, requires restart of Emacs to become effective."
785 :group 'org-structure
786 :type 'boolean)
787
788 (defcustom org-adapt-indentation t
789 "Non-nil means, adapt indentation when promoting and demoting.
790 When this is set and the *entire* text in an entry is indented, the
791 indentation is increased by one space in a demotion command, and
792 decreased by one in a promotion command. If any line in the entry
793 body starts at column 0, indentation is not changed at all."
794 :group 'org-structure
795 :type 'boolean)
796
797 (defcustom org-enable-fixed-width-editor t
798 "Non-nil means, lines starting with \":\" are treated as fixed-width.
799 This currently only means, they are never auto-wrapped.
800 When nil, such lines will be treated like ordinary lines.
801 See also the QUOTE keyword."
802 :group 'org-structure
803 :type 'boolean)
804
805 (defcustom org-cycle-emulate-tab t
806 "Where should `org-cycle' emulate TAB.
807 nil Never
808 white Only in completely white lines
809 t Everywhere except in headlines"
810 :group 'org-structure
811 :type '(choice (const :tag "Never" nil)
812 (const :tag "Only in completely white lines" white)
813 (const :tag "Everywhere except in headlines" t)
814 ))
815
816 (defcustom org-show-following-heading t
817 "Non-nil means, show heading following match in `org-occur'.
818 When doing an `org-occur' it is useful to show the headline which
819 follows the match, even if they do not match the regexp. This makes it
820 easier to edit directly inside the sparse tree. However, if you use
821 org-occur mainly as an overview, the following headlines are
822 unnecessary clutter."
823 :group 'org-structure
824 :type 'boolean)
825
826 (defcustom org-archive-location "%s_archive::"
827 "The location where subtrees should be archived.
828 This string consists of two parts, separated by a double-colon.
829
830 The first part is a file name - when omitted, archiving happens in the same
831 file. %s will be replaced by the current file name (without directory part).
832 Archiving to a different file is useful to keep archived entries from
833 contributing to the Org-mode Agenda.
834
835 The part after the double colon is a headline. The archived entries will be
836 filed under that headline. When omitted, the subtrees are simply filed away
837 at the end of the file, as top-level entries.
838
839 Here are a few examples:
840 \"%s_archive::\"
841 If the current file is Projects.org, archive in file
842 Projects.org_archive, as top-level trees. This is the default.
843
844 \"::* Archived Tasks\"
845 Archive in the current file, under the top-level headline
846 \"* Archived Tasks\".
847
848 \"~/org/archive.org::\"
849 Archive in file ~/org/archive.org (absolute path), as top-level trees.
850
851 \"basement::** Finished Tasks\"
852 Archive in file ./basement (relative path), as level 3 trees
853 below the level 2 heading \"** Finished Tasks\".
854
855 You may set this option on a per-file basis by adding to the buffer a
856 line like
857
858 #+ARCHIVE: basement::** Finished Tasks"
859 :group 'org-structure
860 :type 'string)
861
862 (defcustom org-archive-mark-done t
863 "Non-nil means, mark archived entries as DONE."
864 :group 'org-structure
865 :type 'boolean)
866
867 (defcustom org-archive-stamp-time t
868 "Non-nil means, add a time stamp to archived entries.
869 The time stamp will be added directly after the TODO state keyword in the
870 first line, so it is probably best to use this in combinations with
871 `org-archive-mark-done'."
872 :group 'org-structure
873 :type 'boolean)
874
875 (defgroup org-link nil
876 "Options concerning links in Org-mode."
877 :tag "Org Link"
878 :group 'org)
879
880 (defcustom org-link-format "<%s>"
881 "Default format for linkes in the buffer.
882 This is a format string for printf, %s will be replaced by the link text.
883 If you want to make sure that your link is always properly terminated,
884 include angle brackets into this format, like \"<%s>\". Some people also
885 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
886 :group 'org-link
887 :type '(choice
888 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
889 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
890 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
891 (string :tag "Other" :value "<%s>")))
892
893 (defcustom org-allow-space-in-links t
894 "Non-nil means, file names in links may contain space characters.
895 When nil, it becomes possible to put several links into a line.
896 Note that in tables, a link never extends accross fields, so in a table
897 it is always possible to put several links into a line.
898 Changing this varable requires a re-launch of Emacs of become effective."
899 :group 'org-link
900 :type 'boolean)
901
902 (defcustom org-line-numbers-in-file-links t
903 "Non-nil means, file links from `org-store-link' contain line numbers.
904 The line number will be added to the file name with :NNN and interpreted
905 by the command `org-open-at-point'.
906 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
907 negates this setting for the duration of the command."
908 :group 'org-link
909 :type 'boolean)
910
911 (defcustom org-keep-stored-link-after-insertion nil
912 "Non-nil means, keep link in list for entire session.
913
914 The command `org-store-link' adds a link pointing to the current
915 location to an internal list. These links accumulate during a session.
916 The command `org-insert-link' can be used to insert links into any
917 Org-mode file (offering completion for all stored links). When this
918 option is nil, every link which has been inserted once using \\[org-insert-link]
919 will be removed from the list, to make completing the unused links
920 more efficient."
921 :group 'org-link
922 :type 'boolean)
923
924 (defcustom org-link-frame-setup
925 '((vm . vm-visit-folder-other-frame)
926 (gnus . gnus-other-frame)
927 (file . find-file-other-window))
928 "Setup the frame configuration for following links.
929 When following a link with Emacs, it may often be useful to display
930 this link in another window or frame. This variable can be used to
931 set this up for the different types of links.
932 For VM, use any of
933 `vm-visit-folder'
934 `vm-visit-folder-other-frame'
935 For Gnus, use any of
936 `gnus'
937 `gnus-other-frame'
938 For FILE, use any of
939 `find-file'
940 `find-file-other-window'
941 `find-file-other-frame'
942 For the calendar, use the variable `calendar-setup'.
943 For BBDB, it is currently only possible to display the matches in
944 another window."
945 :group 'org-link
946 :type '(list
947 (cons (const vm)
948 (choice
949 (const vm-visit-folder)
950 (const vm-visit-folder-other-window)
951 (const vm-visit-folder-other-frame)))
952 (cons (const gnus)
953 (choice
954 (const gnus)
955 (const gnus-other-frame)))
956 (cons (const file)
957 (choice
958 (const find-file)
959 (const find-file-other-window)
960 (const find-file-other-frame)))))
961
962 (defcustom org-usenet-links-prefer-google nil
963 "Non-nil means, `org-store-link' will create web links to google groups.
964 When nil, Gnus will be used for such links.
965 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
966 negates this setting for the duration of the command."
967 :group 'org-link
968 :type 'boolean)
969
970 (defcustom org-open-non-existing-files nil
971 "Non-nil means, `org-open-file' will open non-existing file.
972 When nil, an error will be generated."
973 :group 'org-link
974 :type 'boolean)
975
976 (defcustom org-confirm-shell-links t
977 "Non-nil means, ask for confirmation before executing shell links.
978 The default is true, to keep new users from shooting into their own foot."
979 :group 'org-link
980 :type 'boolean)
981
982 (defconst org-file-apps-defaults-gnu
983 '((t . emacs)
984 ("jpg" . "xv %s")
985 ("gif" . "xv %s")
986 ("ppm" . "xv %s")
987 ("pgm" . "xv %s")
988 ("pbm" . "xv %s")
989 ("tif" . "xv %s")
990 ("png" . "xv %s")
991 ("ps" . "gv %s")
992 ("ps.gz" . "gv %s")
993 ("eps" . "gv %s")
994 ("eps.gz" . "gv %s")
995 ("dvi" . "xdvi %s")
996 ("mpeg" . "plaympeg %s")
997 ("mp3" . "plaympeg %s")
998 ("fig" . "xfig %s")
999 ("pdf" . "acroread %s")
1000 ("doc" . "soffice %s")
1001 ("ppt" . "soffice %s")
1002 ("pps" . "soffice %s")
1003 ("html" . "netscape -remote openURL(%s,new-window)")
1004 ("htm" . "netscape -remote openURL(%s,new-window)")
1005 ("xs" . "soffice %s"))
1006 "Default file applications on a UNIX/LINUX system.
1007 See `org-file-apps'.")
1008
1009 (defconst org-file-apps-defaults-macosx
1010 '((t . "open %s")
1011 ("ps" . "gv %s")
1012 ("ps.gz" . "gv %s")
1013 ("eps" . "gv %s")
1014 ("eps.gz" . "gv %s")
1015 ("dvi" . "xdvi %s")
1016 ("fig" . "xfig %s"))
1017 "Default file applications on a MacOS X system.
1018 The system \"open\" is known as a default, but we use X11 applications
1019 for some files for which the OS does not have a good default.
1020 See `org-file-apps'.")
1021
1022 (defconst org-file-apps-defaults-windowsnt
1023 '((t . (w32-shell-execute "open" file)))
1024 "Default file applications on a Windows NT system.
1025 The system \"open\" is used for most files.
1026 See `org-file-apps'.")
1027
1028 (defcustom org-file-apps
1029 '(
1030 ("txt" . emacs)
1031 ("tex" . emacs)
1032 ("ltx" . emacs)
1033 ("org" . emacs)
1034 ("el" . emacs)
1035 )
1036 "External applications for opening `file:path' items in a document.
1037 Org-mode uses system defaults for different file types, but
1038 you can use this variable to set the application for a given file
1039 extension. The entries in this list are cons cells with a file extension
1040 and the corresponding command. Possible values for the command are:
1041 `emacs' The file will be visited by the current Emacs process.
1042 `default' Use the default application for this file type.
1043 string A command to be executed by a shell; %s will be replaced
1044 by the path to the file.
1045 sexp A Lisp form which will be evaluated. The file path will
1046 be available in the Lisp variable `file'.
1047 For more examples, see the system specific constants
1048 `org-file-apps-defaults-macosx'
1049 `org-file-apps-defaults-windowsnt'
1050 `org-file-apps-defaults-gnu'."
1051 :group 'org-link
1052 :type '(repeat
1053 (cons (string :tag "Extension")
1054 (choice :value ""
1055 (const :tag "Visit with Emacs" 'emacs)
1056 (const :tag "Use system default" 'default)
1057 (string :tag "Command")
1058 (sexp :tag "Lisp form")))))
1059
1060
1061 (defgroup org-remember nil
1062 "Options concerning interaction with remember.el."
1063 :tag "Org Remember"
1064 :group 'org)
1065
1066 (defcustom org-directory "~/org"
1067 "Directory with org files.
1068 This directory will be used as default to prompt for org files.
1069 Used by the hooks for remember.el."
1070 :group 'org-remember
1071 :type 'directory)
1072
1073 (defcustom org-default-notes-file "~/.notes"
1074 "Default target for storing notes.
1075 Used by the hooks for remember.el. This can be a string, or nil to mean
1076 the value of `remember-data-file'."
1077 :group 'org-remember
1078 :type '(choice
1079 (const :tag "Default from remember-data-file" nil)
1080 file))
1081
1082 (defcustom org-reverse-note-order nil
1083 "Non-nil means, store new notes at the beginning of a file or entry.
1084 When nil, new notes will be filed to the end of a file or entry."
1085 :group 'org-remember
1086 :type '(choice
1087 (const :tag "Reverse always" t)
1088 (const :tag "Reverse never" nil)
1089 (repeat :tag "By file name regexp"
1090 (cons regexp boolean))))
1091
1092 (defgroup org-table nil
1093 "Options concerning tables in Org-mode."
1094 :tag "Org Table"
1095 :group 'org)
1096
1097 (defcustom org-enable-table-editor 'optimized
1098 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1099 When nil, such lines will be treated like ordinary lines.
1100
1101 When equal to the symbol `optimized', the table editor will be optimized to
1102 do the following
1103 - Use automatic overwrite mode in front of whitespace in table fields.
1104 This make the structure of the table stay in tact as long as the edited
1105 field does not exceed the column width.
1106 - Minimize the number of realigns. Normally, the table is aligned each time
1107 TAB or RET are pressed to move to another field. With optimization this
1108 happens only if changes to a field might have changed the column width.
1109 Optimization requires replacing the functions `self-insert-command',
1110 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1111 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1112 very good at guessing when a re-align will be necessary, but you can always
1113 force one with \\[org-ctrl-c-ctrl-c].
1114
1115 If you would like to use the optimized version in Org-mode, but the
1116 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1117
1118 This variable can be used to turn on and off the table editor during a session,
1119 but in order to toggle optimization, a restart is required.
1120
1121 See also the variable `org-table-auto-blank-field'."
1122 :group 'org-table
1123 :type '(choice
1124 (const :tag "off" nil)
1125 (const :tag "on" t)
1126 (const :tag "on, optimized" optimized)))
1127
1128 (defcustom org-table-auto-blank-field t
1129 "Non-nil means, automatically blank table field when starting to type into it.
1130 This only happens when typing immediately after a field motion
1131 command (TAB, S-TAB or RET).
1132 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1133 :group 'org-table
1134 :type 'boolean)
1135
1136 (defcustom org-table-default-size "5x2"
1137 "The default size for newly created tables, Columns x Rows."
1138 :group 'org-table
1139 :type 'string)
1140
1141 (defcustom org-table-automatic-realign t
1142 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1143 When nil, aligning is only done with \\[org-table-align], or after column
1144 removal/insertion."
1145 :group 'org-table
1146 :type 'boolean)
1147
1148 (defcustom org-table-spaces-around-separators '(1 . 1)
1149 "The number of spaces to be placed before and after separators."
1150 :group 'org-table
1151 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1152
1153 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1154 "The number of spaces to be placed before and after separators.
1155 This option applies when the column separators have been made invisible."
1156 :group 'org-table
1157 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1158
1159 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1160 "Regular expression for recognizing numbers in table columns.
1161 If a table column contains mostly numbers, it will be aligned to the
1162 right. If not, it will be aligned to the left.
1163
1164 The default value of this option is a regular expression which allows
1165 anything which looks remotely like a number as used in scientific
1166 context. For example, all of the following will be considered a
1167 number:
1168 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1169
1170 Other options offered by the customize interface are more restrictive."
1171 :group 'org-table
1172 :type '(choice
1173 (const :tag "Positive Integers"
1174 "^[0-9]+$")
1175 (const :tag "Integers"
1176 "^[-+]?[0-9]+$")
1177 (const :tag "Floating Point Numbers"
1178 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1179 (const :tag "Floating Point Number or Integer"
1180 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1181 (const :tag "Exponential, Floating point, Integer"
1182 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1183 (const :tag "Very General Number-Like"
1184 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1185 (string :tag "Regexp:")))
1186
1187 (defcustom org-table-number-fraction 0.5
1188 "Fraction of numbers in a column required to make the column align right.
1189 In a column all non-white fields are considered. If at least this
1190 fraction of fields is matched by `org-table-number-fraction',
1191 alignment to the right border applies."
1192 :group 'org-table
1193 :type 'number)
1194
1195 (defcustom org-export-highlight-first-table-line t
1196 "Non-nil means, highlight the first table line.
1197 In HTML export, this means use <th> instead of <td>.
1198 In tables created with table.el, this applies to the first table line.
1199 In Org-mode tables, all lines before the first horizontal separator
1200 line will be formatted with <th> tags."
1201 :group 'org-table
1202 :type 'boolean)
1203
1204 (defcustom org-table-tab-recognizes-table.el t
1205 "Non-nil means, TAB will automatically notice a table.el table.
1206 When it sees such a table, it moves point into it and - if necessary -
1207 calls `table-recognize-table'."
1208 :group 'org-table
1209 :type 'boolean)
1210
1211 (defgroup org-table-calculation nil
1212 "Options concerning tables in Org-mode."
1213 :tag "Org Table Calculation"
1214 :group 'org)
1215
1216 (defcustom org-table-copy-increment t
1217 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1218 :group 'org-table-calculation
1219 :type 'boolean)
1220
1221 (defcustom org-calc-default-modes
1222 '(calc-internal-prec 12
1223 calc-float-format (float 5)
1224 calc-angle-mode deg
1225 calc-prefer-frac nil
1226 calc-symbolic-mode nil
1227 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1228 calc-display-working-message t
1229 )
1230 "List with Calc mode settings for use in calc-eval for table formulas.
1231 The list must contain alternating symbols (calc modes variables and values.
1232 Don't remove any of the default settings, just change the values. Org-mode
1233 relies on the variables to be present in the list."
1234 :group 'org-table-calculation
1235 :type 'plist)
1236
1237 (defcustom org-table-formula-evaluate-inline t
1238 "Non-nil means, TAB and RET evaluate a formula in current table field.
1239 If the current field starts with an equal sign, it is assumed to be a formula
1240 which should be evaluated as described in the manual and in the documentation
1241 string of the command `org-table-eval-formula'. This feature requires the
1242 Emacs calc package.
1243 When this variable is nil, formula calculation is only available through
1244 the command \\[org-table-eval-formula]."
1245 :group 'org-table-calculation
1246 :type 'boolean)
1247
1248
1249 (defcustom org-table-formula-use-constants t
1250 "Non-nil means, interpret constants in formulas in tables.
1251 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1252 by the value given in `org-table-formula-constants', or by a value obtained
1253 from the `constants.el' package."
1254 :group 'org-table-calculation
1255 :type 'boolean)
1256
1257 (defcustom org-table-formula-constants nil
1258 "Alist with constant names and values, for use in table formulas.
1259 The car of each element is a name of a constant, without the `$' before it.
1260 The cdr is the value as a string. For example, if you'd like to use the
1261 speed of light in a formula, you would configure
1262
1263 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1264
1265 and then use it in an equation like `$1*$c'."
1266 :group 'org-table-calculation
1267 :type '(repeat
1268 (cons (string :tag "name")
1269 (string :tag "value"))))
1270
1271 (defcustom org-table-formula-numbers-only nil
1272 "Non-nil means, calculate only with numbers in table formulas.
1273 Then all input fields will be converted to a number, and the result
1274 must also be a number. When nil, calc's full potential is available
1275 in table calculations, including symbolics etc."
1276 :group 'org-table-calculation
1277 :type 'boolean)
1278
1279 (defcustom org-table-allow-automatic-line-recalculation t
1280 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1281 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1282 :group 'org-table-calculation
1283 :type 'boolean)
1284
1285 (defgroup org-export nil
1286 "Options for exporting org-listings."
1287 :tag "Org Export"
1288 :group 'org)
1289
1290 (defcustom org-export-language-setup
1291 '(("en" "Author" "Date" "Table of Contents")
1292 ("da" "Ophavsmand" "Dato" "Indhold")
1293 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1294 ("es" "Autor" "Fecha" "\xccndice")
1295 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1296 ("it" "Autore" "Data" "Indice")
1297 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1298 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1299 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1300 "Terms used in export text, translated to different languages.
1301 Use the variable `org-export-default-language' to set the language,
1302 or use the +OPTION lines for a per-file setting."
1303 :group 'org-export
1304 :type '(repeat
1305 (list
1306 (string :tag "HTML language tag")
1307 (string :tag "Author")
1308 (string :tag "Date")
1309 (string :tag "Table of Contents"))))
1310
1311 (defcustom org-export-default-language "en"
1312 "The default language of HTML export, as a string.
1313 This should have an association in `org-export-language-setup'"
1314 :group 'org-export
1315 :type 'string)
1316
1317 (defcustom org-export-headline-levels 3
1318 "The last level which is still exported as a headline.
1319 Inferior levels will produce itemize lists when exported.
1320 Note that a numeric prefix argument to an exporter function overrides
1321 this setting.
1322
1323 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1324 :group 'org-export
1325 :type 'number)
1326
1327 (defcustom org-export-with-section-numbers t
1328 "Non-nil means, add section numbers to headlines when exporting.
1329
1330 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1331 :group 'org-export
1332 :type 'boolean)
1333
1334 (defcustom org-export-with-toc t
1335 "Non-nil means, create a table of contents in exported files.
1336 The TOC contains headlines with levels up to`org-export-headline-levels'.
1337
1338 Headlines which contain any TODO items will be marked with \"(*)\" in
1339 ASCII export, and with red color in HTML output.
1340
1341 In HTML output, the TOC will be clickable.
1342
1343 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1344 :group 'org-export
1345 :type 'boolean)
1346
1347 (defcustom org-export-preserve-breaks nil
1348 "Non-nil means, preserve all line breaks when exporting.
1349 Normally, in HTML output paragraphs will be reformatted. In ASCII
1350 export, line breaks will always be preserved, regardless of this variable.
1351
1352 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1353 :group 'org-export
1354 :type 'boolean)
1355
1356 (defcustom org-export-html-inline-images t
1357 "Non-nil means, inline images into exported HTML pages.
1358 The link will still be to the original location of the image file.
1359 So if you are moving the page, lets say to your public HTML site,
1360 you will have to move the image and maybe change the link."
1361 :group 'org-export
1362 :type 'boolean)
1363
1364 (defcustom org-export-html-expand t
1365 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1366 When nil, these tags will be exported as plain text and therefore
1367 not be interpreted by a browser.
1368
1369 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1370 :group 'org-export
1371 :type 'boolean)
1372
1373 (defcustom org-export-with-fixed-width t
1374 "Non-nil means, lines starting with \":\" will be in fixed width font.
1375 This can be used to have pre-formatted text, fragments of code etc. For
1376 example
1377 : ;; Some Lisp examples
1378 : (while (defc cnt)
1379 : (ding))
1380 will be looking just like this in also HTML. In ASCII export, this option
1381 has no effect.
1382
1383 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1384 :group 'org-export
1385 :type 'boolean)
1386
1387 (defcustom org-export-with-tables t
1388 "If non-nil, lines starting with \"|\" define a table.
1389 For example:
1390
1391 | Name | Address | Birthday |
1392 |-------------+----------+-----------|
1393 | Arthur Dent | England | 29.2.2100 |
1394
1395 In ASCII export, this option has no effect.
1396
1397 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1398 :group 'org-export
1399 :type 'boolean)
1400
1401 (defcustom org-export-prefer-native-exporter-for-tables nil
1402 "Non-nil means, always export tables created with table.el natively.
1403 Natively means, use the HTML code generator in table.el.
1404 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1405 the table does not use row- or column-spanning). This has the
1406 advantage, that the automatic HTML conversions for math symbols and
1407 sub/superscripts can be applied. Org-mode's HTML generator is also
1408 much faster."
1409 :group 'org-export
1410 :type 'boolean)
1411
1412 (defcustom org-export-html-table-tag
1413 "<table border=1 cellspacing=0 cellpadding=6>"
1414 "The HTML tag used to start a table.
1415 This must be a <table> tag, but you may change the options like
1416 borders and spacing."
1417 :group 'org-export
1418 :type 'string)
1419
1420 (defcustom org-export-with-emphasize t
1421 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1422 If the export target supports emphasizing text, the word will be
1423 typeset in bold, italic, or underlined, respectively. Works only for
1424 single words, but you can say: I *really* *mean* *this*.
1425 In ASCII export, this option has no effect.
1426
1427 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1428 :group 'org-export
1429 :type 'boolean)
1430
1431 (defcustom org-match-sexp-depth 3
1432 "Number of stacked braces for sub/superscript matching.
1433 This has to be set before loading org.el to be effective."
1434 :group 'org-export
1435 :type 'integer)
1436
1437 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1438 (defcustom org-export-with-sub-superscripts t
1439 "Non-nil means, interpret \"_\" and \"^\" for export.
1440 When this option is turned on, you can use TeX-like syntax for sub- and
1441 superscripts. Several characters after \"_\" or \"^\" will be
1442 considered as a single item - so grouping with {} is normally not
1443 needed. For example, the following things will be parsed as single
1444 sub- or superscripts.
1445
1446 10^24 or 10^tau several digits will be considered 1 item
1447 10^-12 or 10^-tau a leading sign with digits or a word
1448 x^2-y^3 will be read as x^2 - y^3, because items are
1449 terminated by almost any nonword/nondigit char.
1450 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1451
1452 Still, ambiguity is possible - so when in doubt use {} to enclose the
1453 sub/superscript.
1454 In ASCII export, this option has no effect.
1455
1456 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1457 :group 'org-export
1458 :type 'boolean)
1459
1460 (defcustom org-export-with-TeX-macros t
1461 "Non-nil means, interpret simple TeX-like macros when exporting.
1462 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1463 No only real TeX macros will work here, but the standard HTML entities
1464 for math can be used as macro names as well. For a list of supported
1465 names in HTML export, see the constant `org-html-entities'.
1466 In ASCII export, this option has no effect.
1467
1468 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1469 :group 'org-export
1470 :type 'boolean)
1471
1472 (defcustom org-export-html-with-timestamp nil
1473 "If non-nil, write `org-export-html-html-helper-timestamp'
1474 into the exported html text. Otherwise, the buffer will just be saved
1475 to a file."
1476 :group 'org-export
1477 :type 'boolean)
1478
1479 (defcustom org-export-html-html-helper-timestamp
1480 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1481 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1482 :group 'org-export
1483 :type 'string)
1484
1485 (defcustom org-export-ascii-show-new-buffer t
1486 "Non-nil means, popup buffer containing the exported ASCII text.
1487 Otherwise the buffer will just be saved to a file and stay hidden."
1488 :group 'org-export
1489 :type 'boolean)
1490
1491 (defcustom org-export-html-show-new-buffer nil
1492 "Non-nil means, popup buffer containing the exported html text.
1493 Otherwise, the buffer will just be saved to a file and stay hidden."
1494 :group 'org-export
1495 :type 'boolean)
1496
1497 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1498 "The file name for the iCalendar file covering all agenda files.
1499 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1500 :group 'org-export
1501 :type 'file)
1502
1503 (defcustom org-icalendar-include-todo nil
1504 "Non-nil means, export to iCalendar files should also cover TODO items."
1505 :group 'org-export
1506 :type 'boolean)
1507
1508 ;; FIXME: not yet used.
1509 (defcustom org-icalendar-combined-name "OrgMode"
1510 "Calendar name for the combined iCalendar representing all agenda files."
1511 :group 'org-export
1512 :type 'string)
1513
1514 (defgroup org-faces nil
1515 "Faces for highlighting in Org-mode."
1516 :tag "Org Faces"
1517 :group 'org)
1518
1519 (defface org-level-1 ;; font-lock-function-name-face
1520 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1521 (((class color) (background light)) (:foreground "Blue"))
1522 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1523 (t (:inverse-video t :bold t)))
1524 "Face used for level 1 headlines."
1525 :group 'org-faces)
1526
1527 (defface org-level-2 ;; font-lock-variable-name-face
1528 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1529 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1530 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1531 (t (:bold t :italic t)))
1532 "Face used for level 2 headlines."
1533 :group 'org-faces)
1534
1535 (defface org-level-3 ;; font-lock-keyword-face
1536 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1537 (((class color) (background light)) (:foreground "Purple"))
1538 (((class color) (background dark)) (:foreground "Cyan"))
1539 (t (:bold t)))
1540 "Face used for level 3 headlines."
1541 :group 'org-faces)
1542
1543 (defface org-level-4 ;; font-lock-comment-face
1544 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1545 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1546 (((class color) (background light)) (:foreground "Firebrick"))
1547 (((class color) (background dark)) (:foreground "chocolate1"))
1548 (t (:bold t :italic t)))
1549 "Face used for level 4 headlines."
1550 :group 'org-faces)
1551
1552 (defface org-level-5 ;; font-lock-type-face
1553 '((((type tty) (class color)) (:foreground "green"))
1554 (((class color) (background light)) (:foreground "ForestGreen"))
1555 (((class color) (background dark)) (:foreground "PaleGreen"))
1556 (t (:bold t :underline t)))
1557 "Face used for level 5 headlines."
1558 :group 'org-faces)
1559
1560 (defface org-level-6 ;; font-lock-constant-face
1561 '((((type tty) (class color)) (:foreground "magenta"))
1562 (((class color) (background light)) (:foreground "CadetBlue"))
1563 (((class color) (background dark)) (:foreground "Aquamarine"))
1564 (t (:bold t :underline t)))
1565 "Face used for level 6 headlines."
1566 :group 'org-faces)
1567
1568 (defface org-level-7 ;; font-lock-builtin-face
1569 '((((type tty) (class color)) (:foreground "blue" :weight light))
1570 (((class color) (background light)) (:foreground "Orchid"))
1571 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1572 (t (:bold t)))
1573 "Face used for level 7 headlines."
1574 :group 'org-faces)
1575
1576 (defface org-level-8 ;; font-lock-string-face
1577 '((((type tty) (class color)) (:foreground "green"))
1578 (((class color) (background light)) (:foreground "RosyBrown"))
1579 (((class color) (background dark)) (:foreground "LightSalmon"))
1580 (t (:italic t)))
1581 "Face used for level 8 headlines."
1582 :group 'org-faces)
1583
1584 (defface org-special-keyword ;; font-lock-string-face
1585 '((((type tty) (class color)) (:foreground "green"))
1586 (((class color) (background light)) (:foreground "RosyBrown"))
1587 (((class color) (background dark)) (:foreground "LightSalmon"))
1588 (t (:italic t)))
1589 "Face used for level 8 headlines."
1590 :group 'org-faces)
1591
1592 (defface org-warning ;; font-lock-warning-face
1593 '((((type tty) (class color)) (:foreground "red"))
1594 (((class color) (background light)) (:foreground "Red" :bold t))
1595 (((class color) (background dark)) (:foreground "Red1" :bold t))
1596 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1597 (t (:inverse-video t :bold t)))
1598 "Face for deadlines and TODO keywords."
1599 :group 'org-faces)
1600
1601 (defcustom org-fontify-done-headline nil
1602 "Non-nil means, change the face of a headline if it is marked DONE.
1603 Normally, only the TODO/DONE keyword indicates the state of a headline.
1604 When this is non-nil, the headline after the keyword is set to the
1605 `org-headline-done' as an additional indication."
1606 :group 'org-faces
1607 :type 'boolean)
1608
1609 (defface org-headline-done ;; font-lock-string-face
1610 '((((type tty) (class color)) (:foreground "green"))
1611 (((class color) (background light)) (:foreground "RosyBrown"))
1612 (((class color) (background dark)) (:foreground "LightSalmon"))
1613 (t (:italic t)))
1614 "Face used to indicate that a headline is DONE. See also the variable
1615 `org-fontify-done-headline'."
1616 :group 'org-faces)
1617
1618 ;; Inheritance does not yet work for xemacs. So we just copy...
1619
1620 (defface org-deadline-announce
1621 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1622 (((class color) (background light)) (:foreground "Blue"))
1623 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1624 (t (:inverse-video t :bold t)))
1625 "Face for upcoming deadlines."
1626 :group 'org-faces)
1627
1628 (defface org-scheduled-today
1629 '((((type tty) (class color)) (:foreground "green"))
1630 (((class color) (background light)) (:foreground "DarkGreen"))
1631 (((class color) (background dark)) (:foreground "PaleGreen"))
1632 (t (:bold t :underline t)))
1633 "Face for items scheduled for a certain day."
1634 :group 'org-faces)
1635
1636 (defface org-scheduled-previously
1637 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1638 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1639 (((class color) (background light)) (:foreground "Firebrick"))
1640 (((class color) (background dark)) (:foreground "chocolate1"))
1641 (t (:bold t :italic t)))
1642 "Face for items scheduled previously, and not yet done."
1643 :group 'org-faces)
1644
1645 (defface org-formula
1646 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1647 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1648 (((class color) (background light)) (:foreground "Firebrick"))
1649 (((class color) (background dark)) (:foreground "chocolate1"))
1650 (t (:bold t :italic t)))
1651 "Face for items scheduled previously, and not yet done."
1652 :group 'org-faces)
1653
1654 (defface org-link
1655 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1656 (((class color) (background light)) (:foreground "Purple"))
1657 (((class color) (background dark)) (:foreground "Cyan"))
1658 (t (:bold t)))
1659 "Face for links."
1660 :group 'org-faces)
1661
1662 (defface org-done ;; font-lock-type-face
1663 '((((type tty) (class color)) (:foreground "green"))
1664 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1665 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1666 (t (:bold t :underline t)))
1667 "Face used for DONE."
1668 :group 'org-faces)
1669
1670 (defface org-table ;; font-lock-function-name-face
1671 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1672 (((class color) (background light)) (:foreground "Blue"))
1673 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1674 (t (:inverse-video t :bold t)))
1675 "Face used for tables."
1676 :group 'org-faces)
1677
1678 (defface org-time-grid ;; font-lock-variable-name-face
1679 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1680 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1681 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1682 (t (:bold t :italic t)))
1683 "Face used for level 2 headlines."
1684 :group 'org-faces)
1685
1686 (defvar org-level-faces
1687 '(
1688 org-level-1
1689 org-level-2
1690 org-level-3
1691 org-level-4
1692 org-level-5
1693 org-level-6
1694 org-level-7
1695 org-level-8
1696 ))
1697 (defvar org-n-levels (length org-level-faces))
1698
1699 (defun org-set-regexps-and-options ()
1700 "Precompute regular expressions for current buffer."
1701 (when (eq major-mode 'org-mode)
1702 (let ((re (org-make-options-regexp
1703 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1704 "STARTUP" "ARCHIVE")))
1705 (splitre "[ \t]+")
1706 kwds int key value cat arch)
1707 (save-excursion
1708 (save-restriction
1709 (widen)
1710 (goto-char (point-min))
1711 (while (re-search-forward re nil t)
1712 (setq key (match-string 1) value (match-string 2))
1713 (cond
1714 ((equal key "CATEGORY")
1715 (if (string-match "[ \t]+$" value)
1716 (setq value (replace-match "" t t value)))
1717 (setq cat (intern value)))
1718 ((equal key "SEQ_TODO")
1719 (setq int 'sequence
1720 kwds (append kwds (org-split-string value splitre))))
1721 ((equal key "PRI_TODO")
1722 (setq int 'priority
1723 kwds (append kwds (org-split-string value splitre))))
1724 ((equal key "TYP_TODO")
1725 (setq int 'type
1726 kwds (append kwds (org-split-string value splitre))))
1727 ((equal key "STARTUP")
1728 (let ((opts (org-split-string value splitre))
1729 (set '(("fold" org-startup-folded t)
1730 ("nofold" org-startup-folded nil)
1731 ("content" org-startup-folded content)
1732 ("dlcheck" org-startup-with-deadline-check t)
1733 ("nodlcheck" org-startup-with-deadline-check nil)))
1734 l var val)
1735 (while (setq l (assoc (pop opts) set))
1736 (setq var (nth 1 l) val (nth 2 l))
1737 (set (make-local-variable var) val))))
1738 ((equal key "ARCHIVE")
1739 (string-match " *$" value)
1740 (setq arch (replace-match "" t t value))
1741 (remove-text-properties 0 (length arch)
1742 '(face t fontified t) arch)))
1743 )))
1744 (and cat (set (make-local-variable 'org-category) cat))
1745 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1746 (and arch (set (make-local-variable 'org-archive-location) arch))
1747 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1748 ;; Compute the regular expressions and other local variables
1749 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1750 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1751 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1752 (length org-scheduled-string)))
1753 org-done-string
1754 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1755 org-todo-regexp
1756 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1757 "\\|") "\\)\\>")
1758 org-not-done-regexp
1759 (concat "\\<\\("
1760 (mapconcat 'regexp-quote
1761 (nreverse (cdr (reverse org-todo-keywords)))
1762 "\\|")
1763 "\\)\\>")
1764 org-todo-line-regexp
1765 (concat "^\\(\\*+\\)[ \t]*\\("
1766 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1767 "\\)? *\\(.*\\)")
1768 org-nl-done-regexp
1769 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1770 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1771 org-deadline-regexp (concat "\\<" org-deadline-string)
1772 org-deadline-time-regexp
1773 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1774 org-deadline-line-regexp
1775 (concat "\\<\\(" org-deadline-string "\\).*")
1776 org-scheduled-regexp
1777 (concat "\\<" org-scheduled-string)
1778 org-scheduled-time-regexp
1779 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1780 (org-set-font-lock-defaults)))
1781
1782 ;; Tell the compiler about dynamically scoped variables,
1783 ;; and variables from other packages
1784 (eval-when-compile
1785 (defvar zmacs-regions)
1786 (defvar original-date)
1787 (defvar org-transient-mark-mode)
1788 (defvar org-old-auto-fill-inhibit-regexp)
1789 (defvar orgtbl-mode-menu)
1790 (defvar org-html-entities)
1791 (defvar org-goto-start-pos)
1792 (defvar org-cursor-color)
1793 (defvar org-time-was-given)
1794 (defvar org-ts-what)
1795 (defvar mark-active)
1796 (defvar timecnt)
1797 (defvar levels-open)
1798 (defvar title)
1799 (defvar author)
1800 (defvar email)
1801 (defvar text)
1802 (defvar entry)
1803 (defvar date)
1804 (defvar language)
1805 (defvar options)
1806 (defvar ans1)
1807 (defvar ans2)
1808 (defvar starting-day)
1809 (defvar include-all-loc)
1810 (defvar vm-message-pointer)
1811 (defvar vm-folder-directory)
1812 (defvar wl-summary-buffer-elmo-folder)
1813 (defvar wl-summary-buffer-folder-name)
1814 (defvar gnus-group-name)
1815 (defvar gnus-article-current)
1816 (defvar w3m-current-url)
1817 (defvar org-selected-point)
1818 (defvar calendar-mode-map)
1819 (defvar remember-save-after-remembering)
1820 (defvar remember-data-file))
1821
1822
1823 ;;; Define the mode
1824
1825 (defvar org-mode-map (copy-keymap outline-mode-map)
1826 "Keymap for Org-mode.")
1827
1828 (defvar org-struct-menu)
1829 (defvar org-org-menu)
1830 (defvar org-tbl-menu)
1831
1832 ;; We use a before-change function to check if a table might need
1833 ;; an update.
1834 (defvar org-table-may-need-update t
1835 "Indicates of a table might need an update.
1836 This variable is set by `org-before-change-function'. `org-table-align'
1837 sets it back to nil.")
1838 (defvar org-mode-hook nil)
1839 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1840
1841
1842 ;;;###autoload
1843 (define-derived-mode org-mode outline-mode "Org"
1844 "Outline-based notes management and organizer, alias
1845 \"Carstens outline-mode for keeping track of everything.\"
1846
1847 Org-mode develops organizational tasks around a NOTES file which
1848 contains information about projects as plain text. Org-mode is
1849 implemented on top of outline-mode, which is ideal to keep the content
1850 of large files well structured. It supports ToDo items, deadlines and
1851 time stamps, which magically appear in the diary listing of the Emacs
1852 calendar. Tables are easily created with a built-in table editor.
1853 Plain text URL-like links connect to websites, emails (VM), Usenet
1854 messages (Gnus), BBDB entries, and any files related to the project.
1855 For printing and sharing of notes, an Org-mode file (or a part of it)
1856 can be exported as a structured ASCII or HTML file.
1857
1858 The following commands are available:
1859
1860 \\{org-mode-map}"
1861 (easy-menu-add org-org-menu)
1862 (easy-menu-add org-tbl-menu)
1863 (org-install-agenda-files-menu)
1864 (setq outline-regexp "\\*+")
1865 (if org-startup-truncated (setq truncate-lines t))
1866 (org-set-regexps-and-options)
1867 (set (make-local-variable 'font-lock-unfontify-region-function)
1868 'org-unfontify-region)
1869 ;; Activate before-change-function
1870 (set (make-local-variable 'org-table-may-need-update) t)
1871 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1872 (add-hook 'before-change-functions 'org-before-change-function nil
1873 'local)
1874 ;; Paragraph regular expressions
1875 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1876 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1877 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1878 (set (make-local-variable 'auto-fill-inhibit-regexp)
1879 (concat "\\*\\|#"
1880 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1881 (concat
1882 "\\|[ \t]*["
1883 (if org-enable-table-editor "|" "")
1884 (if org-enable-fixed-width-editor ":" "")
1885 "]"))))
1886 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1887 ;; Settings for Calc embedded mode
1888 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1889 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1890 (if (and org-insert-mode-line-in-empty-file
1891 (interactive-p)
1892 (= (point-min) (point-max)))
1893 (insert " -*- mode: org -*-\n\n"))
1894
1895 ;; Get rid of Outline menus, they are not needed
1896 ;; Need to do this here because define-derived-mode sets up
1897 ;; the keymap so late.
1898 (if org-xemacs-p
1899 (progn
1900 (delete-menu-item '("Headings"))
1901 (delete-menu-item '("Show"))
1902 (delete-menu-item '("Hide"))
1903 (set-menubar-dirty-flag))
1904 (define-key org-mode-map [menu-bar headings] 'undefined)
1905 (define-key org-mode-map [menu-bar hide] 'undefined)
1906 (define-key org-mode-map [menu-bar show] 'undefined))
1907
1908 (unless org-inhibit-startup
1909 (if org-startup-with-deadline-check
1910 (call-interactively 'org-check-deadlines)
1911 (cond
1912 ((eq org-startup-folded t)
1913 (org-cycle '(4)))
1914 ((eq org-startup-folded 'content)
1915 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1916 (org-cycle '(4)) (org-cycle '(4))))))))
1917
1918 (defun org-fill-paragraph (&optional justify)
1919 "Re-align a table, pass through to fill-paragraph if no table."
1920 (save-excursion
1921 (beginning-of-line 1)
1922 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1923
1924 (defsubst org-current-line (&optional pos)
1925 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1926
1927 ;;; Font-Lock stuff
1928
1929 (defvar org-mouse-map (make-sparse-keymap))
1930 (define-key org-mouse-map
1931 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1932 (define-key org-mouse-map
1933 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1934
1935 (require 'font-lock)
1936
1937 (defconst org-non-link-chars "\t\n\r|<>\000")
1938 (defconst org-link-regexp
1939 (if org-allow-space-in-links
1940 (concat
1941 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1942 (concat
1943 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1944 )
1945 "Regular expression for matching links.")
1946 (defconst org-link-maybe-angles-regexp
1947 (concat "<?\\(" org-link-regexp "\\)>?")
1948 "Matches a link and optionally surrounding angle brackets.")
1949 (defconst org-protected-link-regexp
1950 (concat "\000" org-link-regexp "\000")
1951 "Matches a link and optionally surrounding angle brackets.")
1952
1953 (defconst org-ts-lengths
1954 (cons (length (format-time-string (car org-time-stamp-formats)))
1955 (length (format-time-string (cdr org-time-stamp-formats))))
1956 "This holds the lengths of the two different time formats.")
1957 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1958 "Regular expression for fast time stamp matching.")
1959 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1960 "Regular expression matching time strings for analysis.")
1961 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1962 "Regular expression matching time stamps, with groups.")
1963 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1964 "Regular expression matching a time stamp range.")
1965 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1966 org-ts-regexp "\\)?")
1967 "Regular expression matching a time stamp or time stamp range.")
1968
1969 (defun org-activate-links (limit)
1970 "Run through the buffer and add overlays to links."
1971 (if (re-search-forward org-link-regexp limit t)
1972 (progn
1973 (add-text-properties (match-beginning 0) (match-end 0)
1974 (list 'mouse-face 'highlight
1975 'keymap org-mouse-map))
1976 t)))
1977
1978 (defun org-activate-dates (limit)
1979 "Run through the buffer and add overlays to dates."
1980 (if (re-search-forward org-tsr-regexp limit t)
1981 (progn
1982 (add-text-properties (match-beginning 0) (match-end 0)
1983 (list 'mouse-face 'highlight
1984 'keymap org-mouse-map))
1985 t)))
1986
1987 (defun org-font-lock-level ()
1988 (save-excursion
1989 (org-back-to-heading t)
1990 (- (match-end 0) (match-beginning 0))))
1991
1992 (defvar org-font-lock-keywords nil)
1993
1994 (defun org-set-font-lock-defaults ()
1995 (let ((org-font-lock-extra-keywords
1996 (list
1997 '(org-activate-links (0 'org-link))
1998 '(org-activate-dates (0 'org-link))
1999 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2000 '(1 'org-warning t))
2001 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2002 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
2003 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
2004 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2005 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2006 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2007 ;; (3 'bold))
2008 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2009 ;; (3 'italic))
2010 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2011 ;; (3 'underline))
2012 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2013 ; '(1 'org-warning t))
2014 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2015 "\\|" org-quote-string "\\)\\>")
2016 '(1 'org-special-keyword t))
2017 '("^#.*" (0 'font-lock-comment-face t))
2018 (if org-fontify-done-headline
2019 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2020 '(1 'org-done t) '(2 'org-headline-done t))
2021 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2022 '(1 'org-done t)))
2023 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2024 (1 'org-table t))
2025 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2026 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2027 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2028 )))
2029 (set (make-local-variable 'org-font-lock-keywords)
2030 (append
2031 (if org-noutline-p ; FIXME: I am not sure if eval will work
2032 ; on XEmacs if noutline is ever ported
2033 `((eval . (list "^\\(\\*+\\).*"
2034 ,(if org-level-color-stars-only 1 0)
2035 '(nth ;; FIXME: 1<->0 ????
2036 (% (- (match-end 1) (match-beginning 1) 1)
2037 org-n-levels)
2038 org-level-faces)
2039 nil t)))
2040 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2041 (,(if org-level-color-stars-only 2 0)
2042 (nth (% (- (match-end 2) (match-beginning 2) 1)
2043 org-n-levels)
2044 org-level-faces)
2045 nil t))))
2046 org-font-lock-extra-keywords))
2047 (set (make-local-variable 'font-lock-defaults)
2048 '(org-font-lock-keywords t nil nil backward-paragraph))
2049 (kill-local-variable 'font-lock-keywords) nil))
2050
2051 (defun org-unfontify-region (beg end &optional maybe_loudly)
2052 "Remove fontification and activation overlays from links."
2053 (font-lock-default-unfontify-region beg end)
2054 (let* ((buffer-undo-list t)
2055 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2056 (inhibit-modification-hooks t)
2057 deactivate-mark buffer-file-name buffer-file-truename)
2058 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2059
2060 ;;; Visibility cycling
2061
2062 (defvar org-cycle-global-status nil)
2063 (defvar org-cycle-subtree-status nil)
2064 (defun org-cycle (&optional arg)
2065 "Visibility cycling for Org-mode.
2066
2067 - When this function is called with a prefix argument, rotate the entire
2068 buffer through 3 states (global cycling)
2069 1. OVERVIEW: Show only top-level headlines.
2070 2. CONTENTS: Show all headlines of all levels, but no body text.
2071 3. SHOW ALL: Show everything.
2072
2073 - When point is at the beginning of a headline, rotate the subtree started
2074 by this line through 3 different states (local cycling)
2075 1. FOLDED: Only the main headline is shown.
2076 2. CHILDREN: The main headline and the direct children are shown. From
2077 this state, you can move to one of the children and
2078 zoom in further.
2079 3. SUBTREE: Show the entire subtree, including body text.
2080
2081 - When there is a numeric prefix, go up to a heading with level ARG, do
2082 a `show-subtree' and return to the previous cursor position. If ARG
2083 is negative, go up that many levels.
2084
2085 - When point is not at the beginning of a headline, execute
2086 `indent-relative', like TAB normally does. See the option
2087 `org-cycle-emulate-tab' for details.
2088
2089 - Special case: if point is the the beginning of the buffer and there is
2090 no headline in line 1, this function will act as if called with prefix arg."
2091 (interactive "P")
2092
2093 (if (or (and (bobp) (not (looking-at outline-regexp)))
2094 (equal arg '(4)))
2095 ;; special case: use global cycling
2096 (setq arg t))
2097
2098 (cond
2099
2100 ((org-at-table-p 'any)
2101 ;; Enter the table or move to the next field in the table
2102 (or (org-table-recognize-table.el)
2103 (progn
2104 (org-table-justify-field-maybe)
2105 (org-table-next-field))))
2106
2107 ((eq arg t) ;; Global cycling
2108
2109 (cond
2110 ((and (eq last-command this-command)
2111 (eq org-cycle-global-status 'overview))
2112 ;; We just created the overview - now do table of contents
2113 ;; This can be slow in very large buffers, so indicate action
2114 (message "CONTENTS...")
2115 (save-excursion
2116 ;; Visit all headings and show their offspring
2117 (goto-char (point-max))
2118 (catch 'exit
2119 (while (and (progn (condition-case nil
2120 (outline-previous-visible-heading 1)
2121 (error (goto-char (point-min))))
2122 t)
2123 (looking-at outline-regexp))
2124 (show-branches)
2125 (if (bobp) (throw 'exit nil))))
2126 (message "CONTENTS...done"))
2127 (setq org-cycle-global-status 'contents)
2128 (run-hook-with-args 'org-cycle-hook 'contents))
2129
2130 ((and (eq last-command this-command)
2131 (eq org-cycle-global-status 'contents))
2132 ;; We just showed the table of contents - now show everything
2133 (show-all)
2134 (message "SHOW ALL")
2135 (setq org-cycle-global-status 'all)
2136 (run-hook-with-args 'org-cycle-hook 'all))
2137
2138 (t
2139 ;; Default action: go to overview
2140 (hide-sublevels 1)
2141 (message "OVERVIEW")
2142 (setq org-cycle-global-status 'overview)
2143 (run-hook-with-args 'org-cycle-hook 'overview))))
2144
2145 ((integerp arg)
2146 ;; Show-subtree, ARG levels up from here.
2147 (save-excursion
2148 (org-back-to-heading)
2149 (outline-up-heading (if (< arg 0) (- arg)
2150 (- (outline-level) arg)))
2151 (org-show-subtree)))
2152
2153 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2154 ;; At a heading: rotate between three different views
2155 (org-back-to-heading)
2156 (let ((goal-column 0) eoh eol eos)
2157 ;; First, some boundaries
2158 (save-excursion
2159 (org-back-to-heading)
2160 (save-excursion
2161 (beginning-of-line 2)
2162 (while (and (not (eobp)) ;; this is like `next-line'
2163 (get-char-property (1- (point)) 'invisible))
2164 (beginning-of-line 2)) (setq eol (point)))
2165 (outline-end-of-heading) (setq eoh (point))
2166 (outline-end-of-subtree) (setq eos (point))
2167 (outline-next-heading))
2168 ;; Find out what to do next and set `this-command'
2169 (cond
2170 ((= eos eoh)
2171 ;; Nothing is hidden behind this heading
2172 (message "EMPTY ENTRY")
2173 (setq org-cycle-subtree-status nil))
2174 ((>= eol eos)
2175 ;; Entire subtree is hidden in one line: open it
2176 (org-show-entry)
2177 (show-children)
2178 (message "CHILDREN")
2179 (setq org-cycle-subtree-status 'children)
2180 (run-hook-with-args 'org-cycle-hook 'children))
2181 ((and (eq last-command this-command)
2182 (eq org-cycle-subtree-status 'children))
2183 ;; We just showed the children, now show everything.
2184 (org-show-subtree)
2185 (message "SUBTREE")
2186 (setq org-cycle-subtree-status 'subtree)
2187 (run-hook-with-args 'org-cycle-hook 'subtree))
2188 (t
2189 ;; Default action: hide the subtree.
2190 (hide-subtree)
2191 (message "FOLDED")
2192 (setq org-cycle-subtree-status 'folded)
2193 (run-hook-with-args 'org-cycle-hook 'folded)))))
2194
2195 ;; TAB emulation
2196 (buffer-read-only (org-back-to-heading))
2197 ((if (and (eq org-cycle-emulate-tab 'white)
2198 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2199 t
2200 (eq org-cycle-emulate-tab t))
2201 (if (and (looking-at "[ \n\r\t]")
2202 (string-match "^[ \t]*$" (buffer-substring
2203 (point-at-bol) (point))))
2204 (progn
2205 (beginning-of-line 1)
2206 (and (looking-at "[ \t]+") (replace-match ""))))
2207 (indent-relative))
2208
2209 (t (save-excursion
2210 (org-back-to-heading)
2211 (org-cycle)))))
2212
2213 (defun org-optimize-window-after-visibility-change (state)
2214 "Adjust the window after a change in outline visibility.
2215 This function is the default value of the hook `org-cycle-hook'."
2216 (cond
2217 ((eq state 'overview) (org-first-headline-recenter 1))
2218 ((eq state 'content) nil)
2219 ((eq state 'all) nil)
2220 ((eq state 'folded) nil)
2221 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2222 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2223
2224 (defun org-subtree-end-visible-p ()
2225 "Is the end of the current subtree visible?"
2226 (pos-visible-in-window-p
2227 (save-excursion (outline-end-of-subtree) (point))))
2228
2229 (defun org-first-headline-recenter (&optional N)
2230 "Move cursor to the first headline and recenter the headline.
2231 Optional argument N means, put the headline into the Nth line of the window."
2232 (goto-char (point-min))
2233 (when (re-search-forward (concat "^" outline-regexp) nil t)
2234 (beginning-of-line)
2235 (recenter (prefix-numeric-value N))))
2236
2237 (defvar org-goto-window-configuration nil)
2238 (defvar org-goto-marker nil)
2239 (defvar org-goto-map (make-sparse-keymap))
2240 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2241 (while (setq cmd (pop cmds))
2242 (substitute-key-definition cmd cmd org-goto-map global-map)))
2243 (define-key org-goto-map "\C-m" 'org-goto-ret)
2244 (define-key org-goto-map [(left)] 'org-goto-left)
2245 (define-key org-goto-map [(right)] 'org-goto-right)
2246 (define-key org-goto-map [(?q)] 'org-goto-quit)
2247 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2248 (define-key org-goto-map "\C-i" 'org-cycle)
2249 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2250 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2251 (define-key org-goto-map "n" 'outline-next-visible-heading)
2252 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2253 (define-key org-goto-map "f" 'outline-forward-same-level)
2254 (define-key org-goto-map "b" 'outline-backward-same-level)
2255 (define-key org-goto-map "u" 'outline-up-heading)
2256 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2257 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2258 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2259 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2260 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2261 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2262 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2263
2264 (defconst org-goto-help
2265 "Select a location to jump to, press RET
2266 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2267
2268 (defun org-goto ()
2269 "Go to a different location of the document, keeping current visibility.
2270
2271 When you want to go to a different location in a document, the fastest way
2272 is often to fold the entire buffer and then dive into the tree. This
2273 method has the disadvantage, that the previous location will be folded,
2274 which may not be what you want.
2275
2276 This command works around this by showing a copy of the current buffer in
2277 overview mode. You can dive into the tree in that copy, to find the
2278 location you want to reach. When pressing RET, the command returns to the
2279 original buffer in which the visibility is still unchanged. It then jumps
2280 to the new location, making it and the headline hierarchy above it visible."
2281 (interactive)
2282 (let* ((org-goto-start-pos (point))
2283 (selected-point
2284 (org-get-location (current-buffer) org-goto-help)))
2285 (if selected-point
2286 (progn
2287 (goto-char selected-point)
2288 (if (org-invisible-p) (org-show-hierarchy-above)))
2289 (error "Quit"))))
2290
2291 (defun org-get-location (buf help)
2292 "Let the user select a location in the Org-mode buffer BUF.
2293 This function uses a recursive edit. It returns the selected position
2294 or nil."
2295 (let (org-selected-point)
2296 (save-excursion
2297 (save-window-excursion
2298 (delete-other-windows)
2299 (switch-to-buffer (get-buffer-create "*org-goto*"))
2300 (with-output-to-temp-buffer "*Help*"
2301 (princ help))
2302 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2303 (setq buffer-read-only nil)
2304 (erase-buffer)
2305 (insert-buffer-substring buf)
2306 (let ((org-startup-truncated t)
2307 (org-startup-folded t)
2308 (org-startup-with-deadline-check nil))
2309 (org-mode))
2310 (setq buffer-read-only t)
2311 (if (boundp 'org-goto-start-pos)
2312 (goto-char org-goto-start-pos)
2313 (goto-char (point-min)))
2314 (org-beginning-of-line)
2315 (message "Select location and press RET")
2316 ;; now we make sure that during selection, ony very few keys work
2317 ;; and that it is impossible to switch to another window.
2318 (let ((gm (current-global-map))
2319 (overriding-local-map org-goto-map))
2320 (unwind-protect
2321 (progn
2322 (use-global-map org-goto-map)
2323 (recursive-edit))
2324 (use-global-map gm)))))
2325 (kill-buffer "*org-goto*")
2326 org-selected-point))
2327
2328 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2329 (defun org-goto-ret (&optional arg)
2330 "Finish org-goto by going to the new location."
2331 (interactive "P")
2332 (setq org-selected-point (point)
2333 current-prefix-arg arg)
2334 (throw 'exit nil))
2335
2336 (defun org-goto-left ()
2337 "Finish org-goto by going to the new location."
2338 (interactive)
2339 (if (org-on-heading-p)
2340 (progn
2341 (beginning-of-line 1)
2342 (setq org-selected-point (point)
2343 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2344 (throw 'exit nil))
2345 (error "Not on a heading")))
2346
2347 (defun org-goto-right ()
2348 "Finish org-goto by going to the new location."
2349 (interactive)
2350 (if (org-on-heading-p)
2351 (progn
2352 (outline-end-of-subtree)
2353 (or (eobp) (forward-char 1))
2354 (setq org-selected-point (point)
2355 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2356 (throw 'exit nil))
2357 (error "Not on a heading")))
2358
2359 (defun org-goto-quit ()
2360 "Finish org-goto without cursor motion."
2361 (interactive)
2362 (setq org-selected-point nil)
2363 (throw 'exit nil))
2364
2365 ;;; Promotion, Demotion, Inserting new headlines
2366
2367 (defvar org-ignore-region nil
2368 "To temporarily disable the active region.")
2369
2370 (defun org-insert-heading ()
2371 "Insert a new heading with same depth at point."
2372 (interactive)
2373 (let* ((head (save-excursion
2374 (condition-case nil
2375 (org-back-to-heading)
2376 (error (outline-next-heading)))
2377 (prog1 (match-string 0)
2378 (funcall outline-level)))))
2379 (unless (bolp) (newline))
2380 (insert head)
2381 (unless (eolp)
2382 (save-excursion (newline-and-indent)))
2383 (unless (equal (char-before) ?\ )
2384 (insert " "))
2385 (run-hooks 'org-insert-heading-hook)))
2386
2387 (defun org-insert-todo-heading (arg)
2388 "Insert a new heading with the same level and TODO state as current heading.
2389 If the heading has no TODO state, or if the state is DONE, use the first
2390 state (TODO by default). Also with prefix arg, force first state."
2391 (interactive "P")
2392 (org-insert-heading)
2393 (save-excursion
2394 (org-back-to-heading)
2395 (outline-previous-heading)
2396 (looking-at org-todo-line-regexp))
2397 (if (or arg
2398 (not (match-beginning 2))
2399 (equal (match-string 2) org-done-string))
2400 (insert (car org-todo-keywords) " ")
2401 (insert (match-string 2) " ")))
2402
2403 (defun org-promote-subtree ()
2404 "Promote the entire subtree.
2405 See also `org-promote'."
2406 (interactive)
2407 (save-excursion
2408 (org-map-tree 'org-promote)))
2409
2410 (defun org-demote-subtree ()
2411 "Demote the entire subtree. See `org-demote'.
2412 See also `org-promote'."
2413 (interactive)
2414 (save-excursion
2415 (org-map-tree 'org-demote)))
2416
2417 (defun org-do-promote ()
2418 "Promote the current heading higher up the tree.
2419 If the region is active in `transient-mark-mode', promote all headings
2420 in the region."
2421 (interactive)
2422 (save-excursion
2423 (if (org-region-active-p)
2424 (org-map-region 'org-promote (region-beginning) (region-end))
2425 (org-promote)))
2426 (org-fix-position-after-promote))
2427
2428 (defun org-do-demote ()
2429 "Demote the current heading lower down the tree.
2430 If the region is active in `transient-mark-mode', demote all headings
2431 in the region."
2432 (interactive)
2433 (save-excursion
2434 (if (org-region-active-p)
2435 (org-map-region 'org-demote (region-beginning) (region-end))
2436 (org-demote)))
2437 (org-fix-position-after-promote))
2438
2439 (defun org-fix-position-after-promote ()
2440 "Make sure that after pro/demotion cursor position is right."
2441 (and (equal (char-after) ?\ )
2442 (equal (char-before) ?*)
2443 (forward-char 1)))
2444
2445 (defun org-promote ()
2446 "Promote the current heading higher up the tree.
2447 If the region is active in `transient-mark-mode', promote all headings
2448 in the region."
2449 (org-back-to-heading t)
2450 (let* ((level (save-match-data (funcall outline-level)))
2451 (up-head (make-string (1- level) ?*)))
2452 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2453 (replace-match up-head nil t)
2454 (if org-adapt-indentation
2455 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2456
2457 (defun org-demote ()
2458 "Demote the current heading lower down the tree.
2459 If the region is active in `transient-mark-mode', demote all headings
2460 in the region."
2461 (org-back-to-heading t)
2462 (let* ((level (save-match-data (funcall outline-level)))
2463 (down-head (make-string (1+ level) ?*)))
2464 (replace-match down-head nil t)
2465 (if org-adapt-indentation
2466 (org-fixup-indentation "^ " " " "^\\S-"))))
2467
2468 (defun org-map-tree (fun)
2469 "Call FUN for every heading underneath the current one."
2470 (org-back-to-heading)
2471 (let ((level (outline-level)))
2472 (save-excursion
2473 (funcall fun)
2474 (while (and (progn
2475 (outline-next-heading)
2476 (> (funcall outline-level) level))
2477 (not (eobp)))
2478 (funcall fun)))))
2479
2480 (defun org-map-region (fun beg end)
2481 "Call FUN for every heading between BEG and END."
2482 (let ((org-ignore-region t))
2483 (save-excursion
2484 (setq end (copy-marker end))
2485 (goto-char beg)
2486 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2487 (< (point) end))
2488 (funcall fun))
2489 (while (and (progn
2490 (outline-next-heading)
2491 (< (point) end))
2492 (not (eobp)))
2493 (funcall fun)))))
2494
2495 (defun org-fixup-indentation (from to prohibit)
2496 "Change the indentation in the current entry by re-replacing FROM with TO.
2497 However, if the regexp PROHIBIT matches at all, don't do anything.
2498 This is being used to change indentation along with the length of the
2499 heading marker. But if there are any lines which are not indented, nothing
2500 is changed at all."
2501 (save-excursion
2502 (let ((end (save-excursion (outline-next-heading)
2503 (point-marker))))
2504 (unless (save-excursion (re-search-forward prohibit end t))
2505 (while (re-search-forward from end t)
2506 (replace-match to)
2507 (beginning-of-line 2)))
2508 (move-marker end nil))))
2509
2510 ;;; Vertical tree motion, cutting and pasting of subtrees
2511
2512 (defun org-move-subtree-up (&optional arg)
2513 "Move the current subtree up past ARG headlines of the same level."
2514 (interactive "p")
2515 (org-move-subtree-down (- (prefix-numeric-value arg))))
2516
2517 (defun org-move-subtree-down (&optional arg)
2518 "Move the current subtree down past ARG headlines of the same level."
2519 (interactive "p")
2520 (setq arg (prefix-numeric-value arg))
2521 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2522 'outline-get-last-sibling))
2523 (ins-point (make-marker))
2524 (cnt (abs arg))
2525 beg end txt folded)
2526 ;; Select the tree
2527 (org-back-to-heading)
2528 (setq beg (point))
2529 (save-match-data
2530 (save-excursion (outline-end-of-heading)
2531 (setq folded (org-invisible-p)))
2532 (outline-end-of-subtree))
2533 (outline-next-heading)
2534 (setq end (point))
2535 ;; Find insertion point, with error handling
2536 (goto-char beg)
2537 (while (> cnt 0)
2538 (or (and (funcall movfunc) (looking-at outline-regexp))
2539 (progn (goto-char beg)
2540 (error "Cannot move past superior level or buffer limit")))
2541 (setq cnt (1- cnt)))
2542 (if (> arg 0)
2543 ;; Moving forward - still need to move over subtree
2544 (progn (outline-end-of-subtree)
2545 (outline-next-heading)
2546 (if (not (or (looking-at (concat "^" outline-regexp))
2547 (bolp)))
2548 (newline))))
2549 (move-marker ins-point (point))
2550 (setq txt (buffer-substring beg end))
2551 (delete-region beg end)
2552 (insert txt)
2553 (goto-char ins-point)
2554 (if folded (hide-subtree))
2555 (move-marker ins-point nil)))
2556
2557 (defvar org-subtree-clip ""
2558 "Clipboard for cut and paste of subtrees.
2559 This is actually only a copy of the kill, because we use the normal kill
2560 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2561
2562 (defvar org-subtree-clip-folded nil
2563 "Was the last copied subtree folded?
2564 This is used to fold the tree back after pasting.")
2565
2566 (defun org-cut-subtree ()
2567 "Cut the current subtree into the clipboard.
2568 This is a short-hand for marking the subtree and then cutting it."
2569 (interactive)
2570 (org-copy-subtree 'cut))
2571
2572 (defun org-copy-subtree (&optional cut)
2573 "Cut the current subtree into the clipboard.
2574 This is a short-hand for marking the subtree and then copying it.
2575 If CUT is non nil, actually cut the subtree."
2576 (interactive)
2577 (let (beg end folded)
2578 (org-back-to-heading)
2579 (setq beg (point))
2580 (save-match-data
2581 (save-excursion (outline-end-of-heading)
2582 (setq folded (org-invisible-p)))
2583 (outline-end-of-subtree))
2584 (if (equal (char-after) ?\n) (forward-char 1))
2585 (setq end (point))
2586 (goto-char beg)
2587 (when (> end beg)
2588 (setq org-subtree-clip-folded folded)
2589 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2590 (setq org-subtree-clip (current-kill 0))
2591 (message "%s: Subtree with %d characters"
2592 (if cut "Cut" "Copied")
2593 (length org-subtree-clip)))))
2594
2595 (defun org-paste-subtree (&optional level tree)
2596 "Paste the clipboard as a subtree, with modification of headline level.
2597 The entire subtree is promoted or demoted in order to match a new headline
2598 level. By default, the new level is derived from the visible headings
2599 before and after the insertion point, and taken to be the inferior headline
2600 level of the two. So if the previous visible heading is level 3 and the
2601 next is level 4 (or vice versa), level 4 will be used for insertion.
2602 This makes sure that the subtree remains an independent subtree and does
2603 not swallow low level entries.
2604
2605 You can also force a different level, either by using a numeric prefix
2606 argument, or by inserting the heading marker by hand. For example, if the
2607 cursor is after \"*****\", then the tree will be shifted to level 5.
2608
2609 If you want to insert the tree as is, just use \\[yank].
2610
2611 If optional TREE is given, use this text instead of the kill ring."
2612 (interactive "P")
2613 (unless (org-kill-is-subtree-p tree)
2614 (error
2615 (substitute-command-keys
2616 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2617 (let* ((txt (or tree (current-kill 0)))
2618 (^re (concat "^\\(" outline-regexp "\\)"))
2619 (re (concat "\\(" outline-regexp "\\)"))
2620 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2621
2622 (old-level (if (string-match ^re txt)
2623 (- (match-end 0) (match-beginning 0))
2624 -1))
2625 (force-level (cond (level (prefix-numeric-value level))
2626 ((string-match
2627 ^re_ (buffer-substring (point-at-bol) (point)))
2628 (- (match-end 0) (match-beginning 0)))
2629 (t nil)))
2630 (previous-level (save-excursion
2631 (condition-case nil
2632 (progn
2633 (outline-previous-visible-heading 1)
2634 (if (looking-at re)
2635 (- (match-end 0) (match-beginning 0))
2636 1))
2637 (error 1))))
2638 (next-level (save-excursion
2639 (condition-case nil
2640 (progn
2641 (outline-next-visible-heading 1)
2642 (if (looking-at re)
2643 (- (match-end 0) (match-beginning 0))
2644 1))
2645 (error 1))))
2646 (new-level (or force-level (max previous-level next-level)))
2647 (shift (if (or (= old-level -1)
2648 (= new-level -1)
2649 (= old-level new-level))
2650 0
2651 (- new-level old-level)))
2652 (shift1 shift)
2653 (delta (if (> shift 0) -1 1))
2654 (func (if (> shift 0) 'org-demote 'org-promote))
2655 beg end)
2656 ;; Remove the forces level indicator
2657 (if force-level
2658 (delete-region (point-at-bol) (point)))
2659 ;; Make sure we start at the beginning of an empty line
2660 (if (not (bolp)) (insert "\n"))
2661 (if (not (looking-at "[ \t]*$"))
2662 (progn (insert "\n") (backward-char 1)))
2663 ;; Paste
2664 (setq beg (point))
2665 (insert txt)
2666 (setq end (point))
2667 (goto-char beg)
2668 ;; Shift if necessary
2669 (if (= shift 0)
2670 (message "Pasted at level %d, without shift" new-level)
2671 (save-restriction
2672 (narrow-to-region beg end)
2673 (while (not (= shift 0))
2674 (org-map-region func (point-min) (point-max))
2675 (setq shift (+ delta shift)))
2676 (goto-char (point-min))
2677 (message "Pasted at level %d, with shift by %d levels"
2678 new-level shift1)))
2679 (if (and (eq org-subtree-clip (current-kill 0))
2680 org-subtree-clip-folded)
2681 ;; The tree was folded before it was killed/copied
2682 (hide-subtree))))
2683
2684 (defun org-kill-is-subtree-p (&optional txt)
2685 "Check if the current kill is an outline subtree, or a set of trees.
2686 Returns nil if kill does not start with a headline, or if the first
2687 headline level is not the largest headline level in the tree.
2688 So this will actually accept several entries of equal levels as well,
2689 which is OK for `org-paste-subtree'.
2690 If optional TXT is given, check this string instead of the current kill."
2691 (let* ((kill (or txt (current-kill 0) ""))
2692 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2693 (- (match-end 0) (match-beginning 0))))
2694 (re (concat "^" outline-regexp))
2695 (start 1))
2696 (if (not start-level)
2697 nil ;; does not even start with a heading
2698 (catch 'exit
2699 (while (setq start (string-match re kill (1+ start)))
2700 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2701 (throw 'exit nil)))
2702 t))))
2703
2704 (defun org-archive-subtree ()
2705 "Move the current subtree to the archive.
2706 The archive can be a certain top-level heading in the current file, or in
2707 a different file. The tree will be moved to that location, the subtree
2708 heading be marked DONE, and the current time will be added."
2709 (interactive)
2710 ;; Save all relevant TODO keyword-relatex variables
2711 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2712 (tr-org-todo-keywords org-todo-keywords)
2713 (tr-org-todo-interpretation org-todo-interpretation)
2714 (tr-org-done-string org-done-string)
2715 (tr-org-todo-regexp org-todo-regexp)
2716 (tr-org-todo-line-regexp org-todo-line-regexp)
2717 (this-buffer (current-buffer))
2718 file heading buffer level newfile-p)
2719 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2720 (progn
2721 (setq file (format (match-string 1 org-archive-location)
2722 (file-name-nondirectory (buffer-file-name)))
2723 heading (match-string 2 org-archive-location)))
2724 (error "Invalid `org-archive-location'"))
2725 (if (> (length file) 0)
2726 (setq newfile-p (not (file-exists-p file))
2727 buffer (find-file-noselect file))
2728 (setq buffer (current-buffer)))
2729 (unless buffer
2730 (error "Cannot access file \"%s\"" file))
2731 (if (and (> (length heading) 0)
2732 (string-match "^\\*+" heading))
2733 (setq level (match-end 0))
2734 (setq heading nil level 0))
2735 (save-excursion
2736 ;; We first only copy, in case something goes wrong
2737 ;; we need to protect this-command, to avoid kill-region sets it,
2738 ;; which would lead to duplication of subtrees
2739 (let (this-command) (org-copy-subtree))
2740 (set-buffer buffer)
2741 ;; Enforce org-mode for the archive buffer
2742 (if (not (eq major-mode 'org-mode))
2743 ;; Force the mode for future visits.
2744 (let ((org-insert-mode-line-in-empty-file t))
2745 (call-interactively 'org-mode)))
2746 (when newfile-p
2747 (goto-char (point-max))
2748 (insert (format "\nArchived entries from file %s\n\n"
2749 (buffer-file-name this-buffer))))
2750 ;; Force the TODO keywords of the original buffer
2751 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2752 (org-todo-keywords tr-org-todo-keywords)
2753 (org-todo-interpretation tr-org-todo-interpretation)
2754 (org-done-string tr-org-done-string)
2755 (org-todo-regexp tr-org-todo-regexp)
2756 (org-todo-line-regexp tr-org-todo-line-regexp))
2757 (goto-char (point-min))
2758 (if heading
2759 (progn
2760 (if (re-search-forward
2761 (concat "\\(^\\|\r\\)"
2762 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2763 nil t)
2764 (goto-char (match-end 0))
2765 ;; Heading not found, just insert it at the end
2766 (goto-char (point-max))
2767 (or (bolp) (insert "\n"))
2768 (insert "\n" heading "\n")
2769 (end-of-line 0))
2770 ;; Make the heading visible, and the following as well
2771 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2772 (if (re-search-forward
2773 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2774 nil t)
2775 (progn (goto-char (match-beginning 0)) (insert "\n")
2776 (beginning-of-line 0))
2777 (goto-char (point-max)) (insert "\n")))
2778 (goto-char (point-max)) (insert "\n"))
2779 ;; Paste
2780 (org-paste-subtree (1+ level))
2781 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2782 (if org-archive-mark-done
2783 (org-todo (length org-todo-keywords)))
2784 ;; Move cursor to right after the TODO keyword
2785 (when org-archive-stamp-time
2786 (beginning-of-line 1)
2787 (looking-at org-todo-line-regexp)
2788 (goto-char (or (match-end 2) (match-beginning 3)))
2789 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2790 (current-time))
2791 ")"))
2792 ;; Save the buffer, if it is not the same buffer.
2793 (if (not (eq this-buffer buffer)) (save-buffer))))
2794 ;; Here we are back in the original buffer. Everything seems to have
2795 ;; worked. So now cut the tree and finish up.
2796 (let (this-command) (org-cut-subtree))
2797 (if (looking-at "[ \t]*$") (kill-line))
2798 (message "Subtree archived %s"
2799 (if (eq this-buffer buffer)
2800 (concat "under heading: " heading)
2801 (concat "in file: " (abbreviate-file-name file))))))
2802
2803 ;;; Completion
2804
2805 (defun org-complete (&optional arg)
2806 "Perform completion on word at point.
2807 At the beginning of a headline, this completes TODO keywords as given in
2808 `org-todo-keywords'.
2809 If the current word is preceded by a backslash, completes the TeX symbols
2810 that are supported for HTML support.
2811 If the current word is preceded by \"#+\", completes special words for
2812 setting file options.
2813 At all other locations, this simply calls `ispell-complete-word'."
2814 (interactive "P")
2815 (catch 'exit
2816 (let* ((end (point))
2817 (beg (save-excursion
2818 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2819 (skip-chars-backward "a-zA-Z0-9_:$")
2820 (point)))
2821 (texp (equal (char-before beg) ?\\))
2822 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2823 beg)
2824 "#+"))
2825 (pattern (buffer-substring-no-properties beg end))
2826 (completion-ignore-case opt)
2827 (type nil)
2828 (table (cond
2829 (opt
2830 (setq type :opt)
2831 (mapcar (lambda (x)
2832 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2833 (cons (match-string 2 x) (match-string 1 x)))
2834 (org-split-string (org-get-current-options) "\n")))
2835 (texp
2836 (setq type :tex)
2837 org-html-entities)
2838 ((string-match "\\`\\*+[ \t]*\\'"
2839 (buffer-substring (point-at-bol) beg))
2840 (setq type :todo)
2841 (mapcar 'list org-todo-keywords))
2842 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2843 (completion (try-completion pattern table)))
2844 (cond ((eq completion t)
2845 (if (equal type :opt)
2846 (insert (substring (cdr (assoc (upcase pattern) table))
2847 (length pattern)))))
2848 ((null completion)
2849 (message "Can't find completion for \"%s\"" pattern)
2850 (ding))
2851 ((not (string= pattern completion))
2852 (delete-region beg end)
2853 (if (string-match " +$" completion)
2854 (setq completion (replace-match "" t t completion)))
2855 (insert completion)
2856 (if (get-buffer-window "*Completions*")
2857 (delete-window (get-buffer-window "*Completions*")))
2858 (if (and (eq type :todo)
2859 (assoc completion table))
2860 (insert " "))
2861 (if (and (equal type :opt) (assoc completion table))
2862 (message "%s" (substitute-command-keys
2863 "Press \\[org-complete] again to insert example settings"))))
2864 (t
2865 (message "Making completion list...")
2866 (let ((list (sort (all-completions pattern table) 'string<)))
2867 (with-output-to-temp-buffer "*Completions*"
2868 (display-completion-list list pattern)))
2869 (message "Making completion list...%s" "done"))))))
2870
2871 ;;; Comments, TODO and DEADLINE
2872
2873 (defun org-toggle-comment ()
2874 "Change the COMMENT state of an entry."
2875 (interactive)
2876 (save-excursion
2877 (org-back-to-heading)
2878 (if (looking-at (concat outline-regexp
2879 "\\( +\\<" org-comment-string "\\>\\)"))
2880 (replace-match "" t t nil 1)
2881 (if (looking-at outline-regexp)
2882 (progn
2883 (goto-char (match-end 0))
2884 (insert " " org-comment-string))))))
2885
2886 (defvar org-last-todo-state-is-todo nil
2887 "This is non-nil when the last TODO state change led to a TODO state.
2888 If the last change removed the TODO tag or switched to DONE, then
2889 this is nil.")
2890
2891 (defun org-todo (&optional arg)
2892 "Change the TODO state of an item.
2893 The state of an item is given by a keyword at the start of the heading,
2894 like
2895 *** TODO Write paper
2896 *** DONE Call mom
2897
2898 The different keywords are specified in the variable `org-todo-keywords'. By
2899 default the available states are \"TODO\" and \"DONE\".
2900 So for this example: when the item starts with TODO, it is changed to DONE.
2901 When it starts with DONE, the DONE is removed. And when neither TODO nor
2902 DONE are present, add TODO at the beginning of the heading.
2903
2904 With prefix arg, use completion to determined the new state. With numeric
2905 prefix arg, switch to that state."
2906 (interactive "P")
2907 (save-excursion
2908 (org-back-to-heading)
2909 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2910 (or (looking-at (concat " +" org-todo-regexp " *"))
2911 (looking-at " *"))
2912 (let* ((this (match-string 1))
2913 (completion-ignore-case t)
2914 (member (member this org-todo-keywords))
2915 (tail (cdr member))
2916 (state (cond
2917 ((equal arg '(4))
2918 ;; Read a state with completion
2919 (completing-read "State: " (mapcar (lambda(x) (list x))
2920 org-todo-keywords)
2921 nil t))
2922 (arg
2923 ;; user requests a specific state
2924 (nth (1- (prefix-numeric-value arg))
2925 org-todo-keywords))
2926 ((null member) (car org-todo-keywords))
2927 ((null tail) nil) ;; -> first entry
2928 ((eq org-todo-interpretation 'sequence)
2929 (car tail))
2930 ((memq org-todo-interpretation '(type priority))
2931 (if (eq this-command last-command)
2932 (car tail)
2933 (if (> (length tail) 0) org-done-string nil)))
2934 (t nil)))
2935 (next (if state (concat " " state " ") " ")))
2936 (replace-match next t t)
2937 (setq org-last-todo-state-is-todo
2938 (not (equal state org-done-string)))
2939 (run-hooks 'org-after-todo-state-change-hook)))
2940 ;; Fixup cursor location if close to the keyword
2941 (if (and (outline-on-heading-p)
2942 (not (bolp))
2943 (save-excursion (beginning-of-line 1)
2944 (looking-at org-todo-line-regexp))
2945 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2946 (progn
2947 (goto-char (or (match-end 2) (match-end 1)))
2948 (just-one-space))))
2949
2950 (defun org-show-todo-tree (arg)
2951 "Make a compact tree which shows all headlines marked with TODO.
2952 The tree will show the lines where the regexp matches, and all higher
2953 headlines above the match."
2954 (interactive "P")
2955 (let ((case-fold-search nil)
2956 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2957 (message "%d TODO entries found"
2958 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2959
2960 (defun org-deadline ()
2961 "Insert the DEADLINE: string to make a deadline.
2962 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2963 to modify it to the correct date."
2964 (interactive)
2965 (insert
2966 org-deadline-string " "
2967 (format-time-string (car org-time-stamp-formats)
2968 (org-read-date nil 'to-time)))
2969 (message "%s" (substitute-command-keys
2970 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2971
2972 (defun org-schedule ()
2973 "Insert the SCHEDULED: string to schedule a TODO item.
2974 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2975 to modify it to the correct date."
2976 (interactive)
2977 (insert
2978 org-scheduled-string " "
2979 (format-time-string (car org-time-stamp-formats)
2980 (org-read-date nil 'to-time)))
2981 (message "%s" (substitute-command-keys
2982 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2983
2984
2985 (defun org-occur (regexp &optional callback)
2986 "Make a compact tree which shows all matches of REGEXP.
2987 The tree will show the lines where the regexp matches, and all higher
2988 headlines above the match. It will also show the heading after the match,
2989 to make sure editing the matching entry is easy.
2990 if CALLBACK is non-nil, it is a function which is called to confirm
2991 that the match should indeed be shown."
2992 (interactive "sRegexp: ")
2993 (setq regexp (org-check-occur-regexp regexp))
2994 (let ((cnt 0))
2995 (save-excursion
2996 (goto-char (point-min))
2997 (hide-sublevels 1)
2998 (while (re-search-forward regexp nil t)
2999 (when (or (not callback)
3000 (funcall callback))
3001 (setq cnt (1+ cnt))
3002 (org-show-hierarchy-above))))
3003 (run-hooks 'org-occur-hook)
3004 (if (interactive-p)
3005 (message "%d match(es) for regexp %s" cnt regexp))
3006 cnt))
3007
3008 (defun org-show-hierarchy-above ()
3009 "Make sure point and the headings hierarchy above is visible."
3010 (if (org-on-heading-p t)
3011 (org-flag-heading nil) ; only show the heading
3012 (org-show-hidden-entry)) ; show entire entry
3013 (save-excursion
3014 (and org-show-following-heading
3015 (outline-next-heading)
3016 (org-flag-heading nil))) ; show the next heading
3017 (save-excursion ; show all higher headings
3018 (while (condition-case nil
3019 (progn (org-up-heading-all 1) t)
3020 (error nil))
3021 (org-flag-heading nil))))
3022
3023 ;;; Priorities
3024
3025 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3026 "Regular expression matching the priority indicator.")
3027
3028 (defvar org-remove-priority-next-time nil)
3029
3030 (defun org-priority-up ()
3031 "Increase the priority of the current item."
3032 (interactive)
3033 (org-priority 'up))
3034
3035 (defun org-priority-down ()
3036 "Decrease the priority of the current item."
3037 (interactive)
3038 (org-priority 'down))
3039
3040 (defun org-priority (&optional action)
3041 "Change the priority of an item by ARG.
3042 ACTION can be set, up, or down."
3043 (interactive)
3044 (setq action (or action 'set))
3045 (let (current new news have remove)
3046 (save-excursion
3047 (org-back-to-heading)
3048 (if (looking-at org-priority-regexp)
3049 (setq current (string-to-char (match-string 2))
3050 have t)
3051 (setq current org-default-priority))
3052 (cond
3053 ((eq action 'set)
3054 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3055 (setq new (read-char-exclusive))
3056 (cond ((equal new ?\ ) (setq remove t))
3057 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3058 (error "Priority must be between `%c' and `%c'"
3059 ?A org-lowest-priority))))
3060 ((eq action 'up)
3061 (setq new (1- current)))
3062 ((eq action 'down)
3063 (setq new (1+ current)))
3064 (t (error "Invalid action")))
3065 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3066 (setq news (format "%c" new))
3067 (if have
3068 (if remove
3069 (replace-match "" t t nil 1)
3070 (replace-match news t t nil 2))
3071 (if remove
3072 (error "No priority cookie found in line")
3073 (looking-at org-todo-line-regexp)
3074 (if (match-end 2)
3075 (progn
3076 (goto-char (match-end 2))
3077 (insert " [#" news "]"))
3078 (goto-char (match-beginning 3))
3079 (insert "[#" news "] ")))))
3080 (if remove
3081 (message "Priority removed")
3082 (message "Priority of current item set to %s" news))))
3083
3084
3085 (defun org-get-priority (s)
3086 "Find priority cookie and return priority."
3087 (save-match-data
3088 (if (not (string-match org-priority-regexp s))
3089 (* 1000 (- org-lowest-priority org-default-priority))
3090 (* 1000 (- org-lowest-priority
3091 (string-to-char (match-string 2 s)))))))
3092
3093 ;;; Timestamps
3094
3095 (defvar org-last-changed-timestamp nil)
3096
3097 (defun org-time-stamp (arg)
3098 "Prompt for a date/time and insert a time stamp.
3099 If the user specifies a time like HH:MM, or if this command is called
3100 with a prefix argument, the time stamp will contain date and time.
3101 Otherwise, only the date will be included. All parts of a date not
3102 specified by the user will be filled in from the current date/time.
3103 So if you press just return without typing anything, the time stamp
3104 will represent the current date/time. If there is already a timestamp
3105 at the cursor, it will be modified."
3106 (interactive "P")
3107 (let ((fmt (if arg (cdr org-time-stamp-formats)
3108 (car org-time-stamp-formats)))
3109 (org-time-was-given nil)
3110 time)
3111 (cond
3112 ((and (org-at-timestamp-p)
3113 (eq last-command 'org-time-stamp)
3114 (eq this-command 'org-time-stamp))
3115 (insert "--")
3116 (setq time (let ((this-command this-command))
3117 (org-read-date arg 'totime)))
3118 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3119 (insert (format-time-string fmt time)))
3120 ((org-at-timestamp-p)
3121 (setq time (let ((this-command this-command))
3122 (org-read-date arg 'totime)))
3123 (and (org-at-timestamp-p) (replace-match
3124 (setq org-last-changed-timestamp
3125 (format-time-string fmt time))
3126 t t))
3127 (message "Timestamp updated"))
3128 (t
3129 (setq time (let ((this-command this-command))
3130 (org-read-date arg 'totime)))
3131 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3132 (insert (format-time-string fmt time))))))
3133
3134 (defun org-time-stamp-inactive (&optional arg)
3135 "Insert an inactive time stamp.
3136 An inactive time stamp is enclosed in square brackets instead of angle
3137 brackets. It is inactive in the sense that it does not trigger agenda entries,
3138 does not link to the calendar and cannot be changed with the S-cursor keys."
3139 (interactive "P")
3140 (let ((fmt (if arg (cdr org-time-stamp-formats)
3141 (car org-time-stamp-formats)))
3142 (org-time-was-given nil)
3143 time)
3144 (setq time (org-read-date arg 'totime))
3145 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3146 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3147 (insert (format-time-string fmt time))))
3148
3149 ;;; FIXME: Make the function take "Fri" as "next friday"
3150 (defun org-read-date (&optional with-time to-time)
3151 "Read a date and make things smooth for the user.
3152 The prompt will suggest to enter an ISO date, but you can also enter anything
3153 which will at least partially be understood by `parse-time-string'.
3154 Unrecognized parts of the date will default to the current day, month ,year,
3155 hour and minute. For example,
3156 3-2-5 --> 2003-02-05
3157 feb 15 --> currentyear-02-15
3158 sep 12 9 --> 2009-09-12
3159 12:45 --> today 12:45
3160 22 sept 0:34 --> currentyear-09-22 0:34
3161 12 --> currentyear-currentmonth-12
3162 etc.
3163 The function understands only English month and weekday abbreviations,
3164 but this can be configured with the variables `parse-time-months' and
3165 `parse-time-weekdays'.
3166
3167 While prompting, a calendar is popped up - you can also select the
3168 date with the mouse (button 1). The calendar shows a period of three
3169 month. To scroll it to other months, use the keys `>' and `<'.
3170 If you don't like the calendar, turn it off with
3171 \(setq org-popup-calendar-for-date-prompt nil).
3172
3173 With optional argument TO-TIME, the date will immediately be converted
3174 to an internal time.
3175 With an optional argument WITH-TIME, the prompt will suggest to also
3176 insert a time. Note that when WITH-TIME is not set, you can still
3177 enter a time, and this function will inform the calling routine about
3178 this change. The calling routine may then choose to change the format
3179 used to insert the time stamp into the buffer to include the time."
3180 (let* ((default-time
3181 ;; Default time is either today, or, when entering a range,
3182 ;; the range start.
3183 (if (save-excursion
3184 (re-search-backward
3185 (concat org-ts-regexp "--\\=")
3186 (- (point) 20) t))
3187 (apply
3188 'encode-time
3189 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3190 (parse-time-string (match-string 1))))
3191 (current-time)))
3192 (timestr (format-time-string
3193 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3194 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3195 ans ans1 ans2
3196 second minute hour day month year tl)
3197
3198 (if org-popup-calendar-for-date-prompt
3199 ;; Also show a calendar for date selection
3200 ;; Copied (with modifications) from planner.el by John Wiegley
3201 (save-excursion
3202 (save-window-excursion
3203 (let ((view-diary-entries-initially nil))
3204 (calendar))
3205 (calendar-forward-day (- (time-to-days default-time)
3206 (calendar-absolute-from-gregorian
3207 (calendar-current-date))))
3208 (let* ((old-map (current-local-map))
3209 (map (copy-keymap calendar-mode-map))
3210 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3211 (define-key map (kbd "RET") 'org-calendar-select)
3212 (define-key map (if org-xemacs-p [button1] [mouse-1])
3213 'org-calendar-select)
3214 (define-key minibuffer-local-map [(meta shift left)]
3215 (lambda () (interactive)
3216 (org-eval-in-calendar '(calendar-backward-month 1))))
3217 (define-key minibuffer-local-map [(meta shift right)]
3218 (lambda () (interactive)
3219 (org-eval-in-calendar '(calendar-forward-month 1))))
3220 (define-key minibuffer-local-map [(shift up)]
3221 (lambda () (interactive)
3222 (org-eval-in-calendar '(calendar-backward-week 1))))
3223 (define-key minibuffer-local-map [(shift down)]
3224 (lambda () (interactive)
3225 (org-eval-in-calendar '(calendar-forward-week 1))))
3226 (define-key minibuffer-local-map [(shift left)]
3227 (lambda () (interactive)
3228 (org-eval-in-calendar '(calendar-backward-day 1))))
3229 (define-key minibuffer-local-map [(shift right)]
3230 (lambda () (interactive)
3231 (org-eval-in-calendar '(calendar-forward-day 1))))
3232 (define-key minibuffer-local-map ">"
3233 (lambda () (interactive)
3234 (org-eval-in-calendar '(scroll-calendar-left 1))))
3235 (define-key minibuffer-local-map "<"
3236 (lambda () (interactive)
3237 (org-eval-in-calendar '(scroll-calendar-right 1))))
3238 (unwind-protect
3239 (progn
3240 (use-local-map map)
3241 (setq ans (read-string prompt "" nil nil))
3242 (setq ans (or ans1 ans2 ans)))
3243 (use-local-map old-map)))))
3244 ;; Naked prompt only
3245 (setq ans (read-string prompt "" nil timestr)))
3246
3247 (if (string-match
3248 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3249 (progn
3250 (setq year (if (match-end 2)
3251 (string-to-number (match-string 2 ans))
3252 (string-to-number (format-time-string "%Y")))
3253 month (string-to-number (match-string 3 ans))
3254 day (string-to-number (match-string 4 ans)))
3255 (if (< year 100) (setq year (+ 2000 year)))
3256 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3257 t t ans))))
3258 (setq tl (parse-time-string ans)
3259 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3260 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3261 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3262 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3263 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3264 second (or (nth 0 tl) 0))
3265 (if (and (boundp 'org-time-was-given)
3266 (nth 2 tl))
3267 (setq org-time-was-given t))
3268 (if (< year 100) (setq year (+ 2000 year)))
3269 (if to-time
3270 (encode-time second minute hour day month year)
3271 (if (or (nth 1 tl) (nth 2 tl))
3272 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3273 (format "%04d-%02d-%02d" year month day)))))
3274
3275 (defun org-eval-in-calendar (form)
3276 "Eval FORM in the calendar window and return to current window.
3277 Also, store the cursor date in variable ans2."
3278 (let ((sw (selected-window)))
3279 (select-window (get-buffer-window "*Calendar*"))
3280 (eval form)
3281 (when (calendar-cursor-to-date)
3282 (let* ((date (calendar-cursor-to-date))
3283 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3284 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3285 (select-window sw)))
3286
3287 (defun org-calendar-select ()
3288 "Return to `org-read-date' with the date currently selected.
3289 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3290 (interactive)
3291 (when (calendar-cursor-to-date)
3292 (let* ((date (calendar-cursor-to-date))
3293 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3294 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3295 (if (active-minibuffer-window) (exit-minibuffer))))
3296
3297 (defun org-check-deadlines (ndays)
3298 "Check if there are any deadlines due or past due.
3299 A deadline is considered due if it happens within `org-deadline-warning-days'
3300 days from today's date. If the deadline appears in an entry marked DONE,
3301 it is not shown. The prefix arg NDAYS can be used to test that many
3302 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3303 (interactive "P")
3304 (let* ((org-warn-days
3305 (cond
3306 ((equal ndays '(4)) 100000)
3307 (ndays (prefix-numeric-value ndays))
3308 (t org-deadline-warning-days)))
3309 (case-fold-search nil)
3310 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3311 (callback
3312 (lambda ()
3313 (and (let ((d1 (time-to-days (current-time)))
3314 (d2 (time-to-days
3315 (org-time-string-to-time (match-string 1)))))
3316 (< (- d2 d1) org-warn-days))
3317 (not (org-entry-is-done-p))))))
3318 (message "%d deadlines past-due or due within %d days"
3319 (org-occur regexp callback)
3320 org-warn-days)))
3321
3322 (defun org-evaluate-time-range (&optional to-buffer)
3323 "Evaluate a time range by computing the difference between start and end.
3324 Normally the result is just printed in the echo area, but with prefix arg
3325 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3326 If the time range is actually in a table, the result is inserted into the
3327 next column.
3328 For time difference computation, a year is assumed to be exactly 365
3329 days in order to avoid rounding problems."
3330 (interactive "P")
3331 (save-excursion
3332 (unless (org-at-date-range-p)
3333 (goto-char (point-at-bol))
3334 (re-search-forward org-tr-regexp (point-at-eol) t))
3335 (if (not (org-at-date-range-p))
3336 (error "Not at a time-stamp range, and none found in current line")))
3337 (let* ((ts1 (match-string 1))
3338 (ts2 (match-string 2))
3339 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3340 (match-end (match-end 0))
3341 (time1 (org-time-string-to-time ts1))
3342 (time2 (org-time-string-to-time ts2))
3343 (t1 (time-to-seconds time1))
3344 (t2 (time-to-seconds time2))
3345 (diff (abs (- t2 t1)))
3346 (negative (< (- t2 t1) 0))
3347 ;; (ys (floor (* 365 24 60 60)))
3348 (ds (* 24 60 60))
3349 (hs (* 60 60))
3350 (fy "%dy %dd %02d:%02d")
3351 (fy1 "%dy %dd")
3352 (fd "%dd %02d:%02d")
3353 (fd1 "%dd")
3354 (fh "%02d:%02d")
3355 y d h m align)
3356 ;; FIXME: Should I re-introduce years, make year refer to same date?
3357 ;; This would be the only useful way to have years, actually.
3358 (if havetime
3359 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3360 y 0
3361 d (floor (/ diff ds)) diff (mod diff ds)
3362 h (floor (/ diff hs)) diff (mod diff hs)
3363 m (floor (/ diff 60)))
3364 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3365 y 0
3366 d (floor (+ (/ diff ds) 0.5))
3367 h 0 m 0))
3368 (if (not to-buffer)
3369 (message (org-make-tdiff-string y d h m))
3370 (when (org-at-table-p)
3371 (goto-char match-end)
3372 (setq align t)
3373 (and (looking-at " *|") (goto-char (match-end 0))))
3374 (if (looking-at
3375 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3376 (replace-match ""))
3377 (if negative (insert " -"))
3378 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3379 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3380 (insert " " (format fh h m))))
3381 (if align (org-table-align))
3382 (message "Time difference inserted"))))
3383
3384 (defun org-make-tdiff-string (y d h m)
3385 (let ((fmt "")
3386 (l nil))
3387 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3388 l (push y l)))
3389 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3390 l (push d l)))
3391 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3392 l (push h l)))
3393 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3394 l (push m l)))
3395 (apply 'format fmt (nreverse l))))
3396
3397 (defun org-time-string-to-time (s)
3398 (apply 'encode-time (org-parse-time-string s)))
3399
3400 (defun org-parse-time-string (s &optional nodefault)
3401 "Parse the standard Org-mode time string.
3402 This should be a lot faster than the normal `parse-time-string'.
3403 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3404 hour and minute fields will be nil if not given."
3405 (if (string-match org-ts-regexp1 s)
3406 (list 0
3407 (if (or (match-beginning 8) (not nodefault))
3408 (string-to-number (or (match-string 8 s) "0")))
3409 (if (or (match-beginning 7) (not nodefault))
3410 (string-to-number (or (match-string 7 s) "0")))
3411 (string-to-number (match-string 4 s))
3412 (string-to-number (match-string 3 s))
3413 (string-to-number (match-string 2 s))
3414 nil nil nil)
3415 (make-list 9 0)))
3416
3417 (defun org-timestamp-up (&optional arg)
3418 "Increase the date item at the cursor by one.
3419 If the cursor is on the year, change the year. If it is on the month or
3420 the day, change that.
3421 With prefix ARG, change by that many units."
3422 (interactive "p")
3423 (org-timestamp-change (prefix-numeric-value arg)))
3424
3425 (defun org-timestamp-down (&optional arg)
3426 "Decrease the date item at the cursor by one.
3427 If the cursor is on the year, change the year. If it is on the month or
3428 the day, change that.
3429 With prefix ARG, change by that many units."
3430 (interactive "p")
3431 (org-timestamp-change (- (prefix-numeric-value arg))))
3432
3433 (defun org-timestamp-up-day (&optional arg)
3434 "Increase the date in the time stamp by one day.
3435 With prefix ARG, change that many days."
3436 (interactive "p")
3437 (org-timestamp-change (prefix-numeric-value arg) 'day))
3438
3439 (defun org-timestamp-down-day (&optional arg)
3440 "Decrease the date in the time stamp by one day.
3441 With prefix ARG, change that many days."
3442 (interactive "p")
3443 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3444
3445 (defsubst org-pos-in-match-range (pos n)
3446 (and (match-beginning n)
3447 (<= (match-beginning n) pos)
3448 (>= (match-end n) pos)))
3449
3450 (defun org-at-timestamp-p ()
3451 "Determine if the cursor is or at a timestamp."
3452 (interactive)
3453 (let* ((tsr org-ts-regexp2)
3454 (pos (point))
3455 (ans (or (looking-at tsr)
3456 (save-excursion
3457 (skip-chars-backward "^<\n\r\t")
3458 (if (> (point) 1) (backward-char 1))
3459 (and (looking-at tsr)
3460 (> (- (match-end 0) pos) -1))))))
3461 (and (boundp 'org-ts-what)
3462 (setq org-ts-what
3463 (cond
3464 ((org-pos-in-match-range pos 2) 'year)
3465 ((org-pos-in-match-range pos 3) 'month)
3466 ((org-pos-in-match-range pos 7) 'hour)
3467 ((org-pos-in-match-range pos 8) 'minute)
3468 ((or (org-pos-in-match-range pos 4)
3469 (org-pos-in-match-range pos 5)) 'day)
3470 (t 'day))))
3471 ans))
3472
3473 (defun org-timestamp-change (n &optional what)
3474 "Change the date in the time stamp at point.
3475 The date will be changed by N times WHAT. WHAT can be `day', `month',
3476 `year', `minute', `second'. If WHAT is not given, the cursor position
3477 in the timestamp determines what will be changed."
3478 (let ((fmt (car org-time-stamp-formats))
3479 org-ts-what
3480 (pos (point))
3481 ts time time0)
3482 (if (not (org-at-timestamp-p))
3483 (error "Not at a timestamp"))
3484 (setq org-ts-what (or what org-ts-what))
3485 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3486 (- (match-end 0) (match-beginning 0))))
3487 1)
3488 (cdr org-time-stamp-formats)
3489 (car org-time-stamp-formats)))
3490 (setq ts (match-string 0))
3491 (replace-match "")
3492 (setq time0 (org-parse-time-string ts))
3493 (setq time
3494 (apply 'encode-time
3495 (append
3496 (list (or (car time0) 0))
3497 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3498 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3499 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3500 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3501 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3502 (nthcdr 6 time0))))
3503 (if (eq what 'calendar)
3504 (let ((cal-date
3505 (save-excursion
3506 (save-match-data
3507 (set-buffer "*Calendar*")
3508 (calendar-cursor-to-date)))))
3509 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3510 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3511 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3512 (setcar time0 (or (car time0) 0))
3513 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3514 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3515 (setq time (apply 'encode-time time0))))
3516 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3517 (goto-char pos)
3518 ;; Try to recenter the calendar window, if any
3519 (if (and org-calendar-follow-timestamp-change
3520 (get-buffer-window "*Calendar*" t)
3521 (memq org-ts-what '(day month year)))
3522 (org-recenter-calendar (time-to-days time)))))
3523
3524 (defun org-recenter-calendar (date)
3525 "If the calendar is visible, recenter it to DATE."
3526 (let* ((win (selected-window))
3527 (cwin (get-buffer-window "*Calendar*" t)))
3528 (when cwin
3529 (select-window cwin)
3530 (calendar-goto-date (if (listp date) date
3531 (calendar-gregorian-from-absolute date)))
3532 (select-window win))))
3533
3534 (defun org-goto-calendar (&optional arg)
3535 "Go to the Emacs calendar at the current date.
3536 If there is a time stamp in the current line, go to that date.
3537 A prefix ARG can be used force the current date."
3538 (interactive "P")
3539 (let ((tsr org-ts-regexp) diff)
3540 (if (or (org-at-timestamp-p)
3541 (save-excursion
3542 (beginning-of-line 1)
3543 (looking-at (concat ".*" tsr))))
3544 (let ((d1 (time-to-days (current-time)))
3545 (d2 (time-to-days
3546 (org-time-string-to-time (match-string 1)))))
3547 (setq diff (- d2 d1))))
3548 (let ((view-diary-entries-initially nil))
3549 (calendar))
3550 (calendar-goto-today)
3551 (if (and diff (not arg)) (calendar-forward-day diff))))
3552
3553 (defun org-date-from-calendar ()
3554 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3555 If there is already a time stamp at the cursor position, update it."
3556 (interactive)
3557 (org-timestamp-change 0 'calendar))
3558
3559 ;;; Agenda, and Diary Integration
3560
3561 ;;; Define the mode
3562
3563 (defvar org-agenda-mode-map (make-sparse-keymap)
3564 "Keymap for `org-agenda-mode'.")
3565
3566 (defvar org-agenda-menu)
3567 (defvar org-agenda-follow-mode nil)
3568 (defvar org-agenda-buffer-name "*Org Agenda*")
3569 (defvar org-agenda-redo-command nil)
3570 (defvar org-agenda-mode-hook nil)
3571
3572 ;;;###autoload
3573 (defun org-agenda-mode ()
3574 "Mode for time-sorted view on action items in Org-mode files.
3575
3576 The following commands are available:
3577
3578 \\{org-agenda-mode-map}"
3579 (interactive)
3580 (kill-all-local-variables)
3581 (setq major-mode 'org-agenda-mode)
3582 (setq mode-name "Org-Agenda")
3583 (use-local-map org-agenda-mode-map)
3584 (easy-menu-add org-agenda-menu)
3585 (if org-startup-truncated (setq truncate-lines t))
3586 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3587 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3588 (setq org-agenda-follow-mode nil)
3589 (easy-menu-change
3590 '("Agenda") "Agenda Files"
3591 (append
3592 (list
3593 ["Edit File List" (customize-variable 'org-agenda-files) t]
3594 "--")
3595 (mapcar 'org-file-menu-entry org-agenda-files)))
3596 (org-agenda-set-mode-name)
3597 (apply
3598 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3599 org-agenda-mode-hook))
3600
3601 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3602 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3603 (define-key org-agenda-mode-map " " 'org-agenda-show)
3604 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3605 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3606 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3607 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3608 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3609 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3610 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3611 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3612 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3613 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
3614 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
3615
3616 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3617 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3618 (while l (define-key org-agenda-mode-map
3619 (int-to-string (pop l)) 'digit-argument)))
3620
3621 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3622 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3623 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3624 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3625 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3626 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3627 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3628 (define-key org-agenda-mode-map "n" 'next-line)
3629 (define-key org-agenda-mode-map "p" 'previous-line)
3630 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3631 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3632 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3633 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3634 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3635 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3636 (eval-after-load "calendar"
3637 '(define-key calendar-mode-map org-calendar-to-agenda-key
3638 'org-calendar-goto-agenda))
3639 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3640 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3641 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3642 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3643 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3644 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3645 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3646 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3647 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3648 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3649 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3650 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
3651 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
3652 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3653 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3654 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
3655 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3656 "Local keymap for agenda entries from Org-mode.")
3657
3658 (define-key org-agenda-keymap
3659 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3660 (define-key org-agenda-keymap
3661 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3662
3663 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3664 '("Agenda"
3665 ("Agenda Files")
3666 "--"
3667 ["Show" org-agenda-show t]
3668 ["Go To (other window)" org-agenda-goto t]
3669 ["Go To (one window)" org-agenda-switch-to t]
3670 ["Follow Mode" org-agenda-follow-mode
3671 :style toggle :selected org-agenda-follow-mode :active t]
3672 "--"
3673 ["Cycle TODO" org-agenda-todo t]
3674 ("Reschedule"
3675 ["Reschedule +1 day" org-agenda-date-later t]
3676 ["Reschedule -1 day" org-agenda-date-earlier t]
3677 "--"
3678 ["Reschedule to ..." org-agenda-date-prompt t])
3679 ("Priority"
3680 ["Set Priority" org-agenda-priority t]
3681 ["Increase Priority" org-agenda-priority-up t]
3682 ["Decrease Priority" org-agenda-priority-down t]
3683 ["Show Priority" org-agenda-show-priority t])
3684 "--"
3685 ["Rebuild buffer" org-agenda-redo t]
3686 ["Goto Today" org-agenda-goto-today t]
3687 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3688 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3689 "--"
3690 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3691 :style radio :selected (equal org-agenda-ndays 1)]
3692 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3693 :style radio :selected (equal org-agenda-ndays 7)]
3694 "--"
3695 ["Include Diary" org-agenda-toggle-diary
3696 :style toggle :selected org-agenda-include-diary :active t]
3697 ["Use Time Grid" org-agenda-toggle-time-grid
3698 :style toggle :selected org-agenda-use-time-grid :active t]
3699 "--"
3700 ["New Diary Entry" org-agenda-diary-entry t]
3701 ("Calendar Commands"
3702 ["Goto Calendar" org-agenda-goto-calendar t]
3703 ["Phases of the Moon" org-agenda-phases-of-moon t]
3704 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3705 ["Holidays" org-agenda-holidays t]
3706 ["Convert" org-agenda-convert-date t])
3707 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
3708 "--"
3709 ["Quit" org-agenda-quit t]
3710 ["Exit and Release Buffers" org-agenda-exit t]
3711 ))
3712
3713 (defvar org-agenda-markers nil
3714 "List of all currently active markers created by `org-agenda'.")
3715 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3716 "Creation time of the last agenda marker.")
3717
3718 (defun org-agenda-new-marker (&optional pos)
3719 "Return a new agenda marker.
3720 Org-mode keeps a list of these markers and resets them when they are
3721 no longer in use."
3722 (let ((m (copy-marker (or pos (point)))))
3723 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3724 (push m org-agenda-markers)
3725 m))
3726
3727 (defun org-agenda-maybe-reset-markers (&optional force)
3728 "Reset markers created by `org-agenda'. But only if they are old enough."
3729 (if (or force
3730 (> (- (time-to-seconds (current-time))
3731 org-agenda-last-marker-time)
3732 5))
3733 (while org-agenda-markers
3734 (move-marker (pop org-agenda-markers) nil))))
3735
3736 (defvar org-agenda-new-buffers nil
3737 "Buffers created to visit agenda files.")
3738
3739 (defun org-get-agenda-file-buffer (file)
3740 "Get a buffer visiting FILE. If the buffer needs to be created, add
3741 it to the list of buffers which might be released later."
3742 (let ((buf (find-buffer-visiting file)))
3743 (if buf
3744 buf ; just return it
3745 ;; Make a new buffer and remember it
3746 (setq buf (find-file-noselect file))
3747 (if buf (push buf org-agenda-new-buffers))
3748 buf)))
3749
3750 (defun org-release-buffers (blist)
3751 "Release all buffers in list, asking the user for confirmation when needed.
3752 When a buffer is unmodified, it is just killed. When modified, it is saved
3753 \(if the user agrees) and then killed."
3754 (let (buf file)
3755 (while (setq buf (pop blist))
3756 (setq file (buffer-file-name buf))
3757 (when (and (buffer-modified-p buf)
3758 file
3759 (y-or-n-p (format "Save file %s? " file)))
3760 (with-current-buffer buf (save-buffer)))
3761 (kill-buffer buf))))
3762
3763 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3764
3765 (defun org-timeline (&optional include-all)
3766 "Show a time-sorted view of the entries in the current org file.
3767 Only entries with a time stamp of today or later will be listed. With
3768 one \\[universal-argument] prefix argument, past entries will also be listed.
3769 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3770 under the current date.
3771 If the buffer contains an active region, only check the region for
3772 dates."
3773 (interactive "P")
3774 (require 'calendar)
3775 (org-agenda-maybe-reset-markers 'force)
3776 (org-compile-prefix-format org-timeline-prefix-format)
3777 (let* ((dopast include-all)
3778 (dotodo (equal include-all '(16)))
3779 (entry (buffer-file-name))
3780 (org-agenda-files (list (buffer-file-name)))
3781 (date (calendar-current-date))
3782 (win (selected-window))
3783 (pos1 (point))
3784 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3785 (end (if (org-region-active-p) (region-end) (point-max)))
3786 (day-numbers (org-get-all-dates beg end 'no-ranges
3787 t)) ; always include today
3788 (today (time-to-days (current-time)))
3789 (org-respect-restriction t)
3790 (past t)
3791 s e rtn d)
3792 (setq org-agenda-redo-command
3793 (list 'progn
3794 (list 'switch-to-buffer-other-window (current-buffer))
3795 (list 'org-timeline (list 'quote include-all))))
3796 (if (not dopast)
3797 ;; Remove past dates from the list of dates.
3798 (setq day-numbers (delq nil (mapcar (lambda(x)
3799 (if (>= x today) x nil))
3800 day-numbers))))
3801 (switch-to-buffer-other-window
3802 (get-buffer-create org-agenda-buffer-name))
3803 (setq buffer-read-only nil)
3804 (erase-buffer)
3805 (org-agenda-mode) (setq buffer-read-only nil)
3806 (while (setq d (pop day-numbers))
3807 (if (and (>= d today)
3808 dopast
3809 past)
3810 (progn
3811 (setq past nil)
3812 (insert (make-string 79 ?-) "\n")))
3813 (setq date (calendar-gregorian-from-absolute d))
3814 (setq s (point))
3815 (if dotodo
3816 (setq rtn (org-agenda-get-day-entries
3817 entry date :todo :timestamp))
3818 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3819 (if (or rtn (equal d today))
3820 (progn
3821 (insert (calendar-day-name date) " "
3822 (number-to-string (extract-calendar-day date)) " "
3823 (calendar-month-name (extract-calendar-month date)) " "
3824 (number-to-string (extract-calendar-year date)) "\n")
3825 (put-text-property s (1- (point)) 'face
3826 'org-link)
3827 (if (equal d today)
3828 (put-text-property s (1- (point)) 'org-today t))
3829 (insert (org-finalize-agenda-entries rtn) "\n")
3830 (put-text-property s (1- (point)) 'day d))))
3831 (goto-char (point-min))
3832 (setq buffer-read-only t)
3833 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3834 (point-min)))
3835 (when (not org-select-timeline-window)
3836 (select-window win)
3837 (goto-char pos1))))
3838
3839 ;;;###autoload
3840 (defun org-agenda (&optional include-all start-day ndays)
3841 "Produce a weekly view from all files in variable `org-agenda-files'.
3842 The view will be for the current week, but from the overview buffer you
3843 will be able to go to other weeks.
3844 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3845 also be shown, under the current date.
3846 START-DAY defaults to TODAY, or to the most recent match for the weekday
3847 given in `org-agenda-start-on-weekday'.
3848 NDAYS defaults to `org-agenda-ndays'."
3849 (interactive "P")
3850 (org-agenda-maybe-reset-markers 'force)
3851 (org-compile-prefix-format org-agenda-prefix-format)
3852 (require 'calendar)
3853 (let* ((org-agenda-start-on-weekday
3854 (if (or (equal ndays 1)
3855 (and (null ndays) (equal 1 org-agenda-ndays)))
3856 nil org-agenda-start-on-weekday))
3857 (files (copy-sequence org-agenda-files))
3858 (win (selected-window))
3859 (today (time-to-days (current-time)))
3860 (sd (or start-day today))
3861 (start (if (or (null org-agenda-start-on-weekday)
3862 (< org-agenda-ndays 7))
3863 sd
3864 (let* ((nt (calendar-day-of-week
3865 (calendar-gregorian-from-absolute sd)))
3866 (n1 org-agenda-start-on-weekday)
3867 (d (- nt n1)))
3868 (- sd (+ (if (< d 0) 7 0) d)))))
3869 (day-numbers (list start))
3870 (inhibit-redisplay t)
3871 s e rtn rtnall file date d start-pos end-pos todayp nd)
3872 (setq org-agenda-redo-command
3873 (list 'org-agenda (list 'quote include-all) start-day ndays))
3874 ;; Make the list of days
3875 (setq ndays (or ndays org-agenda-ndays)
3876 nd ndays)
3877 (while (> ndays 1)
3878 (push (1+ (car day-numbers)) day-numbers)
3879 (setq ndays (1- ndays)))
3880 (setq day-numbers (nreverse day-numbers))
3881 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3882 (progn
3883 (delete-other-windows)
3884 (switch-to-buffer-other-window
3885 (get-buffer-create org-agenda-buffer-name))))
3886 (setq buffer-read-only nil)
3887 (erase-buffer)
3888 (org-agenda-mode) (setq buffer-read-only nil)
3889 (set (make-local-variable 'starting-day) (car day-numbers))
3890 (set (make-local-variable 'include-all-loc) include-all)
3891 (when (and (or include-all org-agenda-include-all-todo)
3892 (member today day-numbers))
3893 (setq files org-agenda-files
3894 rtnall nil)
3895 (while (setq file (pop files))
3896 (catch 'nextfile
3897 (org-check-agenda-file file)
3898 (setq date (calendar-gregorian-from-absolute today)
3899 rtn (org-agenda-get-day-entries
3900 file date :todo))
3901 (setq rtnall (append rtnall rtn))))
3902 (when rtnall
3903 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3904 (add-text-properties (point-min) (1- (point))
3905 (list 'face 'org-link))
3906 (insert (org-finalize-agenda-entries rtnall) "\n")))
3907 (while (setq d (pop day-numbers))
3908 (setq date (calendar-gregorian-from-absolute d)
3909 s (point))
3910 (if (or (setq todayp (= d today))
3911 (and (not start-pos) (= d sd)))
3912 (setq start-pos (point))
3913 (if (and start-pos (not end-pos))
3914 (setq end-pos (point))))
3915 (setq files org-agenda-files
3916 rtnall nil)
3917 (while (setq file (pop files))
3918 (catch 'nextfile
3919 (org-check-agenda-file file)
3920 (setq rtn (org-agenda-get-day-entries file date))
3921 (setq rtnall (append rtnall rtn))))
3922 (if org-agenda-include-diary
3923 (progn
3924 (require 'diary-lib)
3925 (setq rtn (org-get-entries-from-diary date))
3926 (setq rtnall (append rtnall rtn))))
3927 (if (or rtnall org-agenda-show-all-dates)
3928 (progn
3929 (insert (format "%-9s %2d %s %4d\n"
3930 (calendar-day-name date)
3931 (extract-calendar-day date)
3932 (calendar-month-name (extract-calendar-month date))
3933 (extract-calendar-year date)))
3934 (put-text-property s (1- (point)) 'face
3935 'org-link)
3936 (if rtnall (insert
3937 (org-finalize-agenda-entries ;; FIXME: condition needed
3938 (org-agenda-add-time-grid-maybe
3939 rtnall nd todayp))
3940 "\n"))
3941 (put-text-property s (1- (point)) 'day d))))
3942 (goto-char (point-min))
3943 (setq buffer-read-only t)
3944 (if org-fit-agenda-window
3945 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3946 (/ (frame-height) 2)))
3947 (unless (and (pos-visible-in-window-p (point-min))
3948 (pos-visible-in-window-p (point-max)))
3949 (goto-char (1- (point-max)))
3950 (recenter -1)
3951 (if (not (pos-visible-in-window-p (or start-pos 1)))
3952 (progn
3953 (goto-char (or start-pos 1))
3954 (recenter 1))))
3955 (goto-char (or start-pos 1))
3956 (if (not org-select-agenda-window) (select-window win))
3957 (message "")))
3958
3959 (defun org-check-agenda-file (file)
3960 "Make sure FILE exists. If not, ask user what to do."
3961 ;; FIXME: this does not correctly change the menus
3962 ;; Could probably be fixed by explicitly going to the buffer.
3963 (when (not (file-exists-p file))
3964 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3965 file)
3966 (let ((r (downcase (read-char-exclusive))))
3967 (cond
3968 ((equal r ?r)
3969 (org-remove-file file)
3970 (throw 'nextfile t))
3971 (t (error "Abort"))))))
3972
3973 (defun org-agenda-quit ()
3974 "Exit agenda by removing the window or the buffer."
3975 (interactive)
3976 (let ((buf (current-buffer)))
3977 (if (not (one-window-p)) (delete-window))
3978 (kill-buffer buf)
3979 (org-agenda-maybe-reset-markers 'force)))
3980
3981 (defun org-agenda-exit ()
3982 "Exit agenda by removing the window or the buffer.
3983 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3984 Org-mode buffers visited directly by the user will not be touched."
3985 (interactive)
3986 (org-release-buffers org-agenda-new-buffers)
3987 (setq org-agenda-new-buffers nil)
3988 (org-agenda-quit))
3989
3990 (defun org-agenda-redo ()
3991 "Rebuild Agenda."
3992 (interactive)
3993 (eval org-agenda-redo-command))
3994
3995 (defun org-agenda-goto-today ()
3996 "Go to today."
3997 (interactive)
3998 (if (boundp 'starting-day)
3999 (let ((cmd (car org-agenda-redo-command))
4000 (iall (nth 1 org-agenda-redo-command))
4001 (nday (nth 3 org-agenda-redo-command)))
4002 (eval (list cmd iall nil nday)))
4003 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4004 (point-min)))))
4005
4006 (defun org-agenda-later (arg)
4007 "Go forward in time by `org-agenda-ndays' days.
4008 With prefix ARG, go forward that many times `org-agenda-ndays'."
4009 (interactive "p")
4010 (unless (boundp 'starting-day)
4011 (error "Not allowed"))
4012 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4013 (+ starting-day (* arg org-agenda-ndays))))
4014
4015 (defun org-agenda-earlier (arg)
4016 "Go back in time by `org-agenda-ndays' days.
4017 With prefix ARG, go back that many times `org-agenda-ndays'."
4018 (interactive "p")
4019 (unless (boundp 'starting-day)
4020 (error "Not allowed"))
4021 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4022 (- starting-day (* arg org-agenda-ndays))))
4023
4024 (defun org-agenda-week-view ()
4025 "Switch to weekly view for agenda."
4026 (interactive)
4027 (unless (boundp 'starting-day)
4028 (error "Not allowed"))
4029 (setq org-agenda-ndays 7)
4030 (org-agenda include-all-loc
4031 (or (get-text-property (point) 'day)
4032 starting-day))
4033 (org-agenda-set-mode-name)
4034 (message "Switched to week view"))
4035
4036 (defun org-agenda-day-view ()
4037 "Switch to weekly view for agenda."
4038 (interactive)
4039 (unless (boundp 'starting-day)
4040 (error "Not allowed"))
4041 (setq org-agenda-ndays 1)
4042 (org-agenda include-all-loc
4043 (or (get-text-property (point) 'day)
4044 starting-day))
4045 (org-agenda-set-mode-name)
4046 (message "Switched to day view"))
4047
4048 (defun org-agenda-next-date-line (&optional arg)
4049 "Jump to the next line indicating a date in agenda buffer."
4050 (interactive "p")
4051 (beginning-of-line 1)
4052 (if (looking-at "^\\S-") (forward-char 1))
4053 (if (not (re-search-forward "^\\S-" nil t arg))
4054 (progn
4055 (backward-char 1)
4056 (error "No next date after this line in this buffer")))
4057 (goto-char (match-beginning 0)))
4058
4059 (defun org-agenda-previous-date-line (&optional arg)
4060 "Jump to the next line indicating a date in agenda buffer."
4061 (interactive "p")
4062 (beginning-of-line 1)
4063 (if (not (re-search-backward "^\\S-" nil t arg))
4064 (error "No previous date before this line in this buffer")))
4065
4066 ;; Initialize the highlight
4067 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4068 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4069 'face 'highlight)
4070
4071 (defun org-highlight (begin end &optional buffer)
4072 "Highlight a region with overlay."
4073 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4074 org-hl begin end (or buffer (current-buffer))))
4075
4076 (defun org-unhighlight ()
4077 "Detach overlay INDEX."
4078 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4079
4080
4081 (defun org-agenda-follow-mode ()
4082 "Toggle follow mode in an agenda buffer."
4083 (interactive)
4084 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4085 (org-agenda-set-mode-name)
4086 (message "Follow mode is %s"
4087 (if org-agenda-follow-mode "on" "off")))
4088
4089 (defun org-agenda-toggle-diary ()
4090 "Toggle follow mode in an agenda buffer."
4091 (interactive)
4092 (setq org-agenda-include-diary (not org-agenda-include-diary))
4093 (org-agenda-redo)
4094 (org-agenda-set-mode-name)
4095 (message "Diary inclusion turned %s"
4096 (if org-agenda-include-diary "on" "off")))
4097
4098 (defun org-agenda-toggle-time-grid ()
4099 "Toggle follow mode in an agenda buffer."
4100 (interactive)
4101 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4102 (org-agenda-redo)
4103 (org-agenda-set-mode-name)
4104 (message "Time-grid turned %s"
4105 (if org-agenda-use-time-grid "on" "off")))
4106
4107 (defun org-agenda-set-mode-name ()
4108 "Set the mode name to indicate all the small mode settings."
4109 (setq mode-name
4110 (concat "Org-Agenda"
4111 (if (equal org-agenda-ndays 1) " Day" "")
4112 (if (equal org-agenda-ndays 7) " Week" "")
4113 (if org-agenda-follow-mode " Follow" "")
4114 (if org-agenda-include-diary " Diary" "")
4115 (if org-agenda-use-time-grid " Grid" "")))
4116 (force-mode-line-update))
4117
4118 (defun org-agenda-post-command-hook ()
4119 (and (eolp) (not (bolp)) (backward-char 1))
4120 (if (and org-agenda-follow-mode
4121 (get-text-property (point) 'org-marker))
4122 (org-agenda-show)))
4123
4124 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4125
4126 (defun org-get-entries-from-diary (date)
4127 "Get the (Emacs Calendar) diary entries for DATE."
4128 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4129 (diary-display-hook '(fancy-diary-display))
4130 (list-diary-entries-hook
4131 (cons 'org-diary-default-entry list-diary-entries-hook))
4132 (diary-file-name-prefix-function nil) ; turn this feature off
4133 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4134 entries
4135 (org-disable-agenda-to-diary t))
4136 (save-excursion
4137 (save-window-excursion
4138 (list-diary-entries date 1)))
4139 (if (not (get-buffer fancy-diary-buffer))
4140 (setq entries nil)
4141 (with-current-buffer fancy-diary-buffer
4142 (setq buffer-read-only nil)
4143 (if (= (point-max) 1)
4144 ;; No entries
4145 (setq entries nil)
4146 ;; Omit the date and other unnecessary stuff
4147 (org-agenda-cleanup-fancy-diary)
4148 ;; Add prefix to each line and extend the text properties
4149 (if (= (point-max) 1)
4150 (setq entries nil)
4151 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4152 (set-buffer-modified-p nil)
4153 (kill-buffer fancy-diary-buffer)))
4154 (when entries
4155 (setq entries (org-split-string entries "\n"))
4156 (setq entries
4157 (mapcar
4158 (lambda (x)
4159 (setq x (org-format-agenda-item "" x "Diary" 'time))
4160 ;; Extend the text properties to the beginning of the line
4161 (add-text-properties
4162 0 (length x)
4163 (text-properties-at (1- (length x)) x)
4164 x)
4165 x)
4166 entries)))))
4167
4168 (defun org-agenda-cleanup-fancy-diary ()
4169 "Remove unwanted stuff in buffer created by fancy-diary-display.
4170 This gets rid of the date, the underline under the date, and
4171 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4172 date. Itt also removes lines that contain only whitespace."
4173 (goto-char (point-min))
4174 (if (looking-at ".*?:[ \t]*")
4175 (progn
4176 (replace-match "")
4177 (re-search-forward "\n=+$" nil t)
4178 (replace-match "")
4179 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4180 (re-search-forward "\n=+$" nil t)
4181 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4182 (goto-char (point-min))
4183 (while (re-search-forward "^ +\n" nil t)
4184 (replace-match ""))
4185 (goto-char (point-min))
4186 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4187 (replace-match "")))
4188
4189 ;; Make sure entries from the diary have the right text properties.
4190 (eval-after-load "diary-lib"
4191 '(if (boundp 'diary-modify-entry-list-string-function)
4192 ;; We can rely on the hook, nothing to do
4193 nil
4194 ;; Hook not avaiable, must use advice to make this work
4195 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4196 "Make the position visible."
4197 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4198 (stringp string)
4199 (buffer-file-name))
4200 (setq string (org-modify-diary-entry-string string))))))
4201
4202 (defun org-modify-diary-entry-string (string)
4203 "Add text properties to string, allowing org-mode to act on it."
4204 (add-text-properties
4205 0 (length string)
4206 (list 'mouse-face 'highlight
4207 'keymap org-agenda-keymap
4208 'help-echo
4209 (format
4210 "mouse-2 or RET jump to diary file %s"
4211 (abbreviate-file-name (buffer-file-name)))
4212 'org-agenda-diary-link t
4213 'org-marker (org-agenda-new-marker (point-at-bol)))
4214 string)
4215 string)
4216
4217 (defun org-diary-default-entry ()
4218 "Add a dummy entry to the diary.
4219 Needed to avoid empty dates which mess up holiday display."
4220 ;; Catch the error if dealing with the new add-to-diary-alist
4221 (when org-disable-agenda-to-diary
4222 (condition-case nil
4223 (add-to-diary-list original-date "Org-mode dummy" "")
4224 (error
4225 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4226
4227 (defun org-add-file (&optional file)
4228 "Add current file to the list of files in variable `org-agenda-files'.
4229 These are the files which are being checked for agenda entries.
4230 Optional argument FILE means, use this file instead of the current.
4231 It is possible (but not recommended) to add this function to the
4232 `org-mode-hook'."
4233 (interactive)
4234 (catch 'exit
4235 (let* ((file (or file (buffer-file-name)
4236 (if (interactive-p)
4237 (error "Buffer is not visiting a file")
4238 (throw 'exit nil))))
4239 (true-file (file-truename file))
4240 (afile (abbreviate-file-name file))
4241 (present (delq nil (mapcar
4242 (lambda (x)
4243 (equal true-file (file-truename x)))
4244 org-agenda-files))))
4245 (if (not present)
4246 (progn
4247 (setq org-agenda-files
4248 (cons afile org-agenda-files))
4249 ;; Make sure custom.el does not end up with Org-mode
4250 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4251 (customize-save-variable 'org-agenda-files org-agenda-files))
4252 (org-install-agenda-files-menu)
4253 (message "Added file: %s" afile))
4254 (message "File was already in list: %s" afile)))))
4255
4256 (defun org-remove-file (&optional file)
4257 "Remove current file from the list of files in variable `org-agenda-files'.
4258 These are the files which are being checked for agenda entries.
4259 Optional argument FILE means, use this file instead of the current."
4260 (interactive)
4261 (let* ((file (or file (buffer-file-name)))
4262 (true-file (file-truename file))
4263 (afile (abbreviate-file-name file))
4264 (files (delq nil (mapcar
4265 (lambda (x)
4266 (if (equal true-file
4267 (file-truename x))
4268 nil x))
4269 org-agenda-files))))
4270 (if (not (= (length files) (length org-agenda-files)))
4271 (progn
4272 (setq org-agenda-files files)
4273 (customize-save-variable 'org-agenda-files org-agenda-files)
4274 (org-install-agenda-files-menu)
4275 (message "Removed file: %s" afile))
4276 (message "File was not in list: %s" afile))))
4277
4278 (defun org-file-menu-entry (file)
4279 (vector file (list 'find-file file) t))
4280 ;; FIXME: Maybe removed a buffer visited through the menu from
4281 ;; org-agenda-new-buffers, so that the buffer will not be removed
4282 ;; when exiting the agenda????
4283
4284 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4285 "Return a list of all relevant day numbers from BEG to END buffer positions.
4286 If NO-RANGES is non-nil, include only the start and end dates of a range,
4287 not every single day in the range. If FORCE-TODAY is non-nil, make
4288 sure that TODAY is included in the list."
4289 (let (dates date day day1 day2 ts1 ts2)
4290 (if force-today
4291 (setq dates (list (time-to-days (current-time)))))
4292 (save-excursion
4293 (goto-char beg)
4294 (while (re-search-forward org-ts-regexp end t)
4295 (setq day (time-to-days (org-time-string-to-time
4296 (substring (match-string 1) 0 10))))
4297 (or (memq day dates) (push day dates)))
4298 (unless no-ranges
4299 (goto-char beg)
4300 (while (re-search-forward org-tr-regexp end t)
4301 (setq ts1 (substring (match-string 1) 0 10)
4302 ts2 (substring (match-string 2) 0 10)
4303 day1 (time-to-days (org-time-string-to-time ts1))
4304 day2 (time-to-days (org-time-string-to-time ts2)))
4305 (while (< (setq day1 (1+ day1)) day2)
4306 (or (memq day1 dates) (push day1 dates)))))
4307 (sort dates '<))))
4308
4309 ;;;###autoload
4310 (defun org-diary (&rest args)
4311 "Return diary information from org-files.
4312 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4313 It accesses org files and extracts information from those files to be
4314 listed in the diary. The function accepts arguments specifying what
4315 items should be listed. The following arguments are allowed:
4316
4317 :timestamp List the headlines of items containing a date stamp or
4318 date range matching the selected date. Deadlines will
4319 also be listed, on the expiration day.
4320
4321 :deadline List any deadlines past due, or due within
4322 `org-deadline-warning-days'. The listing occurs only
4323 in the diary for *today*, not at any other date. If
4324 an entry is marked DONE, it is no longer listed.
4325
4326 :scheduled List all items which are scheduled for the given date.
4327 The diary for *today* also contains items which were
4328 scheduled earlier and are not yet marked DONE.
4329
4330 :todo List all TODO items from the org-file. This may be a
4331 long list - so this is not turned on by default.
4332 Like deadlines, these entries only show up in the
4333 diary for *today*, not at any other date.
4334
4335 The call in the diary file should look like this:
4336
4337 &%%(org-diary) ~/path/to/some/orgfile.org
4338
4339 Use a separate line for each org file to check. Or, if you omit the file name,
4340 all files listed in `org-agenda-files' will be checked automatically:
4341
4342 &%%(org-diary)
4343
4344 If you don't give any arguments (as in the example above), the default
4345 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4346 also be written as
4347
4348 &%%(org-diary :deadline :timestamp :scheduled)
4349
4350 The function expects the lisp variables `entry' and `date' to be provided
4351 by the caller, because this is how the calendar works. Don't use this
4352 function from a program - use `org-agenda-get-day-entries' instead."
4353 (org-agenda-maybe-reset-markers)
4354 (org-compile-prefix-format org-agenda-prefix-format)
4355 (setq args (or args '(:deadline :scheduled :timestamp)))
4356 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4357 (list entry)
4358 org-agenda-files))
4359 file rtn results)
4360 ;; If this is called during org-agenda, don't return any entries to
4361 ;; the calendar. Org Agenda will list these entries itself.
4362 (if org-disable-agenda-to-diary (setq files nil))
4363 (while (setq file (pop files))
4364 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4365 (setq results (append results rtn)))
4366 (if results
4367 (concat (org-finalize-agenda-entries results) "\n"))))
4368
4369 (defun org-agenda-get-day-entries (file date &rest args)
4370 "Does the work for `org-diary' and `org-agenda'.
4371 FILE is the path to a file to be checked for entries. DATE is date like
4372 the one returned by `calendar-current-date'. ARGS are symbols indicating
4373 which kind of entries should be extracted. For details about these, see
4374 the documentation of `org-diary'."
4375 (setq args (or args '(:deadline :scheduled :timestamp)))
4376 (let* ((org-startup-with-deadline-check nil)
4377 (org-startup-folded nil)
4378 (buffer (if (file-exists-p file)
4379 (org-get-agenda-file-buffer file)
4380 (error "No such file %s" file)))
4381 arg results rtn)
4382 (if (not buffer)
4383 ;; If file does not exist, make sure an error message ends up in diary
4384 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4385 (with-current-buffer buffer
4386 (unless (eq major-mode 'org-mode)
4387 (error "Agenda file %s is not in `org-mode'" file))
4388 (let ((case-fold-search nil))
4389 (save-excursion
4390 (save-restriction
4391 (if org-respect-restriction
4392 (if (org-region-active-p)
4393 ;; Respect a region to restrict search
4394 (narrow-to-region (region-beginning) (region-end)))
4395 ;; If we work for the calendar or many files,
4396 ;; get rid of any restriction
4397 (widen))
4398 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4399 (while (setq arg (pop args))
4400 (cond
4401 ((and (eq arg :todo)
4402 (equal date (calendar-current-date)))
4403 (setq rtn (org-agenda-get-todos))
4404 (setq results (append results rtn)))
4405 ((eq arg :timestamp)
4406 (setq rtn (org-agenda-get-blocks))
4407 (setq results (append results rtn))
4408 (setq rtn (org-agenda-get-timestamps))
4409 (setq results (append results rtn)))
4410 ((eq arg :scheduled)
4411 (setq rtn (org-agenda-get-scheduled))
4412 (setq results (append results rtn)))
4413 ((and (eq arg :deadline)
4414 (equal date (calendar-current-date)))
4415 (setq rtn (org-agenda-get-deadlines))
4416 (setq results (append results rtn))))))))
4417 results))))
4418
4419 (defun org-entry-is-done-p ()
4420 "Is the current entry marked DONE?"
4421 (save-excursion
4422 (and (re-search-backward "[\r\n]\\*" nil t)
4423 (looking-at org-nl-done-regexp))))
4424
4425 (defun org-at-date-range-p ()
4426 "Is the cursor inside a date range?"
4427 (interactive)
4428 (save-excursion
4429 (catch 'exit
4430 (let ((pos (point)))
4431 (skip-chars-backward "^<\r\n")
4432 (skip-chars-backward "<")
4433 (and (looking-at org-tr-regexp)
4434 (>= (match-end 0) pos)
4435 (throw 'exit t))
4436 (skip-chars-backward "^<\r\n")
4437 (skip-chars-backward "<")
4438 (and (looking-at org-tr-regexp)
4439 (>= (match-end 0) pos)
4440 (throw 'exit t)))
4441 nil)))
4442
4443 (defun org-agenda-get-todos ()
4444 "Return the TODO information for agenda display."
4445 (let* ((props (list 'face nil
4446 'done-face 'org-done
4447 'mouse-face 'highlight
4448 'keymap org-agenda-keymap
4449 'help-echo
4450 (format "mouse-2 or RET jump to org file %s"
4451 (abbreviate-file-name (buffer-file-name)))))
4452 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4453 "[^\n\r]*\\)"))
4454 marker priority
4455 ee txt)
4456 (goto-char (point-min))
4457 (while (re-search-forward regexp nil t)
4458 (goto-char (match-beginning 1))
4459 (setq marker (org-agenda-new-marker (point-at-bol))
4460 txt (org-format-agenda-item "" (match-string 1))
4461 priority
4462 (+ (org-get-priority txt)
4463 (if org-todo-kwd-priority-p
4464 (- org-todo-kwd-max-priority -2
4465 (length
4466 (member (match-string 2) org-todo-keywords)))
4467 1)))
4468 (add-text-properties
4469 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4470 'priority priority)
4471 props)
4472 txt)
4473 (push txt ee)
4474 (goto-char (match-end 1)))
4475 (nreverse ee)))
4476
4477 (defconst org-agenda-no-heading-message
4478 "No heading for this item in buffer or region")
4479
4480 (defun org-agenda-get-timestamps ()
4481 "Return the date stamp information for agenda display."
4482 (let* ((props (list 'face nil
4483 'mouse-face 'highlight
4484 'keymap org-agenda-keymap
4485 'help-echo
4486 (format "mouse-2 or RET jump to org file %s"
4487 (abbreviate-file-name (buffer-file-name)))))
4488 (regexp (regexp-quote
4489 (substring
4490 (format-time-string
4491 (car org-time-stamp-formats)
4492 (apply 'encode-time ; DATE bound by calendar
4493 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4494 0 11)))
4495 marker hdmarker deadlinep scheduledp donep tmp priority
4496 ee txt timestr)
4497 (goto-char (point-min))
4498 (while (re-search-forward regexp nil t)
4499 (if (not (save-match-data (org-at-date-range-p)))
4500 (progn
4501 (setq marker (org-agenda-new-marker (match-beginning 0))
4502 tmp (buffer-substring (max (point-min)
4503 (- (match-beginning 0)
4504 org-ds-keyword-length))
4505 (match-beginning 0))
4506 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4507 deadlinep (string-match org-deadline-regexp tmp)
4508 scheduledp (string-match org-scheduled-regexp tmp)
4509 donep (org-entry-is-done-p))
4510 (if (string-match ">" timestr)
4511 ;; substring should only run to end of time stamp
4512 (setq timestr (substring timestr 0 (match-end 0))))
4513 (save-excursion
4514 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4515 (progn
4516 (goto-char (match-end 1))
4517 (setq hdmarker (org-agenda-new-marker))
4518 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4519 (setq txt (org-format-agenda-item
4520 (format "%s%s"
4521 (if deadlinep "Deadline: " "")
4522 (if scheduledp "Scheduled: " ""))
4523 (match-string 1) nil timestr)))
4524 (setq txt org-agenda-no-heading-message))
4525 (setq priority (org-get-priority txt))
4526 (add-text-properties
4527 0 (length txt) (append (list 'org-marker marker
4528 'org-hd-marker hdmarker) props)
4529 txt)
4530 (if deadlinep
4531 (add-text-properties
4532 0 (length txt)
4533 (list 'face
4534 (if donep 'org-done 'org-warning)
4535 'undone-face 'org-warning
4536 'done-face 'org-done
4537 'priority (+ 100 priority))
4538 txt)
4539 (if scheduledp
4540 (add-text-properties
4541 0 (length txt)
4542 (list 'face 'org-scheduled-today
4543 'undone-face 'org-scheduled-today
4544 'done-face 'org-done
4545 priority (+ 99 priority))
4546 txt)
4547 (add-text-properties
4548 0 (length txt)
4549 (list 'priority priority) txt)))
4550 (push txt ee))
4551 (outline-next-heading))))
4552 (nreverse ee)))
4553
4554 (defun org-agenda-get-deadlines ()
4555 "Return the deadline information for agenda display."
4556 (let* ((wdays org-deadline-warning-days)
4557 (props (list 'mouse-face 'highlight
4558 'keymap org-agenda-keymap
4559 'help-echo
4560 (format "mouse-2 or RET jump to org file %s"
4561 (abbreviate-file-name (buffer-file-name)))))
4562 (regexp org-deadline-time-regexp)
4563 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4564 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4565 d2 diff pos pos1
4566 ee txt head)
4567 (goto-char (point-min))
4568 (while (re-search-forward regexp nil t)
4569 (setq pos (1- (match-beginning 1))
4570 d2 (time-to-days
4571 (org-time-string-to-time (match-string 1)))
4572 diff (- d2 d1))
4573 ;; When to show a deadline in the calendar:
4574 ;; If the expiration is within wdays warning time.
4575 ;; Past-due deadlines are only shown on the current date
4576 (if (and (< diff wdays) todayp (not (= diff 0)))
4577 (save-excursion
4578 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4579 (progn
4580 (goto-char (match-end 0))
4581 (setq pos1 (match-end 1))
4582 (setq head (buffer-substring-no-properties
4583 (point)
4584 (progn (skip-chars-forward "^\r\n")
4585 (point))))
4586 (if (string-match org-looking-at-done-regexp head)
4587 (setq txt nil)
4588 (setq txt (org-format-agenda-item
4589 (format "In %3d d.: " diff) head))))
4590 (setq txt org-agenda-no-heading-message))
4591 (when txt
4592 (add-text-properties
4593 0 (length txt)
4594 (append
4595 (list 'org-marker (org-agenda-new-marker pos)
4596 'org-hd-marker (org-agenda-new-marker pos1)
4597 'priority (+ (- 10 diff) (org-get-priority txt))
4598 'face (cond ((<= diff 0) 'org-warning)
4599 ((<= diff 5) 'org-scheduled-previously)
4600 (t nil))
4601 'undone-face (cond
4602 ((<= diff 0) 'org-warning)
4603 ((<= diff 5) 'org-scheduled-previously)
4604 (t nil))
4605 'done-face 'org-done)
4606 props)
4607 txt)
4608 (push txt ee)))))
4609 ee))
4610
4611 (defun org-agenda-get-scheduled ()
4612 "Return the scheduled information for agenda display."
4613 (let* ((props (list 'face 'org-scheduled-previously
4614 'undone-face 'org-scheduled-previously
4615 'done-face 'org-done
4616 'mouse-face 'highlight
4617 'keymap org-agenda-keymap
4618 'help-echo
4619 (format "mouse-2 or RET jump to org file %s"
4620 (abbreviate-file-name (buffer-file-name)))))
4621 (regexp org-scheduled-time-regexp)
4622 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4623 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4624 d2 diff pos pos1
4625 ee txt head)
4626 (goto-char (point-min))
4627 (while (re-search-forward regexp nil t)
4628 (setq pos (1- (match-beginning 1))
4629 d2 (time-to-days
4630 (org-time-string-to-time (match-string 1)))
4631 diff (- d2 d1))
4632 ;; When to show a scheduled item in the calendar:
4633 ;; If it is on or past the date.
4634 (if (and (< diff 0) todayp)
4635 (save-excursion
4636 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4637 (progn
4638 (goto-char (match-end 0))
4639 (setq pos1 (match-end 1))
4640 (setq head (buffer-substring-no-properties
4641 (point)
4642 (progn (skip-chars-forward "^\r\n") (point))))
4643 (if (string-match org-looking-at-done-regexp head)
4644 (setq txt nil)
4645 (setq txt (org-format-agenda-item
4646 (format "Sched.%2dx: " (- 1 diff)) head))))
4647 (setq txt org-agenda-no-heading-message))
4648 (when txt
4649 (add-text-properties
4650 0 (length txt)
4651 (append (list 'org-marker (org-agenda-new-marker pos)
4652 'org-hd-marker (org-agenda-new-marker pos1)
4653 'priority (+ (- 5 diff) (org-get-priority txt)))
4654 props) txt)
4655 (push txt ee)))))
4656 ee))
4657
4658 (defun org-agenda-get-blocks ()
4659 "Return the date-range information for agenda display."
4660 (let* ((props (list 'face nil
4661 'mouse-face 'highlight
4662 'keymap org-agenda-keymap
4663 'help-echo
4664 (format "mouse-2 or RET jump to org file %s"
4665 (abbreviate-file-name (buffer-file-name)))))
4666 (regexp org-tr-regexp)
4667 (d0 (calendar-absolute-from-gregorian date))
4668 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4669 (goto-char (point-min))
4670 (while (re-search-forward regexp nil t)
4671 (setq timestr (match-string 0)
4672 s1 (match-string 1)
4673 s2 (match-string 2)
4674 d1 (time-to-days (org-time-string-to-time s1))
4675 d2 (time-to-days (org-time-string-to-time s2)))
4676 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4677 ;; Only allow days between the limits, because the normal
4678 ;; date stamps will catch the limits.
4679 (save-excursion
4680 (setq marker (org-agenda-new-marker (point)))
4681 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4682 (progn
4683 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4684 (goto-char (match-end 1))
4685 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4686 (setq txt (org-format-agenda-item
4687 (format (if (= d1 d2) "" "(%d/%d): ")
4688 (1+ (- d0 d1)) (1+ (- d2 d1)))
4689 (match-string 1) nil (if (= d0 d1) timestr))))
4690 (setq txt org-agenda-no-heading-message))
4691 (add-text-properties
4692 0 (length txt) (append (list 'org-marker marker
4693 'org-hd-marker hdmarker
4694 'priority (org-get-priority txt))
4695 props)
4696 txt)
4697 (push txt ee)))
4698 (outline-next-heading))
4699 ;; Sort the entries by expiration date.
4700 (nreverse ee)))
4701
4702
4703
4704 (defconst org-plain-time-of-day-regexp
4705 (concat
4706 "\\(\\<[012]?[0-9]"
4707 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4708 "\\(--?"
4709 "\\(\\<[012]?[0-9]"
4710 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4711 "\\)?")
4712 "Regular expression to match a plain time or time range.
4713 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4714 groups carry important information:
4715 0 the full match
4716 1 the first time, range or not
4717 8 the second time, if it is a range.")
4718
4719 (defconst org-stamp-time-of-day-regexp
4720 (concat
4721 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4722 "\\([012][0-9]:[0-5][0-9]\\)>"
4723 "\\(--?"
4724 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4725 "Regular expression to match a timestamp time or time range.
4726 After a match, the following groups carry important information:
4727 0 the full match
4728 1 date plus weekday, for backreferencing to make sure both times on same day
4729 2 the first time, range or not
4730 4 the second time, if it is a range.")
4731
4732 (defvar org-prefix-has-time nil
4733 "A flag, set by `org-compile-prefix-format'.
4734 The flag is set if the currently compiled format contains a `%t'.")
4735
4736 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4737 "Format TXT to be inserted into the agenda buffer.
4738 In particular, it adds the prefix and corresponding text properties. EXTRA
4739 must be a string and replaces the `%s' specifier in the prefix format.
4740 CATEGORY (string, symbol or nil) may be used to overule the default
4741 category taken from local variable or file name. It will replace the `%c'
4742 specifier in the format. DOTIME, when non-nil, indicates that a
4743 time-of-day should be extracted from TXT for sorting of this entry, and for
4744 the `%t' specifier in the format. When DOTIME is a string, this string is
4745 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4746 only the correctly processes TXT should be returned - this is used by
4747 `org-agenda-change-all-lines'."
4748 (save-match-data
4749 ;; Diary entries sometimes have extra whitespace at the beginning
4750 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4751 (let* ((category (or category
4752 org-category
4753 (if (buffer-file-name)
4754 (file-name-sans-extension
4755 (file-name-nondirectory (buffer-file-name)))
4756 "")))
4757 time ;; needed for the eval of the prefix format
4758 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4759 (time-of-day (and dotime (org-get-time-of-day ts)))
4760 stamp plain s0 s1 s2 rtn)
4761 (when (and dotime time-of-day org-prefix-has-time)
4762 ;; Extract starting and ending time and move them to prefix
4763 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4764 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4765 (setq s0 (match-string 0 ts)
4766 s1 (match-string (if plain 1 2) ts)
4767 s2 (match-string (if plain 8 4) ts))
4768
4769 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4770 ;; them, we might want to remove them there to avoid duplication.
4771 ;; The user can turn this off with a variable.
4772 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4773 (string-match (concat (regexp-quote s0) " *") txt)
4774 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4775 (= (match-beginning 0) 0)
4776 t))
4777 (setq txt (replace-match "" nil nil txt))))
4778 ;; Normalize the time(s) to 24 hour
4779 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4780 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4781
4782 ;; Create the final string
4783 (if noprefix
4784 (setq rtn txt)
4785 ;; Prepare the variables needed in the eval of the compiled format
4786 (setq time (cond (s2 (concat s1 "-" s2))
4787 (s1 (concat s1 "......"))
4788 (t ""))
4789 extra (or extra "")
4790 category (if (symbolp category) (symbol-name category) category))
4791 ;; Evaluate the compiled format
4792 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4793
4794 ;; And finally add the text properties
4795 (add-text-properties
4796 0 (length rtn) (list 'category (downcase category)
4797 'prefix-length (- (length rtn) (length txt))
4798 'time-of-day time-of-day
4799 'dotime dotime)
4800 rtn)
4801 rtn)))
4802
4803 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4804 (catch 'exit
4805 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4806 ((and todayp (member 'today (car org-agenda-time-grid))))
4807 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4808 ((member 'weekly (car org-agenda-time-grid)))
4809 (t (throw 'exit list)))
4810 (let* ((have (delq nil (mapcar
4811 (lambda (x) (get-text-property 1 'time-of-day x))
4812 list)))
4813 (string (nth 1 org-agenda-time-grid))
4814 (gridtimes (nth 2 org-agenda-time-grid))
4815 (req (car org-agenda-time-grid))
4816 (remove (member 'remove-match req))
4817 new time)
4818 (if (and (member 'require-timed req) (not have))
4819 ;; don't show empty grid
4820 (throw 'exit list))
4821 (while (setq time (pop gridtimes))
4822 (unless (and remove (member time have))
4823 (setq time (int-to-string time))
4824 (push (org-format-agenda-item
4825 nil string "" ;; FIXME: put a category?
4826 (concat (substring time 0 -2) ":" (substring time -2)))
4827 new)
4828 (put-text-property
4829 1 (length (car new)) 'face 'org-time-grid (car new))))
4830 (if (member 'time-up org-agenda-sorting-strategy)
4831 (append new list)
4832 (append list new)))))
4833
4834 (defun org-compile-prefix-format (format)
4835 "Compile the prefix format into a Lisp form that can be evaluated.
4836 The resulting form is returned and stored in the variable
4837 `org-prefix-format-compiled'."
4838 (setq org-prefix-has-time nil)
4839 (let ((start 0) varform vars var (s format) c f opt)
4840 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4841 s start)
4842 (setq var (cdr (assoc (match-string 4 s)
4843 '(("c" . category) ("t" . time) ("s" . extra))))
4844 c (or (match-string 3 s) "")
4845 opt (match-beginning 1)
4846 start (1+ (match-beginning 0)))
4847 (if (equal var 'time) (setq org-prefix-has-time t))
4848 (setq f (concat "%" (match-string 2 s) "s"))
4849 (if opt
4850 (setq varform
4851 `(if (equal "" ,var)
4852 ""
4853 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4854 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4855 (setq s (replace-match "%s" t nil s))
4856 (push varform vars))
4857 (setq vars (nreverse vars))
4858 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4859
4860 (defun org-get-time-of-day (s &optional string)
4861 "Check string S for a time of day.
4862 If found, return it as a military time number between 0 and 2400.
4863 If not found, return nil.
4864 The optional STRING argument forces conversion into a 5 character wide string
4865 HH:MM."
4866 (save-match-data
4867 (when
4868 (or
4869 (string-match
4870 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4871 (string-match
4872 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4873 (let* ((t0 (+ (* 100
4874 (+ (string-to-number (match-string 1 s))
4875 (if (and (match-beginning 4)
4876 (equal (downcase (match-string 4 s)) "pm"))
4877 12 0)))
4878 (if (match-beginning 3)
4879 (string-to-number (match-string 3 s))
4880 0)))
4881 (t1 (concat " " (int-to-string t0))))
4882 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4883
4884 (defun org-finalize-agenda-entries (list)
4885 "Sort and concatenate the agenda items."
4886 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4887
4888 (defsubst org-cmp-priority (a b)
4889 "Compare the priorities of string a and b."
4890 (let ((pa (or (get-text-property 1 'priority a) 0))
4891 (pb (or (get-text-property 1 'priority b) 0)))
4892 (cond ((> pa pb) +1)
4893 ((< pa pb) -1)
4894 (t nil))))
4895
4896 (defsubst org-cmp-category (a b)
4897 "Compare the string values of categories of strings a and b."
4898 (let ((ca (or (get-text-property 1 'category a) ""))
4899 (cb (or (get-text-property 1 'category b) "")))
4900 (cond ((string-lessp ca cb) -1)
4901 ((string-lessp cb ca) +1)
4902 (t nil))))
4903
4904 (defsubst org-cmp-time (a b)
4905 "Compare the time-of-day values of strings a and b."
4906 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4907 (ta (or (get-text-property 1 'time-of-day a) def))
4908 (tb (or (get-text-property 1 'time-of-day b) def)))
4909 (cond ((< ta tb) -1)
4910 ((< tb ta) +1)
4911 (t nil))))
4912
4913 (defun org-entries-lessp (a b)
4914 "Predicate for sorting agenda entries."
4915 ;; The following variables will be used when the form is evaluated.
4916 (let* ((time-up (org-cmp-time a b))
4917 (time-down (if time-up (- time-up) nil))
4918 (priority-up (org-cmp-priority a b))
4919 (priority-down (if priority-up (- priority-up) nil))
4920 (category-up (org-cmp-category a b))
4921 (category-down (if category-up (- category-up) nil))
4922 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4923 (cdr (assoc
4924 (eval (cons 'or org-agenda-sorting-strategy))
4925 '((-1 . t) (1 . nil) (nil . nil))))))
4926
4927 (defun org-agenda-show-priority ()
4928 "Show the priority of the current item.
4929 This priority is composed of the main priority given with the [#A] cookies,
4930 and by additional input from the age of a schedules or deadline entry."
4931 (interactive)
4932 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4933 (message "Priority is %d" (if pri pri -1000))))
4934
4935 (defun org-agenda-goto (&optional highlight)
4936 "Go to the Org-mode file which contains the item at point."
4937 (interactive)
4938 (let* ((marker (or (get-text-property (point) 'org-marker)
4939 (org-agenda-error)))
4940 (buffer (marker-buffer marker))
4941 (pos (marker-position marker)))
4942 (switch-to-buffer-other-window buffer)
4943 (widen)
4944 (goto-char pos)
4945 (when (eq major-mode 'org-mode)
4946 (org-show-hidden-entry)
4947 (save-excursion
4948 (and (outline-next-heading)
4949 (org-flag-heading nil)))) ; show the next heading
4950 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4951
4952 (defun org-agenda-switch-to ()
4953 "Go to the Org-mode file which contains the item at point."
4954 (interactive)
4955 (let* ((marker (or (get-text-property (point) 'org-marker)
4956 (org-agenda-error)))
4957 (buffer (marker-buffer marker))
4958 (pos (marker-position marker)))
4959 (switch-to-buffer buffer)
4960 (delete-other-windows)
4961 (widen)
4962 (goto-char pos)
4963 (when (eq major-mode 'org-mode)
4964 (org-show-hidden-entry)
4965 (save-excursion
4966 (and (outline-next-heading)
4967 (org-flag-heading nil)))))) ; show the next heading
4968
4969 (defun org-agenda-goto-mouse (ev)
4970 "Go to the Org-mode file which contains the item at the mouse click."
4971 (interactive "e")
4972 (mouse-set-point ev)
4973 (org-agenda-goto))
4974
4975 (defun org-agenda-show ()
4976 "Display the Org-mode file which contains the item at point."
4977 (interactive)
4978 (let ((win (selected-window)))
4979 (org-agenda-goto t)
4980 (select-window win)))
4981
4982 (defun org-agenda-recenter (arg)
4983 "Display the Org-mode file which contains the item at point and recenter."
4984 (interactive "P")
4985 (let ((win (selected-window)))
4986 (org-agenda-goto t)
4987 (recenter arg)
4988 (select-window win)))
4989
4990 (defun org-agenda-show-mouse (ev)
4991 "Display the Org-mode file which contains the item at the mouse click."
4992 (interactive "e")
4993 (mouse-set-point ev)
4994 (org-agenda-show))
4995
4996 (defun org-agenda-check-no-diary ()
4997 "Check if the entry is a diary link and abort if yes."
4998 (if (get-text-property (point) 'org-agenda-diary-link)
4999 (org-agenda-error)))
5000
5001 (defun org-agenda-error ()
5002 (error "Command not allowed in this line"))
5003
5004 (defvar org-last-heading-marker (make-marker)
5005 "Marker pointing to the headline that last changed its TODO state
5006 by a remote command from the agenda.")
5007
5008 (defun org-agenda-todo ()
5009 "Cycle TODO state of line at point, also in Org-mode file.
5010 This changes the line at point, all other lines in the agenda referring to
5011 the same tree node, and the headline of the tree node in the Org-mode file."
5012 (interactive)
5013 (org-agenda-check-no-diary)
5014 (let* ((col (current-column))
5015 (marker (or (get-text-property (point) 'org-marker)
5016 (org-agenda-error)))
5017 (buffer (marker-buffer marker))
5018 (pos (marker-position marker))
5019 (hdmarker (get-text-property (point) 'org-hd-marker))
5020 (buffer-read-only nil)
5021 newhead)
5022 (with-current-buffer buffer
5023 (widen)
5024 (goto-char pos)
5025 (org-show-hidden-entry)
5026 (save-excursion
5027 (and (outline-next-heading)
5028 (org-flag-heading nil))) ; show the next heading
5029 (org-todo)
5030 (forward-char 1)
5031 (setq newhead (org-get-heading))
5032 (save-excursion
5033 (org-back-to-heading)
5034 (move-marker org-last-heading-marker (point))))
5035 (beginning-of-line 1)
5036 (save-excursion
5037 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5038 (move-to-column col)))
5039
5040 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5041 "Change all lines in the agenda buffer which match hdmarker.
5042 The new content of the line will be NEWHEAD (as modified by
5043 `org-format-agenda-item'). HDMARKER is checked with
5044 `equal' against all `org-hd-marker' text properties in the file.
5045 If FIXFACE is non-nil, the face of each item is modified acording to
5046 the new TODO state."
5047 (let* (props m pl undone-face done-face finish new dotime)
5048 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5049 (save-excursion
5050 (goto-char (point-max))
5051 (beginning-of-line 1)
5052 (while (not finish)
5053 (setq finish (bobp))
5054 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5055 (equal m hdmarker))
5056 (setq props (text-properties-at (point))
5057 dotime (get-text-property (point) 'dotime)
5058 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
5059 pl (get-text-property (point) 'prefix-length)
5060 undone-face (get-text-property (point) 'undone-face)
5061 done-face (get-text-property (point) 'done-face))
5062 (move-to-column pl)
5063 (if (looking-at ".*")
5064 (progn
5065 (replace-match new t t)
5066 (beginning-of-line 1)
5067 (add-text-properties (point-at-bol) (point-at-eol) props)
5068 (if fixface
5069 (add-text-properties
5070 (point-at-bol) (point-at-eol)
5071 (list 'face
5072 (if org-last-todo-state-is-todo
5073 undone-face done-face))))
5074 (beginning-of-line 1))
5075 (error "Line update did not work")))
5076 (beginning-of-line 0)))))
5077
5078 (defun org-agenda-priority-up ()
5079 "Increase the priority of line at point, also in Org-mode file."
5080 (interactive)
5081 (org-agenda-priority 'up))
5082
5083 (defun org-agenda-priority-down ()
5084 "Decrease the priority of line at point, also in Org-mode file."
5085 (interactive)
5086 (org-agenda-priority 'down))
5087
5088 (defun org-agenda-priority (&optional force-direction)
5089 "Set the priority of line at point, also in Org-mode file.
5090 This changes the line at point, all other lines in the agenda referring to
5091 the same tree node, and the headline of the tree node in the Org-mode file."
5092 (interactive)
5093 (org-agenda-check-no-diary)
5094 (let* ((marker (or (get-text-property (point) 'org-marker)
5095 (org-agenda-error)))
5096 (buffer (marker-buffer marker))
5097 (pos (marker-position marker))
5098 (hdmarker (get-text-property (point) 'org-hd-marker))
5099 (buffer-read-only nil)
5100 newhead)
5101 (with-current-buffer buffer
5102 (widen)
5103 (goto-char pos)
5104 (org-show-hidden-entry)
5105 (save-excursion
5106 (and (outline-next-heading)
5107 (org-flag-heading nil))) ; show the next heading
5108 (funcall 'org-priority force-direction)
5109 (end-of-line 1)
5110 (setq newhead (org-get-heading)))
5111 (org-agenda-change-all-lines newhead hdmarker)
5112 (beginning-of-line 1)))
5113
5114 (defun org-agenda-date-later (arg &optional what)
5115 "Change the date of this item to one day later."
5116 (interactive "p")
5117 (org-agenda-check-no-diary)
5118 (let* ((marker (or (get-text-property (point) 'org-marker)
5119 (org-agenda-error)))
5120 (buffer (marker-buffer marker))
5121 (pos (marker-position marker)))
5122 (with-current-buffer buffer
5123 (widen)
5124 (goto-char pos)
5125 (if (not (org-at-timestamp-p))
5126 (error "Cannot find time stamp"))
5127 (org-timestamp-change arg (or what 'day))
5128 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5129
5130 (defun org-agenda-date-earlier (arg &optional what)
5131 "Change the date of this item to one day earlier."
5132 (interactive "p")
5133 (org-agenda-date-later (- arg) what))
5134
5135 (defun org-agenda-date-prompt (arg)
5136 "Change the date of this item. Date is prompted for, with default today.
5137 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5138 be used to request time specification in the time stamp."
5139 (interactive "P")
5140 (org-agenda-check-no-diary)
5141 (let* ((marker (or (get-text-property (point) 'org-marker)
5142 (org-agenda-error)))
5143 (buffer (marker-buffer marker))
5144 (pos (marker-position marker)))
5145 (with-current-buffer buffer
5146 (widen)
5147 (goto-char pos)
5148 (if (not (org-at-timestamp-p))
5149 (error "Cannot find time stamp"))
5150 (org-time-stamp arg)
5151 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5152
5153 (defun org-get-heading ()
5154 "Return the heading of the current entry, without the stars."
5155 (save-excursion
5156 (if (and (re-search-backward "[\r\n]\\*" nil t)
5157 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5158 (match-string 1)
5159 "")))
5160
5161 (defun org-agenda-diary-entry ()
5162 "Make a diary entry, like the `i' command from the calendar.
5163 All the standard commands work: block, weekly etc"
5164 (interactive)
5165 (require 'diary-lib)
5166 (let* ((char (progn
5167 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5168 (read-char-exclusive)))
5169 (cmd (cdr (assoc char
5170 '((?d . insert-diary-entry)
5171 (?w . insert-weekly-diary-entry)
5172 (?m . insert-monthly-diary-entry)
5173 (?y . insert-yearly-diary-entry)
5174 (?a . insert-anniversary-diary-entry)
5175 (?b . insert-block-diary-entry)
5176 (?c . insert-cyclic-diary-entry)))))
5177 (oldf (symbol-function 'calendar-cursor-to-date))
5178 (point (point))
5179 (mark (or (mark t) (point))))
5180 (unless cmd
5181 (error "No command associated with <%c>" char))
5182 (unless (and (get-text-property point 'day)
5183 (or (not (equal ?b char))
5184 (get-text-property mark 'day)))
5185 (error "Don't know which date to use for diary entry"))
5186 ;; We implement this by hacking the `calendar-cursor-to-date' function
5187 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5188 (let ((calendar-mark-ring
5189 (list (calendar-gregorian-from-absolute
5190 (or (get-text-property mark 'day)
5191 (get-text-property point 'day))))))
5192 (unwind-protect
5193 (progn
5194 (fset 'calendar-cursor-to-date
5195 (lambda (&optional error)
5196 (calendar-gregorian-from-absolute
5197 (get-text-property point 'day))))
5198 (call-interactively cmd))
5199 (fset 'calendar-cursor-to-date oldf)))))
5200
5201
5202 (defun org-agenda-execute-calendar-command (cmd)
5203 "Execute a calendar command from the agenda, with the date associated to
5204 the cursor position."
5205 (require 'diary-lib)
5206 (unless (get-text-property (point) 'day)
5207 (error "Don't know which date to use for calendar command"))
5208 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5209 (point (point))
5210 (date (calendar-gregorian-from-absolute
5211 (get-text-property point 'day)))
5212 (displayed-day (extract-calendar-day date))
5213 (displayed-month (extract-calendar-month date))
5214 (displayed-year (extract-calendar-year date)))
5215 (unwind-protect
5216 (progn
5217 (fset 'calendar-cursor-to-date
5218 (lambda (&optional error)
5219 (calendar-gregorian-from-absolute
5220 (get-text-property point 'day))))
5221 (call-interactively cmd))
5222 (fset 'calendar-cursor-to-date oldf))))
5223
5224 (defun org-agenda-phases-of-moon ()
5225 "Display the phases of the moon for the 3 months around the cursor date."
5226 (interactive)
5227 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5228
5229 (defun org-agenda-holidays ()
5230 "Display the holidays for the 3 months around the cursor date."
5231 (interactive)
5232 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5233
5234 (defun org-agenda-sunrise-sunset (arg)
5235 "Display sunrise and sunset for the cursor date.
5236 Latitude and longitude can be specified with the variables
5237 `calendar-latitude' and `calendar-longitude'. When called with prefix
5238 argument, latitude and longitude will be prompted for."
5239 (interactive "P")
5240 (let ((calendar-longitude (if arg nil calendar-longitude))
5241 (calendar-latitude (if arg nil calendar-latitude))
5242 (calendar-location-name
5243 (if arg "the given coordinates" calendar-location-name)))
5244 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5245
5246 (defun org-agenda-goto-calendar ()
5247 "Open the Emacs calendar with the date at the cursor."
5248 (interactive)
5249 (let* ((day (or (get-text-property (point) 'day)
5250 (error "Don't know which date to open in calendar")))
5251 (date (calendar-gregorian-from-absolute day)))
5252 (let ((view-diary-entries-initially nil))
5253 (calendar))
5254 (calendar-goto-date date)))
5255
5256 (defun org-calendar-goto-agenda ()
5257 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5258 This is a command that has to be installed in `calendar-mode-map'."
5259 (interactive)
5260 (org-agenda nil (calendar-absolute-from-gregorian
5261 (calendar-cursor-to-date))))
5262
5263 (defun org-agenda-convert-date ()
5264 (interactive)
5265 (let ((day (get-text-property (point) 'day))
5266 date s)
5267 (unless day
5268 (error "Don't know which date to convert"))
5269 (setq date (calendar-gregorian-from-absolute day))
5270 (setq s (concat
5271 "Gregorian: " (calendar-date-string date) "\n"
5272 "ISO: " (calendar-iso-date-string date) "\n"
5273 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5274 "Julian: " (calendar-julian-date-string date) "\n"
5275 "Astron. JD: " (calendar-astro-date-string date)
5276 " (Julian date number at noon UTC)\n"
5277 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5278 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5279 "French: " (calendar-french-date-string date) "\n"
5280 "Mayan: " (calendar-mayan-date-string date) "\n"
5281 "Coptic: " (calendar-coptic-date-string date) "\n"
5282 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5283 "Persian: " (calendar-persian-date-string date) "\n"
5284 "Chinese: " (calendar-chinese-date-string date) "\n"))
5285 (with-output-to-temp-buffer "*Dates*"
5286 (princ s))
5287 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5288
5289 ;;; Link Stuff
5290
5291 (defun org-find-file-at-mouse (ev)
5292 "Open file link or URL at mouse."
5293 (interactive "e")
5294 (mouse-set-point ev)
5295 (org-open-at-point 'in-emacs))
5296
5297 (defun org-open-at-mouse (ev)
5298 "Open file link or URL at mouse."
5299 (interactive "e")
5300 (mouse-set-point ev)
5301 (org-open-at-point))
5302
5303 (defun org-open-at-point (&optional in-emacs)
5304 "Open link at or after point.
5305 If there is no link at point, this function will search forward up to
5306 the end of the current subtree.
5307 Normally, files will be opened by an appropriate application. If the
5308 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5309 (interactive "P")
5310 (if (org-at-timestamp-p)
5311 (org-agenda nil (time-to-days (org-time-string-to-time
5312 (substring (match-string 1) 0 10)))
5313 1)
5314 (let (type path line (pos (point)))
5315 (save-excursion
5316 (skip-chars-backward
5317 (concat (if org-allow-space-in-links "^" "^ ")
5318 org-non-link-chars))
5319 (if (re-search-forward
5320 org-link-regexp
5321 (save-excursion
5322 (condition-case nil
5323 (progn (outline-end-of-subtree) (max pos (point)))
5324 (error (end-of-line 1) (point))))
5325 t)
5326 (setq type (match-string 1)
5327 path (match-string 2)))
5328 (unless path
5329 (error "No link found"))
5330 ;; Remove any trailing spaces in path
5331 (if (string-match " +\\'" path)
5332 (setq path (replace-match "" t t path)))
5333
5334 (cond
5335
5336 ((string= type "file")
5337 (if (string-match ":\\([0-9]+\\)\\'" path)
5338 (setq line (string-to-number (match-string 1 path))
5339 path (substring path 0 (match-beginning 0))))
5340 (org-open-file path in-emacs line))
5341
5342 ((string= type "news")
5343 (org-follow-gnus-link path))
5344
5345 ((string= type "bbdb")
5346 (org-follow-bbdb-link path))
5347
5348 ((string= type "gnus")
5349 (let (group article)
5350 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5351 (error "Error in Gnus link"))
5352 (setq group (match-string 1 path)
5353 article (match-string 3 path))
5354 (org-follow-gnus-link group article)))
5355
5356 ((string= type "vm")
5357 (let (folder article)
5358 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5359 (error "Error in VM link"))
5360 (setq folder (match-string 1 path)
5361 article (match-string 3 path))
5362 ;; in-emacs is the prefix arg, will be interpreted as read-only
5363 (org-follow-vm-link folder article in-emacs)))
5364
5365 ((string= type "wl")
5366 (let (folder article)
5367 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5368 (error "Error in Wanderlust link"))
5369 (setq folder (match-string 1 path)
5370 article (match-string 3 path))
5371 (org-follow-wl-link folder article)))
5372
5373 ((string= type "rmail")
5374 (let (folder article)
5375 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5376 (error "Error in RMAIL link"))
5377 (setq folder (match-string 1 path)
5378 article (match-string 3 path))
5379 (org-follow-rmail-link folder article)))
5380
5381 ((string= type "shell")
5382 (let ((cmd path))
5383 (while (string-match "@{" cmd)
5384 (setq cmd (replace-match "<" t t cmd)))
5385 (while (string-match "@}" cmd)
5386 (setq cmd (replace-match ">" t t cmd)))
5387 (if (or (not org-confirm-shell-links)
5388 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5389 (shell-command cmd)
5390 (error "Abort"))))
5391
5392 (t
5393 (browse-url-at-point)))))))
5394
5395 (defun org-follow-bbdb-link (name)
5396 "Follow a BBDB link to NAME."
5397 (require 'bbdb)
5398 (let ((inhibit-redisplay t))
5399 (catch 'exit
5400 ;; Exact match on name
5401 (bbdb-name (concat "\\`" name "\\'") nil)
5402 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5403 ;; Exact match on name
5404 (bbdb-company (concat "\\`" name "\\'") nil)
5405 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5406 ;; Partial match on name
5407 (bbdb-name name nil)
5408 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5409 ;; Partial match on company
5410 (bbdb-company name nil)
5411 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5412 ;; General match including network address and notes
5413 (bbdb name nil)
5414 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5415 (delete-window (get-buffer-window "*BBDB*"))
5416 (error "No matching BBDB record")))))
5417
5418 (defun org-follow-gnus-link (&optional group article)
5419 "Follow a Gnus link to GROUP and ARTICLE."
5420 (require 'gnus)
5421 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5422 (if group (gnus-fetch-group group))
5423 (if article
5424 (or (gnus-summary-goto-article article nil 'force)
5425 (if (fboundp 'gnus-summary-insert-cached-articles)
5426 (progn
5427 (gnus-summary-insert-cached-articles)
5428 (gnus-summary-goto-article article nil 'force))
5429 (message "Message could not be found.")))))
5430
5431 (defun org-follow-vm-link (&optional folder article readonly)
5432 "Follow a VM link to FOLDER and ARTICLE."
5433 (require 'vm)
5434 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5435 ;; ange-ftp or efs or tramp access
5436 (let ((user (or (match-string 1 folder) (user-login-name)))
5437 (host (match-string 2 folder))
5438 (file (match-string 3 folder)))
5439 (cond
5440 ((featurep 'tramp)
5441 ;; use tramp to access the file
5442 (if org-xemacs-p
5443 (setq folder (format "[%s@%s]%s" user host file))
5444 (setq folder (format "/%s@%s:%s" user host file))))
5445 (t
5446 ;; use ange-ftp or efs
5447 (require (if org-xemacs-p 'efs 'ange-ftp))
5448 (setq folder (format "/%s@%s:%s" user host file))))))
5449 (when folder
5450 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5451 (sit-for 0.1)
5452 (when article
5453 (vm-select-folder-buffer)
5454 (widen)
5455 (let ((case-fold-search t))
5456 (goto-char (point-min))
5457 (if (not (re-search-forward
5458 (concat "^" "message-id: *" (regexp-quote article))))
5459 (error "Could not find the specified message in this folder"))
5460 (vm-isearch-update)
5461 (vm-isearch-narrow)
5462 (vm-beginning-of-message)
5463 (vm-summarize)))))
5464
5465 (defun org-follow-wl-link (folder article)
5466 "Follow a Wanderlust link to FOLDER and ARTICLE."
5467 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5468 (if article (wl-summary-jump-to-msg-by-message-id article))
5469 (wl-summary-redisplay))
5470
5471 (defun org-follow-rmail-link (folder article)
5472 "Follow an RMAIL link to FOLDER and ARTICLE."
5473 (let (message-number)
5474 (save-excursion
5475 (save-window-excursion
5476 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5477 (setq message-number
5478 (save-restriction
5479 (widen)
5480 (goto-char (point-max))
5481 (if (re-search-backward
5482 (concat "^Message-ID:\\s-+" (regexp-quote
5483 (or article "")))
5484 nil t)
5485 (rmail-what-message))))))
5486 (if message-number
5487 (progn
5488 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5489 (rmail-show-message message-number)
5490 message-number)
5491 (error "Message not found"))))
5492
5493 (defun org-open-file (path &optional in-emacs line)
5494 "Open the file at PATH.
5495 First, this expands any special file name abbreviations. Then the
5496 configuration variable `org-file-apps' is checked if it contains an
5497 entry for this file type, and if yes, the corresponding command is launched.
5498 If no application is found, Emacs simply visits the file.
5499 With optional argument IN-EMACS, Emacs will visit the file.
5500 If the file does not exist, an error is thrown."
5501 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5502 (dfile (downcase file))
5503 ext cmd apps)
5504 (if (and (not (file-exists-p file))
5505 (not org-open-non-existing-files))
5506 (error "No such file: %s" file))
5507 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5508 (setq ext (match-string 1 dfile))
5509 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5510 (setq ext (match-string 1 dfile))))
5511 (setq apps (append org-file-apps (org-default-apps)))
5512 (if in-emacs
5513 (setq cmd 'emacs)
5514 (setq cmd (or (cdr (assoc ext apps))
5515 (cdr (assoc t apps)))))
5516 (cond
5517 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5518 (setq cmd (format cmd (concat "\"" file "\"")))
5519 (save-window-excursion
5520 (shell-command (concat cmd " & &"))))
5521 ((or (stringp cmd)
5522 (eq cmd 'emacs))
5523 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5524 (if line (goto-line line)))
5525 ((consp cmd)
5526 (eval cmd))
5527 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5528
5529 (defun org-default-apps ()
5530 "Return the default applications for this operating system."
5531 (cond
5532 ((eq system-type 'darwin)
5533 org-file-apps-defaults-macosx)
5534 ((eq system-type 'windows-nt)
5535 org-file-apps-defaults-windowsnt)
5536 (t org-file-apps-defaults-gnu)))
5537
5538 (defun org-expand-file-name (path)
5539 "Replace special path abbreviations and expand the file name."
5540 (expand-file-name path))
5541
5542
5543 (defvar org-insert-link-history nil
5544 "Minibuffer history for links inserted with `org-insert-link'.")
5545
5546 (defvar org-stored-links nil
5547 "Contains the links stored with `org-store-link'.")
5548
5549 ;;;###autoload
5550 (defun org-store-link (arg)
5551 "\\<org-mode-map>Store an org-link to the current location.
5552 This link can later be inserted into an org-buffer with
5553 \\[org-insert-link].
5554 For some link types, a prefix arg is interpreted:
5555 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5556 For file links, arg negates `org-line-numbers-in-file-links'."
5557 (interactive "P")
5558 (let (link cpltxt)
5559 (cond
5560
5561 ((eq major-mode 'bbdb-mode)
5562 (setq cpltxt (concat
5563 "bbdb:"
5564 (or (bbdb-record-name (bbdb-current-record))
5565 (bbdb-record-company (bbdb-current-record))))
5566 link (org-make-link cpltxt)))
5567
5568 ((eq major-mode 'calendar-mode)
5569 (let ((cd (calendar-cursor-to-date)))
5570 (setq link
5571 (format-time-string
5572 (car org-time-stamp-formats)
5573 (apply 'encode-time
5574 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5575 nil nil nil))))))
5576
5577 ((or (eq major-mode 'vm-summary-mode)
5578 (eq major-mode 'vm-presentation-mode))
5579 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5580 (vm-follow-summary-cursor)
5581 (save-excursion
5582 (vm-select-folder-buffer)
5583 (let* ((message (car vm-message-pointer))
5584 (folder (buffer-file-name))
5585 (subject (vm-su-subject message))
5586 (author (vm-su-full-name message))
5587 (message-id (vm-su-message-id message)))
5588 (setq folder (abbreviate-file-name folder))
5589 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5590 folder)
5591 (setq folder (replace-match "" t t folder)))
5592 (setq cpltxt (concat author " on: " subject))
5593 (setq link (concat cpltxt "\n "
5594 (org-make-link
5595 "vm:" folder "#" message-id))))))
5596
5597 ((eq major-mode 'wl-summary-mode)
5598 (let* ((msgnum (wl-summary-message-number))
5599 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5600 msgnum 'message-id))
5601 (wl-message-entity (elmo-msgdb-overview-get-entity
5602 msgnum (wl-summary-buffer-msgdb)))
5603 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5604 (subject "???")) ; FIXME: How to get subject of email?
5605 (setq cpltxt (concat author " on: " subject))
5606 (setq link (concat cpltxt "\n "
5607 (org-make-link
5608 "wl:" wl-summary-buffer-folder-name
5609 "#" message-id)))))
5610
5611 ((eq major-mode 'rmail-mode)
5612 (save-excursion
5613 (save-restriction
5614 (rmail-narrow-to-non-pruned-header)
5615 (let ((folder (buffer-file-name))
5616 (message-id (mail-fetch-field "message-id"))
5617 (author (mail-fetch-field "from"))
5618 (subject (mail-fetch-field "subject")))
5619 (setq cpltxt (concat author " on: " subject))
5620 (setq link (concat cpltxt "\n "
5621 (org-make-link
5622 "rmail:" folder "#" message-id)))))))
5623
5624 ((eq major-mode 'gnus-group-mode)
5625 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5626 (gnus-group-group-name)) ; version
5627 ((fboundp 'gnus-group-name)
5628 (gnus-group-name))
5629 (t "???"))))
5630 (setq cpltxt (concat
5631 (if (org-xor arg org-usenet-links-prefer-google)
5632 "http://groups.google.com/groups?group="
5633 "gnus:")
5634 group)
5635 link (org-make-link cpltxt))))
5636
5637 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5638 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5639 (gnus-summary-beginning-of-article)
5640 (let* ((group (car gnus-article-current))
5641 (article (cdr gnus-article-current))
5642 (header (gnus-summary-article-header article))
5643 (author (mail-header-from header))
5644 (message-id (mail-header-id header))
5645 (date (mail-header-date header))
5646 (subject (gnus-summary-subject-string)))
5647 (setq cpltxt (concat author " on: " subject))
5648 (if (org-xor arg org-usenet-links-prefer-google)
5649 (setq link
5650 (concat
5651 cpltxt "\n "
5652 (format "http://groups.google.com/groups?as_umsgid=%s"
5653 (org-fixup-message-id-for-http message-id))))
5654 (setq link (concat cpltxt "\n"
5655 (org-make-link
5656 "gnus:" group
5657 "#" (number-to-string article)))))))
5658
5659 ((eq major-mode 'w3-mode)
5660 (setq cpltxt (url-view-url t)
5661 link (org-make-link cpltxt)))
5662 ((eq major-mode 'w3m-mode)
5663 (setq cpltxt w3m-current-url
5664 link (org-make-link cpltxt)))
5665
5666 ((buffer-file-name)
5667 ;; Just link to this file here.
5668 (setq cpltxt (concat "file:"
5669 (abbreviate-file-name (buffer-file-name))))
5670 ;; Add the line number?
5671 (if (org-xor org-line-numbers-in-file-links arg)
5672 (setq cpltxt
5673 (concat cpltxt
5674 ":" (int-to-string
5675 (+ (if (bolp) 1 0) (count-lines
5676 (point-min) (point)))))))
5677 (setq link (org-make-link cpltxt)))
5678
5679 ((interactive-p)
5680 (error "Cannot link to a buffer which is not visiting a file"))
5681
5682 (t (setq link nil)))
5683
5684 (if (and (interactive-p) link)
5685 (progn
5686 (setq org-stored-links
5687 (cons (cons (or cpltxt link) link) org-stored-links))
5688 (message "Stored: %s" (or cpltxt link)))
5689 link)))
5690
5691 (defun org-make-link (&rest strings)
5692 "Concatenate STRINGS, format resulting string with `org-link-format'."
5693 (format org-link-format (apply 'concat strings)))
5694
5695 (defun org-xor (a b)
5696 "Exclusive or."
5697 (if a (not b) b))
5698
5699 (defun org-get-header (header)
5700 "Find a header field in the current buffer."
5701 (save-excursion
5702 (goto-char (point-min))
5703 (let ((case-fold-search t) s)
5704 (cond
5705 ((eq header 'from)
5706 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5707 (setq s (match-string 1)))
5708 (while (string-match "\"" s)
5709 (setq s (replace-match "" t t s)))
5710 (if (string-match "[<(].*" s)
5711 (setq s (replace-match "" t t s))))
5712 ((eq header 'message-id)
5713 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5714 (setq s (match-string 1))))
5715 ((eq header 'subject)
5716 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5717 (setq s (match-string 1)))))
5718 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5719 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5720 s)))
5721
5722
5723 (defun org-fixup-message-id-for-http (s)
5724 "Replace special characters in a message id, so it can be used in an http query."
5725 (while (string-match "<" s)
5726 (setq s (replace-match "%3C" t t s)))
5727 (while (string-match ">" s)
5728 (setq s (replace-match "%3E" t t s)))
5729 (while (string-match "@" s)
5730 (setq s (replace-match "%40" t t s)))
5731 s)
5732
5733 (defun org-insert-link (&optional complete-file)
5734 "Insert a link. At the prompt, enter the link.
5735
5736 Completion can be used to select a link previously stored with
5737 `org-store-link'. When the empty string is entered (i.e. if you just
5738 press RET at the prompt), the link defaults to the most recently
5739 stored link. As SPC triggers completion in the minibuffer, you need to
5740 use M-SPC or C-q SPC to force the insertion of a space character.
5741
5742 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5743 selected using completion. The path to the file will be relative to
5744 the current directory if the file is in the current directory or a
5745 subdirectory. Otherwise, the link will be the absolute path as
5746 completed in the minibuffer (i.e. normally ~/path/to/file).
5747
5748 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5749 is in the current directory or below."
5750 (interactive "P")
5751 (let ((link (if complete-file
5752 (read-file-name "File: ")
5753 (completing-read
5754 "Link: " org-stored-links nil nil nil
5755 org-insert-link-history
5756 (or (car (car org-stored-links))))))
5757 linktxt matched)
5758 (if (or (not link) (equal link ""))
5759 (error "No links available"))
5760 (if complete-file
5761 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5762 (cond
5763 ((equal complete-file '(16))
5764 (insert
5765 (org-make-link
5766 "file:" (abbreviate-file-name (expand-file-name link)))))
5767 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5768 (expand-file-name link))
5769 (insert
5770 (org-make-link
5771 "file:" (match-string 1 (expand-file-name link)))))
5772 (t (insert (org-make-link "file:" link)))))
5773 (setq linktxt (cdr (assoc link org-stored-links)))
5774 (if (not org-keep-stored-link-after-insertion)
5775 (setq org-stored-links (delq (assoc link org-stored-links)
5776 org-stored-links)))
5777 (if (not linktxt) (setq link (org-make-link link)))
5778 (let ((lines (org-split-string (or linktxt link) "\n")))
5779 (insert (car lines))
5780 (setq matched (string-match org-link-regexp (car lines)))
5781 (setq lines (cdr lines))
5782 (while lines
5783 (insert "\n")
5784 (if (save-excursion
5785 (beginning-of-line 0)
5786 (looking-at "[ \t]+\\S-"))
5787 (indent-relative))
5788 (setq matched (or matched
5789 (string-match org-link-regexp (car lines))))
5790 (insert (car lines))
5791 (setq lines (cdr lines))))
5792 (unless matched
5793 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5794
5795 ;;; Hooks for remember.el
5796 ;;;###autoload
5797 (defun org-remember-annotation ()
5798 "Return a link to the current location as an annotation for remember.el.
5799 If you are using Org-mode files as target for data storage with
5800 remember.el, then the annotations should include a link compatible with the
5801 conventions in Org-mode. This function returns such a link."
5802 (org-store-link nil))
5803
5804 (defconst org-remember-help
5805 "Select a destination location for the note.
5806 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5807 RET at beg-of-buf -> Append to file as level 2 headline
5808 RET on headline -> Store as sublevel entry to current headline
5809 <left>/<right> -> before/after current headline, same headings level")
5810
5811 ;;;###autoload
5812 (defun org-remember-handler ()
5813 "Store stuff from remember.el into an org file.
5814 First prompts for an org file. If the user just presses return, the value
5815 of `org-default-notes-file' is used.
5816 Then the command offers the headings tree of the selected file in order to
5817 file the text at a specific location.
5818 You can either immediately press RET to get the note appended to the
5819 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5820 find a better place. Then press RET or <left> or <right> in insert the note.
5821
5822 Key Cursor position Note gets inserted
5823 -----------------------------------------------------------------------------
5824 RET buffer-start as level 2 heading at end of file
5825 RET on headline as sublevel of the heading at cursor
5826 RET no heading at cursor position, level taken from context.
5827 Or use prefix arg to specify level manually.
5828 <left> on headline as same level, before current heading
5829 <right> on headline as same level, after current heading
5830
5831 So the fastest way to store the note is to press RET RET to append it to
5832 the default file. This way your current train of thought is not
5833 interrupted, in accordance with the principles of remember.el. But with
5834 little extra effort, you can push it directly to the correct location.
5835
5836 Before being stored away, the function ensures that the text has a
5837 headline, i.e. a first line that starts with a \"*\". If not, a headline
5838 is constructed from the current date and some additional data.
5839
5840 If the variable `org-adapt-indentation' is non-nil, the entire text is
5841 also indented so that it starts in the same column as the headline
5842 \(i.e. after the stars).
5843
5844 See also the variable `org-reverse-note-order'."
5845 (catch 'quit
5846 (let* ((txt (buffer-substring (point-min) (point-max)))
5847 (fastp current-prefix-arg)
5848 (file (if fastp org-default-notes-file (org-get-org-file)))
5849 (visiting (find-buffer-visiting file))
5850 (org-startup-with-deadline-check nil)
5851 (org-startup-folded nil)
5852 spos level indent reversed)
5853 ;; Modify text so that it becomes a nice subtree which can be inserted
5854 ;; into an org tree.
5855 (let* ((lines (split-string txt "\n"))
5856 (first (car lines))
5857 (lines (cdr lines)))
5858 (if (string-match "^\\*+" first)
5859 ;; Is already a headline
5860 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5861 -1) ?\ ))
5862 ;; We need to add a headline: Use time and first buffer line
5863 (setq lines (cons first lines)
5864 first (concat "* " (current-time-string)
5865 " (" (remember-buffer-desc) ")")
5866 indent " "))
5867 (if org-adapt-indentation
5868 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5869 (setq txt (concat first "\n"
5870 (mapconcat 'identity lines "\n"))))
5871 ;; Find the file
5872 (if (not visiting)
5873 (find-file-noselect file))
5874 (with-current-buffer (get-file-buffer file)
5875 (setq reversed (org-notes-order-reversed-p))
5876 (save-excursion
5877 (save-restriction
5878 (widen)
5879 ;; Ask the User for a location
5880 (setq spos (if fastp 1 (org-get-location
5881 (current-buffer)
5882 org-remember-help)))
5883 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5884 ; not handle this note
5885 (goto-char spos)
5886 (cond ((bobp)
5887 ;; Put it at the start or end, as level 2
5888 (save-restriction
5889 (widen)
5890 (goto-char (if reversed (point-min) (point-max)))
5891 (if (not (bolp)) (newline))
5892 (org-paste-subtree (or current-prefix-arg 2) txt)))
5893 ((and (org-on-heading-p nil) (not current-prefix-arg))
5894 ;; Put it below this entry, at the beg/end of the subtree
5895 (org-back-to-heading)
5896 (setq level (outline-level))
5897 (if reversed
5898 (outline-end-of-heading)
5899 (outline-end-of-subtree))
5900 (if (not (bolp)) (newline))
5901 (beginning-of-line 1)
5902 (org-paste-subtree (1+ level) txt))
5903 (t
5904 ;; Put it right there, with automatic level determined by
5905 ;; org-paste-subtree or from prefix arg
5906 (org-paste-subtree current-prefix-arg txt)))
5907 (when remember-save-after-remembering
5908 (save-buffer)
5909 (if (not visiting) (kill-buffer (current-buffer)))))))))
5910 t) ;; return t to indicate that we took care of this note.
5911
5912 (defun org-get-org-file ()
5913 "Read a filename, with default directory `org-directory'."
5914 (let ((default (or org-default-notes-file remember-data-file)))
5915 (read-file-name (format "File name [%s]: " default)
5916 (file-name-as-directory org-directory)
5917 default)))
5918
5919 (defun org-notes-order-reversed-p ()
5920 "Check if the current file should receive notes in reversed order."
5921 (cond
5922 ((not org-reverse-note-order) nil)
5923 ((eq t org-reverse-note-order) t)
5924 ((not (listp org-reverse-note-order)) nil)
5925 (t (catch 'exit
5926 (let ((all org-reverse-note-order)
5927 entry)
5928 (while (setq entry (pop all))
5929 (if (string-match (car entry) (buffer-file-name))
5930 (throw 'exit (cdr entry))))
5931 nil)))))
5932
5933 ;;; Tables
5934
5935 ;; Watch out: Here we are talking about two different kind of tables.
5936 ;; Most of the code is for the tables created with the Org-mode table editor.
5937 ;; Sometimes, we talk about tables created and edited with the table.el
5938 ;; Emacs package. We call the former org-type tables, and the latter
5939 ;; table.el-type tables.
5940
5941
5942 (defun org-before-change-function (beg end)
5943 "Every change indicates that a table might need an update."
5944 (setq org-table-may-need-update t))
5945
5946 (defconst org-table-line-regexp "^[ \t]*|"
5947 "Detects an org-type table line.")
5948 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5949 "Detects an org-type table line.")
5950 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5951 "Detects a table line marked for automatic recalculation.")
5952 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5953 "Detects a table line marked for automatic recalculation.")
5954 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5955 "Detects a table line marked for automatic recalculation.")
5956 (defconst org-table-hline-regexp "^[ \t]*|-"
5957 "Detects an org-type table hline.")
5958 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5959 "Detects a table-type table hline.")
5960 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5961 "Detects an org-type or table-type table.")
5962 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5963 "Searching from within a table (any type) this finds the first line
5964 outside the table.")
5965 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5966 "Searching from within a table (any type) this finds the first line
5967 outside the table.")
5968
5969 (defun org-table-create-with-table.el ()
5970 "Use the table.el package to insert a new table.
5971 If there is already a table at point, convert between Org-mode tables
5972 and table.el tables."
5973 (interactive)
5974 (require 'table)
5975 (cond
5976 ((org-at-table.el-p)
5977 (if (y-or-n-p "Convert table to Org-mode table? ")
5978 (org-table-convert)))
5979 ((org-at-table-p)
5980 (if (y-or-n-p "Convert table to table.el table? ")
5981 (org-table-convert)))
5982 (t (call-interactively 'table-insert))))
5983
5984 (defun org-table-create (&optional size)
5985 "Query for a size and insert a table skeleton.
5986 SIZE is a string Columns x Rows like for example \"3x2\"."
5987 (interactive "P")
5988 (unless size
5989 (setq size (read-string
5990 (concat "Table size Columns x Rows [e.g. "
5991 org-table-default-size "]: ")
5992 "" nil org-table-default-size)))
5993
5994 (let* ((pos (point))
5995 (indent (make-string (current-column) ?\ ))
5996 (split (org-split-string size " *x *"))
5997 (rows (string-to-number (nth 1 split)))
5998 (columns (string-to-number (car split)))
5999 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6000 "\n")))
6001 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6002 (point-at-bol) (point)))
6003 (beginning-of-line 1)
6004 (newline))
6005 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6006 (dotimes (i rows) (insert line))
6007 (goto-char pos)
6008 (if (> rows 1)
6009 ;; Insert a hline after the first row.
6010 (progn
6011 (end-of-line 1)
6012 (insert "\n|-")
6013 (goto-char pos)))
6014 (org-table-align)))
6015
6016 (defun org-table-convert-region (beg0 end0 nspace)
6017 "Convert region to a table.
6018 The region goes from BEG0 to END0, but these borders will be moved
6019 slightly, to make sure a beginning of line in the first line is included.
6020 When NSPACE is non-nil, it indicates the minimum number of spaces that
6021 separate columns (default: just one space)"
6022 (let* ((beg (min beg0 end0))
6023 (end (max beg0 end0))
6024 (tabsep t)
6025 re)
6026 (goto-char beg)
6027 (beginning-of-line 1)
6028 (setq beg (move-marker (make-marker) (point)))
6029 (goto-char end)
6030 (if (bolp) (backward-char 1) (end-of-line 1))
6031 (setq end (move-marker (make-marker) (point)))
6032 ;; Lets see if this is tab-separated material. If every nonempty line
6033 ;; contains a tab, we will assume that it is tab-separated material
6034 (if nspace
6035 (setq tabsep nil)
6036 (goto-char beg)
6037 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6038 (if nspace (setq tabsep nil))
6039 (if tabsep
6040 (setq re "^\\|\t")
6041 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6042 (max 1 (prefix-numeric-value nspace)))))
6043 (goto-char beg)
6044 (while (re-search-forward re end t)
6045 (replace-match "|" t t))
6046 (goto-char beg)
6047 (insert " ")
6048 (org-table-align)))
6049
6050 (defun org-table-import (file arg)
6051 "Import FILE as a table.
6052 The file is assumed to be tab-separated. Such files can be produced by most
6053 spreadsheet and database applications. If no tabs (at least one per line)
6054 are found, lines will be split on whitespace into fields."
6055 (interactive "f\nP")
6056 (or (bolp) (newline))
6057 (let ((beg (point))
6058 (pm (point-max)))
6059 (insert-file-contents file)
6060 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6061
6062 (defun org-table-export ()
6063 "Export table as a tab-separated file.
6064 Such a file can be imported into a spreadsheet program like Excel."
6065 (interactive)
6066 (let* ((beg (org-table-begin))
6067 (end (org-table-end))
6068 (table (buffer-substring beg end))
6069 (file (read-file-name "Export table to: "))
6070 buf)
6071 (unless (or (not (file-exists-p file))
6072 (y-or-n-p (format "Overwrite file %s? " file)))
6073 (error "Abort"))
6074 (with-current-buffer (find-file-noselect file)
6075 (setq buf (current-buffer))
6076 (erase-buffer)
6077 (fundamental-mode)
6078 (insert table)
6079 (goto-char (point-min))
6080 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6081 (replace-match "" t t)
6082 (end-of-line 1))
6083 (goto-char (point-min))
6084 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6085 (replace-match "" t t)
6086 (goto-char (min (1+ (point)) (point-max))))
6087 (goto-char (point-min))
6088 (while (re-search-forward "^-[-+]*$" nil t)
6089 (replace-match "")
6090 (if (looking-at "\n")
6091 (delete-char 1)))
6092 (goto-char (point-min))
6093 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6094 (replace-match "\t" t t))
6095 (save-buffer))
6096 (kill-buffer buf)))
6097
6098 (defvar org-table-aligned-begin-marker (make-marker)
6099 "Marker at the beginning of the table last aligned.
6100 Used to check if cursor still is in that table, to minimize realignment.")
6101 (defvar org-table-aligned-end-marker (make-marker)
6102 "Marker at the end of the table last aligned.
6103 Used to check if cursor still is in that table, to minimize realignment.")
6104 (defvar org-table-last-alignment nil
6105 "List of flags for flushright alignment, from the last re-alignment.
6106 This is being used to correctly align a single field after TAB or RET.")
6107 ;; FIXME: The following is currently not used.
6108 (defvar org-table-last-column-widths nil
6109 "List of max width of fields in each column.
6110 This is being used to correctly align a single field after TAB or RET.")
6111
6112 (defvar org-last-recalc-line nil)
6113
6114 (defun org-table-align ()
6115 "Align the table at point by aligning all vertical bars."
6116 (interactive)
6117 ;; (message "align") (sit-for 2)
6118 (let* (
6119 ;; Limits of table
6120 (beg (org-table-begin))
6121 (end (org-table-end))
6122 ;; Current cursor position
6123 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6124 (colpos (org-table-current-column))
6125 (winstart (window-start))
6126 text lines (new "") lengths l typenums ty fields maxfields i
6127 column
6128 (indent "") cnt frac
6129 rfmt hfmt
6130 (spaces (if (org-in-invisibility-spec-p '(org-table))
6131 org-table-spaces-around-invisible-separators
6132 org-table-spaces-around-separators))
6133 (sp1 (car spaces))
6134 (sp2 (cdr spaces))
6135 (rfmt1 (concat
6136 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6137 (hfmt1 (concat
6138 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6139 emptystrings)
6140 (untabify beg end)
6141 ;; (message "Aligning table...")
6142 ;; Get the rows
6143 (setq lines (org-split-string
6144 (buffer-substring-no-properties beg end) "\n"))
6145 ;; Store the indentation of the first line
6146 (if (string-match "^ *" (car lines))
6147 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6148 ;; Mark the hlines
6149 (setq lines (mapcar (lambda (l)
6150 (if (string-match "^ *|-" l)
6151 nil
6152 (if (string-match "[ \t]+$" l)
6153 (substring l 0 (match-beginning 0))
6154 l)))
6155 lines))
6156 ;; Get the data fields
6157 (setq fields (mapcar
6158 (lambda (l)
6159 (org-split-string l " *| *"))
6160 (delq nil (copy-sequence lines))))
6161 ;; How many fields in the longest line?
6162 (condition-case nil
6163 (setq maxfields (apply 'max (mapcar 'length fields)))
6164 (error
6165 (kill-region beg end)
6166 (org-table-create org-table-default-size)
6167 (error "Empty table - created default table")))
6168 ;; A list of empty string to fill any short rows on output
6169 (setq emptystrings (make-list maxfields ""))
6170 ;; Get the maximum length of a field and the most common datatype
6171 ;; for each column
6172 (setq i -1)
6173 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6174 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6175 ;; maximum length
6176 (push (apply 'max 1 (mapcar 'length column)) lengths)
6177 ;; compute the fraction stepwise, ignoring empty fields
6178 (setq cnt 0 frac 0.0)
6179 (mapcar
6180 (lambda (x)
6181 (if (equal x "")
6182 nil
6183 (setq frac ( / (+ (* frac cnt)
6184 (if (string-match org-table-number-regexp x) 1 0))
6185 (setq cnt (1+ cnt))))))
6186 column)
6187 (push (>= frac org-table-number-fraction) typenums))
6188 (setq lengths (nreverse lengths)
6189 typenums (nreverse typenums))
6190 (setq org-table-last-alignment typenums
6191 org-table-last-column-widths lengths)
6192 ;; Compute the formats needed for output of the table
6193 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6194 (while (setq l (pop lengths))
6195 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6196 (setq rfmt (concat rfmt (format rfmt1 ty l))
6197 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6198 (setq rfmt (concat rfmt "\n")
6199 hfmt (concat (substring hfmt 0 -1) "|\n"))
6200 ;; Produce the new table
6201 ;;(while lines
6202 ;; (setq l (pop lines))
6203 ;; (if l
6204 ;; (setq new (concat new (apply 'format rfmt
6205 ;; (append (pop fields) emptystrings))))
6206 ;; (setq new (concat new hfmt))))
6207 (setq new (mapconcat
6208 (lambda (l)
6209 (if l (apply 'format rfmt
6210 (append (pop fields) emptystrings))
6211 hfmt))
6212 lines ""))
6213 ;; Replace the old one
6214 (delete-region beg end)
6215 (move-marker end nil)
6216 (move-marker org-table-aligned-begin-marker (point))
6217 (insert new)
6218 (move-marker org-table-aligned-end-marker (point))
6219 ;; Try to move to the old location (approximately)
6220 (goto-line linepos)
6221 (set-window-start (selected-window) winstart 'noforce)
6222 (org-table-goto-column colpos)
6223 (setq org-table-may-need-update nil)
6224 (if (org-in-invisibility-spec-p '(org-table))
6225 (org-table-add-invisible-to-vertical-lines))
6226 ))
6227
6228 (defun org-table-begin (&optional table-type)
6229 "Find the beginning of the table and return its position.
6230 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6231 (save-excursion
6232 (if (not (re-search-backward
6233 (if table-type org-table-any-border-regexp
6234 org-table-border-regexp)
6235 nil t))
6236 (error "Can't find beginning of table")
6237 (goto-char (match-beginning 0))
6238 (beginning-of-line 2)
6239 (point))))
6240
6241 (defun org-table-end (&optional table-type)
6242 "Find the end of the table and return its position.
6243 With argument TABLE-TYPE, go to the end of a table.el-type table."
6244 (save-excursion
6245 (if (not (re-search-forward
6246 (if table-type org-table-any-border-regexp
6247 org-table-border-regexp)
6248 nil t))
6249 (goto-char (point-max))
6250 (goto-char (match-beginning 0)))
6251 (point-marker)))
6252
6253 (defun org-table-justify-field-maybe (&optional new)
6254 "Justify the current field, text to left, number to right.
6255 Optional argument NEW may specify text to replace the current field content."
6256 (cond
6257 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6258 ((org-at-table-hline-p)
6259 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6260 ;; (setq org-table-may-need-update t)
6261 )
6262 ((and (not new)
6263 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6264 (current-buffer)))
6265 (< (point) org-table-aligned-begin-marker)
6266 (>= (point) org-table-aligned-end-marker)))
6267 ;; This is not the same table, force a full re-align
6268 (setq org-table-may-need-update t))
6269 (t ;; realign the current field, based on previous full realign
6270 (let* ((pos (point)) s
6271 (col (org-table-current-column))
6272 (num (nth (1- col) org-table-last-alignment))
6273 l f n o e)
6274 (when (> col 0)
6275 (skip-chars-backward "^|\n")
6276 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6277 (progn
6278 (setq s (match-string 1)
6279 o (match-string 0)
6280 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6281 e (not (= (match-beginning 2) (match-end 2))))
6282 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6283 l (if e "|" (setq org-table-may-need-update t) ""))
6284 n (format f s t t))
6285 (if new
6286 (if (<= (length new) l)
6287 (setq n (format f new t t)) ;; FIXME: why t t?????
6288 (setq n (concat new "|") org-table-may-need-update t)))
6289 (or (equal n o)
6290 (let (org-table-may-need-update)
6291 (replace-match n))))
6292 (setq org-table-may-need-update t))
6293 (goto-char pos))))))
6294
6295 (defun org-table-next-field ()
6296 "Go to the next field in the current table.
6297 Before doing so, re-align the table if necessary."
6298 (interactive)
6299 (org-table-maybe-eval-formula)
6300 (org-table-maybe-recalculate-line)
6301 (if (and org-table-automatic-realign
6302 org-table-may-need-update)
6303 (org-table-align))
6304 (if (org-at-table-hline-p)
6305 (end-of-line 1))
6306 (condition-case nil
6307 (progn
6308 (re-search-forward "|" (org-table-end))
6309 (if (looking-at "[ \t]*$")
6310 (re-search-forward "|" (org-table-end)))
6311 (if (looking-at "-")
6312 (progn
6313 (beginning-of-line 0)
6314 (org-table-insert-row 'below))
6315 (if (looking-at " ") (forward-char 1))))
6316 (error
6317 (org-table-insert-row 'below))))
6318
6319 (defun org-table-previous-field ()
6320 "Go to the previous field in the table.
6321 Before doing so, re-align the table if necessary."
6322 (interactive)
6323 (org-table-justify-field-maybe)
6324 (org-table-maybe-recalculate-line)
6325 (if (and org-table-automatic-realign
6326 org-table-may-need-update)
6327 (org-table-align))
6328 (if (org-at-table-hline-p)
6329 (end-of-line 1))
6330 (re-search-backward "|" (org-table-begin))
6331 (re-search-backward "|" (org-table-begin))
6332 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6333 (re-search-backward "|" (org-table-begin)))
6334 (if (looking-at "| ?")
6335 (goto-char (match-end 0))))
6336
6337 (defun org-table-next-row ()
6338 "Go to the next row (same column) in the current table.
6339 Before doing so, re-align the table if necessary."
6340 (interactive)
6341 (org-table-maybe-eval-formula)
6342 (org-table-maybe-recalculate-line)
6343 (if (or (looking-at "[ \t]*$")
6344 (save-excursion (skip-chars-backward " \t") (bolp)))
6345 (newline)
6346 (if (and org-table-automatic-realign
6347 org-table-may-need-update)
6348 (org-table-align))
6349 (let ((col (org-table-current-column)))
6350 (beginning-of-line 2)
6351 (if (or (not (org-at-table-p))
6352 (org-at-table-hline-p))
6353 (progn
6354 (beginning-of-line 0)
6355 (org-table-insert-row 'below)))
6356 (org-table-goto-column col)
6357 (skip-chars-backward "^|\n\r")
6358 (if (looking-at " ") (forward-char 1)))))
6359
6360 (defun org-table-copy-down (n)
6361 "Copy a field down in the current column.
6362 If the field at the cursor is empty, copy into it the content of the nearest
6363 non-empty field above. With argument N, use the Nth non-empty field.
6364 If the current field is not empty, it is copied down to the next row, and
6365 the cursor is moved with it. Therefore, repeating this command causes the
6366 column to be filled row-by-row.
6367 If the variable `org-table-copy-increment' is non-nil and the field is an
6368 integer, it will be incremented while copying."
6369 (interactive "p")
6370 (let* ((colpos (org-table-current-column))
6371 (field (org-table-get-field))
6372 (non-empty (string-match "[^ \t]" field))
6373 (beg (org-table-begin))
6374 txt)
6375 (org-table-check-inside-data-field)
6376 (if non-empty
6377 (progn
6378 (setq txt (org-trim field))
6379 (org-table-next-row)
6380 (org-table-blank-field))
6381 (save-excursion
6382 (setq txt
6383 (catch 'exit
6384 (while (progn (beginning-of-line 1)
6385 (re-search-backward org-table-dataline-regexp
6386 beg t))
6387 (org-table-goto-column colpos t)
6388 (if (and (looking-at
6389 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6390 (= (setq n (1- n)) 0))
6391 (throw 'exit (match-string 1))))))))
6392 (if txt
6393 (progn
6394 (if (and org-table-copy-increment
6395 (string-match "^[0-9]+$" txt))
6396 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6397 (insert txt)
6398 (org-table-maybe-recalculate-line)
6399 (org-table-align))
6400 (error "No non-empty field found"))))
6401
6402 (defun org-table-check-inside-data-field ()
6403 "Is point inside a table data field?
6404 I.e. not on a hline or before the first or after the last column?
6405 This actually throws an error, so it aborts the current command."
6406 (if (or (not (org-at-table-p))
6407 (= (org-table-current-column) 0)
6408 (org-at-table-hline-p)
6409 (looking-at "[ \t]*$"))
6410 (error "Not in table data field")))
6411
6412 (defvar org-table-clip nil
6413 "Clipboard for table regions.")
6414
6415 (defun org-table-blank-field ()
6416 "Blank the current table field or active region."
6417 (interactive)
6418 (org-table-check-inside-data-field)
6419 (if (and (interactive-p) (org-region-active-p))
6420 (let (org-table-clip)
6421 (org-table-cut-region (region-beginning) (region-end)))
6422 (skip-chars-backward "^|")
6423 (backward-char 1)
6424 (if (looking-at "|[^|\n]+")
6425 (let* ((pos (match-beginning 0))
6426 (match (match-string 0))
6427 (len (length match)))
6428 (replace-match (concat "|" (make-string (1- len) ?\ )))
6429 (goto-char (+ 2 pos))
6430 (substring match 1)))))
6431
6432 (defun org-table-get-field (&optional n replace)
6433 "Return the value of the field in column N of current row.
6434 N defaults to current field.
6435 If REPLACE is a string, replace field with this value. The return value
6436 is always the old value."
6437 (and n (org-table-goto-column n))
6438 (skip-chars-backward "^|\n")
6439 (backward-char 1)
6440 (if (looking-at "|[^|\r\n]*")
6441 (let* ((pos (match-beginning 0))
6442 (val (buffer-substring (1+ pos) (match-end 0))))
6443 (if replace
6444 (replace-match (concat "|" replace)))
6445 (goto-char (min (point-at-eol) (+ 2 pos)))
6446 val)
6447 (forward-char 1) ""))
6448
6449 (defun org-table-current-column ()
6450 "Find out which column we are in.
6451 When called interactively, column is also displayed in echo area."
6452 (interactive)
6453 (if (interactive-p) (org-table-check-inside-data-field))
6454 (save-excursion
6455 (let ((cnt 0) (pos (point)))
6456 (beginning-of-line 1)
6457 (while (search-forward "|" pos t)
6458 (setq cnt (1+ cnt)))
6459 (if (interactive-p) (message "This is table column %d" cnt))
6460 cnt)))
6461
6462 (defun org-table-goto-column (n &optional on-delim force)
6463 "Move the cursor to the Nth column in the current table line.
6464 With optional argument ON-DELIM, stop with point before the left delimiter
6465 of the field.
6466 If there are less than N fields, just go to after the last delimiter.
6467 However, when FORCE is non-nil, create new columns if necessary."
6468 (let ((pos (point-at-eol)))
6469 (beginning-of-line 1)
6470 (when (> n 0)
6471 (while (and (> (setq n (1- n)) -1)
6472 (or (search-forward "|" pos t)
6473 (and force
6474 (progn (end-of-line 1)
6475 (skip-chars-backward "^|")
6476 (insert " | "))))))
6477 ; (backward-char 2) t)))))
6478 (when (and force (not (looking-at ".*|")))
6479 (save-excursion (end-of-line 1) (insert " | ")))
6480 (if on-delim
6481 (backward-char 1)
6482 (if (looking-at " ") (forward-char 1))))))
6483
6484 (defun org-at-table-p (&optional table-type)
6485 "Return t if the cursor is inside an org-type table.
6486 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6487 (if org-enable-table-editor
6488 (save-excursion
6489 (beginning-of-line 1)
6490 (looking-at (if table-type org-table-any-line-regexp
6491 org-table-line-regexp)))
6492 nil))
6493
6494 (defun org-table-recognize-table.el ()
6495 "If there is a table.el table nearby, recognize it and move into it."
6496 (if org-table-tab-recognizes-table.el
6497 (if (org-at-table.el-p)
6498 (progn
6499 (beginning-of-line 1)
6500 (if (looking-at org-table-dataline-regexp)
6501 nil
6502 (if (looking-at org-table1-hline-regexp)
6503 (progn
6504 (beginning-of-line 2)
6505 (if (looking-at org-table-any-border-regexp)
6506 (beginning-of-line -1)))))
6507 (if (re-search-forward "|" (org-table-end t) t)
6508 (progn
6509 (require 'table)
6510 (if (table--at-cell-p (point))
6511 t
6512 (message "recognizing table.el table...")
6513 (table-recognize-table)
6514 (message "recognizing table.el table...done")))
6515 (error "This should not happen..."))
6516 t)
6517 nil)
6518 nil))
6519
6520 (defun org-at-table.el-p ()
6521 "Return t if the cursor is inside a table.el-type table."
6522 (save-excursion
6523 (if (org-at-table-p 'any)
6524 (progn
6525 (goto-char (org-table-begin 'any))
6526 (looking-at org-table1-hline-regexp))
6527 nil)))
6528
6529 (defun org-at-table-hline-p ()
6530 "Return t if the cursor is inside a hline in a table."
6531 (if org-enable-table-editor
6532 (save-excursion
6533 (beginning-of-line 1)
6534 (looking-at org-table-hline-regexp))
6535 nil))
6536
6537 (defun org-table-insert-column ()
6538 "Insert a new column into the table."
6539 (interactive)
6540 (if (not (org-at-table-p))
6541 (error "Not at a table"))
6542 (org-table-find-dataline)
6543 (let* ((col (max 1 (org-table-current-column)))
6544 (beg (org-table-begin))
6545 (end (org-table-end))
6546 ;; Current cursor position
6547 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6548 (colpos col))
6549 (goto-char beg)
6550 (while (< (point) end)
6551 (if (org-at-table-hline-p)
6552 nil
6553 (org-table-goto-column col t)
6554 (insert "| "))
6555 (beginning-of-line 2))
6556 (move-marker end nil)
6557 (goto-line linepos)
6558 (org-table-goto-column colpos)
6559 (org-table-align)
6560 (org-table-modify-formulas 'insert col)))
6561
6562 (defun org-table-find-dataline ()
6563 "Find a dataline in the current table, which is needed for column commands."
6564 (if (and (org-at-table-p)
6565 (not (org-at-table-hline-p)))
6566 t
6567 (let ((col (current-column))
6568 (end (org-table-end)))
6569 (move-to-column col)
6570 (while (and (< (point) end)
6571 (or (not (= (current-column) col))
6572 (org-at-table-hline-p)))
6573 (beginning-of-line 2)
6574 (move-to-column col))
6575 (if (and (org-at-table-p)
6576 (not (org-at-table-hline-p)))
6577 t
6578 (error
6579 "Please position cursor in a data line for column operations")))))
6580
6581 (defun org-table-delete-column ()
6582 "Delete a column into the table."
6583 (interactive)
6584 (if (not (org-at-table-p))
6585 (error "Not at a table"))
6586 (org-table-find-dataline)
6587 (org-table-check-inside-data-field)
6588 (let* ((col (org-table-current-column))
6589 (beg (org-table-begin))
6590 (end (org-table-end))
6591 ;; Current cursor position
6592 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6593 (colpos col))
6594 (goto-char beg)
6595 (while (< (point) end)
6596 (if (org-at-table-hline-p)
6597 nil
6598 (org-table-goto-column col t)
6599 (and (looking-at "|[^|\n]+|")
6600 (replace-match "|")))
6601 (beginning-of-line 2))
6602 (move-marker end nil)
6603 (goto-line linepos)
6604 (org-table-goto-column colpos)
6605 (org-table-align)
6606 (org-table-modify-formulas 'remove col)))
6607
6608 (defun org-table-move-column-right ()
6609 "Move column to the right."
6610 (interactive)
6611 (org-table-move-column nil))
6612 (defun org-table-move-column-left ()
6613 "Move column to the left."
6614 (interactive)
6615 (org-table-move-column 'left))
6616
6617 (defun org-table-move-column (&optional left)
6618 "Move the current column to the right. With arg LEFT, move to the left."
6619 (interactive "P")
6620 (if (not (org-at-table-p))
6621 (error "Not at a table"))
6622 (org-table-find-dataline)
6623 (org-table-check-inside-data-field)
6624 (let* ((col (org-table-current-column))
6625 (col1 (if left (1- col) col))
6626 (beg (org-table-begin))
6627 (end (org-table-end))
6628 ;; Current cursor position
6629 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6630 (colpos (if left (1- col) (1+ col))))
6631 (if (and left (= col 1))
6632 (error "Cannot move column further left"))
6633 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6634 (error "Cannot move column further right"))
6635 (goto-char beg)
6636 (while (< (point) end)
6637 (if (org-at-table-hline-p)
6638 nil
6639 (org-table-goto-column col1 t)
6640 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6641 (replace-match "|\\2|\\1|")))
6642 (beginning-of-line 2))
6643 (move-marker end nil)
6644 (goto-line linepos)
6645 (org-table-goto-column colpos)
6646 (org-table-align)
6647 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6648
6649 (defun org-table-move-row-down ()
6650 "move table row down."
6651 (interactive)
6652 (org-table-move-row nil))
6653 (defun org-table-move-row-up ()
6654 "move table row up."
6655 (interactive)
6656 (org-table-move-row 'up))
6657
6658 (defun org-table-move-row (&optional up)
6659 "Move the current table line down. With arg UP, move it up."
6660 (interactive "P")
6661 (let ((col (current-column))
6662 (pos (point))
6663 (tonew (if up 0 2))
6664 txt)
6665 (beginning-of-line tonew)
6666 (if (not (org-at-table-p))
6667 (progn
6668 (goto-char pos)
6669 (error "Cannot move row further")))
6670 (goto-char pos)
6671 (beginning-of-line 1)
6672 (setq pos (point))
6673 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6674 (delete-region (point) (1+ (point-at-eol)))
6675 (beginning-of-line tonew)
6676 (insert txt)
6677 (beginning-of-line 0)
6678 (move-to-column col)))
6679
6680 (defun org-table-insert-row (&optional arg)
6681 "Insert a new row above the current line into the table.
6682 With prefix ARG, insert below the current line."
6683 (interactive "P")
6684 (if (not (org-at-table-p))
6685 (error "Not at a table"))
6686 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6687 new)
6688 (if (string-match "^[ \t]*|-" line)
6689 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6690 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6691 ;; Fix the first field if necessary
6692 (setq new (concat new))
6693 (if (string-match "^[ \t]*| *[#$] *|" line)
6694 (setq new (replace-match (match-string 0 line) t t new)))
6695 (beginning-of-line (if arg 2 1))
6696 (let (org-table-may-need-update)
6697 (insert-before-markers new)
6698 (insert-before-markers "\n"))
6699 (beginning-of-line 0)
6700 (re-search-forward "| ?" (point-at-eol) t)
6701 (and org-table-may-need-update (org-table-align))))
6702
6703 (defun org-table-insert-hline (&optional arg)
6704 "Insert a horizontal-line below the current line into the table.
6705 With prefix ARG, insert above the current line."
6706 (interactive "P")
6707 (if (not (org-at-table-p))
6708 (error "Not at a table"))
6709 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6710 (col (current-column))
6711 start)
6712 (if (string-match "^[ \t]*|-" line)
6713 (setq line
6714 (mapcar (lambda (x) (if (member x '(?| ?+))
6715 (prog1 (if start ?+ ?|) (setq start t))
6716 (if start ?- ?\ )))
6717 line))
6718 (setq line
6719 (mapcar (lambda (x) (if (equal x ?|)
6720 (prog1 (if start ?+ ?|) (setq start t))
6721 (if start ?- ?\ )))
6722 line)))
6723 (beginning-of-line (if arg 1 2))
6724 (apply 'insert line)
6725 (if (equal (char-before (point)) ?+)
6726 (progn (backward-delete-char 1) (insert "|")))
6727 (insert "\n")
6728 (beginning-of-line 0)
6729 (move-to-column col)))
6730
6731 (defun org-table-kill-row ()
6732 "Delete the current row or horizontal line from the table."
6733 (interactive)
6734 (if (not (org-at-table-p))
6735 (error "Not at a table"))
6736 (let ((col (current-column)))
6737 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6738 (if (not (org-at-table-p)) (beginning-of-line 0))
6739 (move-to-column col)))
6740
6741
6742 (defun org-table-cut-region (beg end)
6743 "Copy region in table to the clipboard and blank all relevant fields."
6744 (interactive "r")
6745 (org-table-copy-region beg end 'cut))
6746
6747 (defun org-table-copy-region (beg end &optional cut)
6748 "Copy rectangular region in table to clipboard.
6749 A special clipboard is used which can only be accessed
6750 with `org-table-paste-rectangle'"
6751 (interactive "rP")
6752 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6753 region cols
6754 (rpl (if cut " " nil)))
6755 (goto-char beg)
6756 (org-table-check-inside-data-field)
6757 (setq l01 (count-lines (point-min) (point))
6758 c01 (org-table-current-column))
6759 (goto-char end)
6760 (org-table-check-inside-data-field)
6761 (setq l02 (count-lines (point-min) (point))
6762 c02 (org-table-current-column))
6763 (setq l1 (min l01 l02) l2 (max l01 l02)
6764 c1 (min c01 c02) c2 (max c01 c02))
6765 (catch 'exit
6766 (while t
6767 (catch 'nextline
6768 (if (> l1 l2) (throw 'exit t))
6769 (goto-line l1)
6770 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6771 (setq cols nil ic1 c1 ic2 c2)
6772 (while (< ic1 (1+ ic2))
6773 (push (org-table-get-field ic1 rpl) cols)
6774 (setq ic1 (1+ ic1)))
6775 (push (nreverse cols) region)
6776 (setq l1 (1+ l1)))))
6777 (setq org-table-clip (nreverse region))
6778 (if cut (org-table-align))
6779 org-table-clip))
6780
6781 (defun org-table-paste-rectangle ()
6782 "Paste a rectangular region into a table.
6783 The upper right corner ends up in the current field. All involved fields
6784 will be overwritten. If the rectangle does not fit into the present table,
6785 the table is enlarged as needed. The process ignores horizontal separator
6786 lines."
6787 (interactive)
6788 (unless (and org-table-clip (listp org-table-clip))
6789 (error "First cut/copy a region to paste!"))
6790 (org-table-check-inside-data-field)
6791 (let* ((clip org-table-clip)
6792 (line (count-lines (point-min) (point)))
6793 (col (org-table-current-column))
6794 (org-enable-table-editor t)
6795 (org-table-automatic-realign nil)
6796 c cols field)
6797 (while (setq cols (pop clip))
6798 (while (org-at-table-hline-p) (beginning-of-line 2))
6799 (if (not (org-at-table-p))
6800 (progn (end-of-line 0) (org-table-next-field)))
6801 (setq c col)
6802 (while (setq field (pop cols))
6803 (org-table-goto-column c nil 'force)
6804 (org-table-get-field nil field)
6805 (setq c (1+ c)))
6806 (beginning-of-line 2))
6807 (goto-line line)
6808 (org-table-goto-column col)
6809 (org-table-align)))
6810
6811 (defun org-table-convert ()
6812 "Convert from `org-mode' table to table.el and back.
6813 Obviously, this only works within limits. When an Org-mode table is
6814 converted to table.el, all horizontal separator lines get lost, because
6815 table.el uses these as cell boundaries and has no notion of horizontal lines.
6816 A table.el table can be converted to an Org-mode table only if it does not
6817 do row or column spanning. Multiline cells will become multiple cells.
6818 Beware, Org-mode does not test if the table can be successfully converted - it
6819 blindly applies a recipe that works for simple tables."
6820 (interactive)
6821 (require 'table)
6822 (if (org-at-table.el-p)
6823 ;; convert to Org-mode table
6824 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6825 (end (move-marker (make-marker) (org-table-end t))))
6826 (table-unrecognize-region beg end)
6827 (goto-char beg)
6828 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6829 (replace-match ""))
6830 (goto-char beg))
6831 (if (org-at-table-p)
6832 ;; convert to table.el table
6833 (let ((beg (move-marker (make-marker) (org-table-begin)))
6834 (end (move-marker (make-marker) (org-table-end))))
6835 ;; first, get rid of all horizontal lines
6836 (goto-char beg)
6837 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6838 (replace-match ""))
6839 ;; insert a hline before first
6840 (goto-char beg)
6841 (org-table-insert-hline 'above)
6842 ;; insert a hline after each line
6843 (while (progn (beginning-of-line 2) (< (point) end))
6844 (org-table-insert-hline))
6845 (goto-char beg)
6846 (setq end (move-marker end (org-table-end)))
6847 ;; replace "+" at beginning and ending of hlines
6848 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6849 (replace-match "\\1+-"))
6850 (goto-char beg)
6851 (while (re-search-forward "-|[ \t]*$" end t)
6852 (replace-match "-+"))
6853 (goto-char beg)))))
6854
6855 (defun org-table-wrap-region (arg)
6856 "Wrap several fields in a column like a paragraph.
6857 This is useful if you'd like to spread the contents of a field over several
6858 lines, in order to keep the table compact.
6859
6860 If there is an active region, and both point and mark are in the same column,
6861 the text in the column is wrapped to minimum width for the given number of
6862 lines. Generally, this makes the table more compact. A prefix ARG may be
6863 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6864 formats the selected text to two lines. If the region was longer than 2
6865 lines, the remaining lines remain empty. A negative prefix argument reduces
6866 the current number of lines by that amount. The wrapped text is pasted back
6867 into the table. If you formatted it to more lines than it was before, fields
6868 further down in the table get overwritten - so you might need to make space in
6869 the table first.
6870
6871 If there is no region, the current field is split at the cursor position and
6872 the text fragment to the right of the cursor is prepended to the field one
6873 line down.
6874
6875 If there is no region, but you specify a prefix ARG, the current field gets
6876 blank, and the content is appended to the field above."
6877 (interactive "P")
6878 (org-table-check-inside-data-field)
6879 (if (org-region-active-p)
6880 ;; There is a region: fill as a paragraph
6881 (let ((beg (region-beginning))
6882 nlines)
6883 (org-table-cut-region (region-beginning) (region-end))
6884 (if (> (length (car org-table-clip)) 1)
6885 (error "Region must be limited to single column"))
6886 (setq nlines (if arg
6887 (if (< arg 1)
6888 (+ (length org-table-clip) arg)
6889 arg)
6890 (length org-table-clip)))
6891 (setq org-table-clip
6892 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6893 nil nlines)))
6894 (goto-char beg)
6895 (org-table-paste-rectangle))
6896 ;; No region, split the current field at point
6897 (if arg
6898 ;; combine with field above
6899 (let ((s (org-table-blank-field))
6900 (col (org-table-current-column)))
6901 (beginning-of-line 0)
6902 (while (org-at-table-hline-p) (beginning-of-line 0))
6903 (org-table-goto-column col)
6904 (skip-chars-forward "^|")
6905 (skip-chars-backward " ")
6906 (insert " " (org-trim s))
6907 (org-table-align))
6908 ;; split field
6909 (when (looking-at "\\([^|]+\\)+|")
6910 (let ((s (match-string 1)))
6911 (replace-match " |")
6912 (goto-char (match-beginning 0))
6913 (org-table-next-row)
6914 (insert (org-trim s) " ")
6915 (org-table-align))))))
6916
6917 (defun org-trim (s)
6918 "Remove whitespace at beginning and end of string."
6919 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6920 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6921 s)
6922
6923 (defun org-wrap (string &optional width lines)
6924 "Wrap string to either a number of lines, or a width in characters.
6925 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6926 that costs. If there is a word longer than WIDTH, the text is actually
6927 wrapped to the length of that word.
6928 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6929 many lines, whatever width that takes.
6930 The return value is a list of lines, without newlines at the end."
6931 (let* ((words (org-split-string string "[ \t\n]+"))
6932 (maxword (apply 'max (mapcar 'length words)))
6933 w ll)
6934 (cond (width
6935 (org-do-wrap words (max maxword width)))
6936 (lines
6937 (setq w maxword)
6938 (setq ll (org-do-wrap words maxword))
6939 (if (<= (length ll) lines)
6940 ll
6941 (setq ll words)
6942 (while (> (length ll) lines)
6943 (setq w (1+ w))
6944 (setq ll (org-do-wrap words w)))
6945 ll))
6946 (t (error "Cannot wrap this")))))
6947
6948
6949 (defun org-do-wrap (words width)
6950 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6951 (let (lines line)
6952 (while words
6953 (setq line (pop words))
6954 (while (and words (< (+ (length line) (length (car words))) width))
6955 (setq line (concat line " " (pop words))))
6956 (setq lines (push line lines)))
6957 (nreverse lines)))
6958
6959 ;; FIXME: I think I can make this more efficient
6960 (defun org-split-string (string &optional separators)
6961 "Splits STRING into substrings at SEPARATORS.
6962 No empty strings are returned if there are matches at the beginning
6963 and end of string."
6964 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6965 (start 0)
6966 notfirst
6967 (list nil))
6968 (while (and (string-match rexp string
6969 (if (and notfirst
6970 (= start (match-beginning 0))
6971 (< start (length string)))
6972 (1+ start) start))
6973 (< (match-beginning 0) (length string)))
6974 (setq notfirst t)
6975 (or (eq (match-beginning 0) 0)
6976 (and (eq (match-beginning 0) (match-end 0))
6977 (eq (match-beginning 0) start))
6978 (setq list
6979 (cons (substring string start (match-beginning 0))
6980 list)))
6981 (setq start (match-end 0)))
6982 (or (eq start (length string))
6983 (setq list
6984 (cons (substring string start)
6985 list)))
6986 (nreverse list)))
6987
6988 (defun org-table-add-invisible-to-vertical-lines ()
6989 "Add an `invisible' property to vertical lines of current table."
6990 (interactive)
6991 (let* ((beg (org-table-begin))
6992 (end (org-table-end))
6993 (end1))
6994 (save-excursion
6995 (goto-char beg)
6996 (while (< (point) end)
6997 (setq end1 (point-at-eol))
6998 (if (looking-at org-table-dataline-regexp)
6999 (while (re-search-forward "|" end1 t)
7000 (add-text-properties (1- (point)) (point)
7001 '(invisible org-table)))
7002 (while (re-search-forward "[+|]" end1 t)
7003 (add-text-properties (1- (point)) (point)
7004 '(invisible org-table))))
7005 (beginning-of-line 2)))))
7006
7007 (defun org-table-toggle-vline-visibility (&optional arg)
7008 "Toggle the visibility of table vertical lines.
7009 The effect is immediate and on all tables in the file.
7010 With prefix ARG, make lines invisible when ARG is positive, make lines
7011 visible when ARG is not positive"
7012 (interactive "P")
7013 (let ((action (cond
7014 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
7015 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
7016 (t (if (org-in-invisibility-spec-p '(org-table))
7017 'off
7018 'on)))))
7019 (if (eq action 'off)
7020 (progn
7021 (org-remove-from-invisibility-spec '(org-table))
7022 (org-table-map-tables 'org-table-align)
7023 (message "Vertical table lines visible")
7024 (if (org-at-table-p)
7025 (org-table-align)))
7026 (org-add-to-invisibility-spec '(org-table))
7027 (org-table-map-tables 'org-table-align)
7028 (message "Vertical table lines invisible"))
7029 (redraw-frame (selected-frame))))
7030
7031 (defun org-table-map-tables (function)
7032 "Apply FUNCTION to the start of all tables in the buffer."
7033 (save-excursion
7034 (save-restriction
7035 (widen)
7036 (goto-char (point-min))
7037 (while (re-search-forward org-table-any-line-regexp nil t)
7038 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7039 (beginning-of-line 1)
7040 (if (looking-at org-table-line-regexp)
7041 (save-excursion (funcall function)))
7042 (re-search-forward org-table-any-border-regexp nil 1)))))
7043
7044 (defun org-table-sum (&optional beg end nlast)
7045 "Sum numbers in region of current table column.
7046 The result will be displayed in the echo area, and will be available
7047 as kill to be inserted with \\[yank].
7048
7049 If there is an active region, it is interpreted as a rectangle and all
7050 numbers in that rectangle will be summed. If there is no active
7051 region and point is located in a table column, sum all numbers in that
7052 column.
7053
7054 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7055 numbers are assumed to be times as well (in decimal hours) and the
7056 numbers are added as such.
7057
7058 If NLAST is a number, only the NLAST fields will actually be summed."
7059 (interactive)
7060 (save-excursion
7061 (let (col (timecnt 0) diff h m s org-table-clip)
7062 (cond
7063 ((and beg end)) ; beg and end given explicitly
7064 ((org-region-active-p)
7065 (setq beg (region-beginning) end (region-end)))
7066 (t
7067 (setq col (org-table-current-column))
7068 (goto-char (org-table-begin))
7069 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7070 (error "No table data"))
7071 (org-table-goto-column col)
7072 ;not needed? (skip-chars-backward "^|")
7073 (setq beg (point))
7074 (goto-char (org-table-end))
7075 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7076 (error "No table data"))
7077 (org-table-goto-column col)
7078 ;not needed? (skip-chars-forward "^|")
7079 (setq end (point))))
7080 (let* ((items (apply 'append (org-table-copy-region beg end)))
7081 (items1 (cond ((not nlast) items)
7082 ((>= nlast (length items)) items)
7083 (t (setq items (reverse items))
7084 (setcdr (nthcdr (1- nlast) items) nil)
7085 (nreverse items))))
7086 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7087 items1)))
7088 (res (apply '+ numbers))
7089 (sres (if (= timecnt 0)
7090 (format "%g" res)
7091 (setq diff (* 3600 res)
7092 h (floor (/ diff 3600)) diff (mod diff 3600)
7093 m (floor (/ diff 60)) diff (mod diff 60)
7094 s diff)
7095 (format "%d:%02d:%02d" h m s))))
7096 (kill-new sres)
7097 (if (interactive-p)
7098 (message "%s"
7099 (substitute-command-keys
7100 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7101 (length numbers) sres))))
7102 sres))))
7103
7104 (defun org-table-get-number-for-summing (s)
7105 (let (n)
7106 (if (string-match "^ *|? *" s)
7107 (setq s (replace-match "" nil nil s)))
7108 (if (string-match " *|? *$" s)
7109 (setq s (replace-match "" nil nil s)))
7110 (setq n (string-to-number s))
7111 (cond
7112 ((and (string-match "0" s)
7113 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7114 ((string-match "\\`[ \t]+\\'" s) nil)
7115 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7116 (let ((h (string-to-number (or (match-string 1 s) "0")))
7117 (m (string-to-number (or (match-string 2 s) "0")))
7118 (s (string-to-number (or (match-string 4 s) "0"))))
7119 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7120 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7121 ((equal n 0) nil)
7122 (t n))))
7123
7124 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7125 "Get a calc vector from a column, accorting to desctiptor DESC.
7126 Optional arguments TBEG and COL can give the beginning of the table and
7127 the current column, to avoid unnecessary parsing."
7128 (save-excursion
7129 (or tbeg (setq tbeg (org-table-begin)))
7130 (or col (setq col (org-table-current-column)))
7131 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7132 (cond
7133 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7134 (setq n1 (- (match-end 1) (match-beginning 1)))
7135 (if (match-beginning 3)
7136 (setq n2 (- (match-end 2) (match-beginning 3))))
7137 (setq n (if n2 (max n1 n2) n1))
7138 (setq n1 (if n2 (min n1 n2)))
7139 (setq nn n)
7140 (while (and (> nn 0)
7141 (re-search-backward org-table-hline-regexp tbeg t))
7142 (push (org-current-line) hline-list)
7143 (setq nn (1- nn)))
7144 (setq hline-list (nreverse hline-list))
7145 (goto-line (nth (1- n) hline-list))
7146 (when (re-search-forward org-table-dataline-regexp)
7147 (org-table-goto-column col)
7148 (setq beg (point)))
7149 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7150 (when (re-search-backward org-table-dataline-regexp)
7151 (org-table-goto-column col)
7152 (setq end (point)))
7153 (setq l (apply 'append (org-table-copy-region beg end)))
7154 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7155 (if (equal x "") "0" x))
7156 l ",") "]"))
7157 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7158 (setq n1 (string-to-number (match-string 1 desc))
7159 n2 (string-to-number (match-string 2 desc)))
7160 (beginning-of-line 1)
7161 (save-excursion
7162 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7163 (org-table-goto-column col)
7164 (setq beg (point))))
7165 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7166 (org-table-goto-column col)
7167 (setq end (point)))
7168 (setq l (apply 'append (org-table-copy-region beg end)))
7169 (concat "[" (mapconcat
7170 (lambda (x) (setq x (org-trim x))
7171 (if (equal x "") "0" x))
7172 l ",") "]"))
7173 ((string-match "\\([0-9]+\\)" desc)
7174 (beginning-of-line 1)
7175 (when (re-search-backward org-table-dataline-regexp tbeg t
7176 (string-to-number (match-string 0 desc)))
7177 (org-table-goto-column col)
7178 (org-trim (org-table-get-field))))))))
7179
7180 (defvar org-table-formula-history nil)
7181
7182 (defvar org-table-column-names nil
7183 "Alist with column names, derived from the `!' line.")
7184 (defvar org-table-column-name-regexp nil
7185 "Regular expression matching the current column names.")
7186 (defvar org-table-local-parameters nil
7187 "Alist with parameter names, derived from the `$' line.")
7188 (defvar org-table-named-field-locations nil
7189 "Alist with locations of named fields.")
7190
7191 (defun org-table-get-formula (&optional equation named)
7192 "Read a formula from the minibuffer, offer stored formula as default."
7193 (let* ((name (car (rassoc (list (org-current-line)
7194 (org-table-current-column))
7195 org-table-named-field-locations)))
7196 (scol (if named
7197 (if name name
7198 (error "Not in a named field"))
7199 (int-to-string (org-table-current-column))))
7200 (dummy (and name (not named)
7201 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7202 (error "Abort")))
7203 (org-table-may-need-update nil)
7204 (stored-list (org-table-get-stored-formulas))
7205 (stored (cdr (assoc scol stored-list)))
7206 (eq (cond
7207 ((and stored equation (string-match "^ *=? *$" equation))
7208 stored)
7209 ((stringp equation)
7210 equation)
7211 (t (read-string
7212 (format "%s formula $%s=" (if named "Field" "Column") scol)
7213 (or stored "") 'org-table-formula-history
7214 ;stored
7215 ))))
7216 mustsave)
7217 (when (not (string-match "\\S-" eq))
7218 ;; remove formula
7219 (setq stored-list (delq (assoc scol stored-list) stored-list))
7220 (org-table-store-formulas stored-list)
7221 (error "Formula removed"))
7222 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7223 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7224 (if (and name (not named))
7225 ;; We set the column equation, delete the named one.
7226 (setq stored-list (delq (assoc name stored-list) stored-list)
7227 mustsave t))
7228 (if stored
7229 (setcdr (assoc scol stored-list) eq)
7230 (setq stored-list (cons (cons scol eq) stored-list)))
7231 (if (or mustsave (not (equal stored eq)))
7232 (org-table-store-formulas stored-list))
7233 eq))
7234
7235 (defun org-table-store-formulas (alist)
7236 "Store the list of formulas below the current table."
7237 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7238 (save-excursion
7239 (goto-char (org-table-end))
7240 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7241 (delete-region (point) (match-end 0)))
7242 (insert "#+TBLFM: "
7243 (mapconcat (lambda (x)
7244 (concat "$" (car x) "=" (cdr x)))
7245 alist "::")
7246 "\n")))
7247
7248 (defun org-table-get-stored-formulas ()
7249 "Return an alist with the t=stored formulas directly after current table."
7250 (interactive)
7251 (let (scol eq eq-alist strings string seen)
7252 (save-excursion
7253 (goto-char (org-table-end))
7254 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7255 (setq strings (org-split-string (match-string 2) " *:: *"))
7256 (while (setq string (pop strings))
7257 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7258 (setq scol (match-string 1 string)
7259 eq (match-string 2 string)
7260 eq-alist (cons (cons scol eq) eq-alist))
7261 (if (member scol seen)
7262 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7263 (push scol seen))))))
7264 (nreverse eq-alist)))
7265
7266 (defun org-table-modify-formulas (action &rest columns)
7267 "Modify the formulas stored below the current table.
7268 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7269 expected, for the other action only a single column number is needed."
7270 (let ((list (org-table-get-stored-formulas))
7271 (nmax (length (org-split-string
7272 (buffer-substring (point-at-bol) (point-at-eol))
7273 "|")))
7274 col col1 col2 scol si sc1 sc2)
7275 (cond
7276 ((null list)) ; No action needed if there are no stored formulas
7277 ((eq action 'remove)
7278 (setq col (car columns)
7279 scol (int-to-string col))
7280 (org-table-replace-in-formulas list scol "INVALID")
7281 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7282 (loop for i from (1+ col) upto nmax by 1 do
7283 (setq si (int-to-string i))
7284 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7285 (if (assoc si list) (setcar (assoc si list)
7286 (int-to-string (1- i))))))
7287 ((eq action 'insert)
7288 (setq col (car columns))
7289 (loop for i from nmax downto col 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 'swap)
7295 (setq col1 (car columns) col2 (nth 1 columns)
7296 sc1 (int-to-string col1) sc2 (int-to-string col2))
7297 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7298 (org-table-replace-in-formulas list sc1 "ZqZ")
7299 (org-table-replace-in-formulas list sc2 sc1)
7300 (org-table-replace-in-formulas list "ZqZ" sc2)
7301 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7302 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7303 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7304 (t (error "Invalid action in `org-table-modify-formulas'")))
7305 (if list (org-table-store-formulas list))))
7306
7307 (defun org-table-replace-in-formulas (list s1 s2)
7308 (let (elt re s)
7309 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7310 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7311 re (concat (regexp-quote s1) "\\>"))
7312 (while (setq elt (pop list))
7313 (setq s (cdr elt))
7314 (while (string-match re s)
7315 (setq s (replace-match s2 t t s)))
7316 (setcdr elt s))))
7317
7318 (defun org-table-get-specials ()
7319 "Get the column nmaes and local parameters for this table."
7320 (save-excursion
7321 (let ((beg (org-table-begin)) (end (org-table-end))
7322 names name fields fields1 field cnt c v line col)
7323 (setq org-table-column-names nil
7324 org-table-local-parameters nil
7325 org-table-named-field-locations nil)
7326 (goto-char beg)
7327 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7328 (setq names (org-split-string (match-string 1) " *| *")
7329 cnt 1)
7330 (while (setq name (pop names))
7331 (setq cnt (1+ cnt))
7332 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7333 (push (cons name (int-to-string cnt)) org-table-column-names))))
7334 (setq org-table-column-names (nreverse org-table-column-names))
7335 (setq org-table-column-name-regexp
7336 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7337 (goto-char beg)
7338 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7339 (setq fields (org-split-string (match-string 1) " *| *"))
7340 (while (setq field (pop fields))
7341 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7342 (push (cons (match-string 1 field) (match-string 2 field))
7343 org-table-local-parameters))))
7344 (goto-char beg)
7345 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7346 (setq c (match-string 1)
7347 fields (org-split-string (match-string 2) " *| *"))
7348 (save-excursion
7349 (beginning-of-line (if (equal c "_") 2 0))
7350 (setq line (org-current-line) col 1)
7351 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7352 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7353 (while (and fields1 (setq field (pop fields)))
7354 (setq v (pop fields1) col (1+ col))
7355 (when (and (stringp field) (stringp v)
7356 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7357 (push (cons field v) org-table-local-parameters)
7358 (push (list field line col) org-table-named-field-locations)))))))
7359
7360 (defun org-this-word ()
7361 ;; Get the current word
7362 (save-excursion
7363 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7364 (end (progn (skip-chars-forward "^ \t\n") (point))))
7365 (buffer-substring-no-properties beg end))))
7366
7367 (defun org-table-maybe-eval-formula ()
7368 "Check if the current field starts with \"=\" or \":=\".
7369 If yes, store the formula and apply it."
7370 ;; We already know we are in a table. Get field will only return a formula
7371 ;; when appropriate. It might return a separator line, but no problem.
7372 (when org-table-formula-evaluate-inline
7373 (let* ((field (org-trim (or (org-table-get-field) "")))
7374 named eq)
7375 (when (string-match "^:?=\\(.*\\)" field)
7376 (setq named (equal (string-to-char field) ?:)
7377 eq (match-string 1 field))
7378 (if (fboundp 'calc-eval)
7379 (org-table-eval-formula (if named '(4) nil) eq))))))
7380
7381 (defvar org-recalc-commands nil
7382 "List of commands triggering the reccalculation of a line.
7383 Will be filled automatically during use.")
7384
7385 (defvar org-recalc-marks
7386 '((" " . "Unmarked: no special line, no automatic recalculation")
7387 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7388 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7389 ("!" . "Column name definition line. Reference in formula as $name.")
7390 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7391 ("_" . "Names for values in row below this one.")
7392 ("^" . "Names for values in row above this one.")))
7393
7394 (defun org-table-rotate-recalc-marks (&optional newchar)
7395 "Rotate the recalculation mark in the first column.
7396 If in any row, the first field is not consistent with a mark,
7397 insert a new column for the makers.
7398 When there is an active region, change all the lines in the region,
7399 after prompting for the marking character.
7400 After each change, a message will be displayed indication the meaning
7401 of the new mark."
7402 (interactive)
7403 (unless (org-at-table-p) (error "Not at a table"))
7404 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7405 (beg (org-table-begin))
7406 (end (org-table-end))
7407 (l (org-current-line))
7408 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7409 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7410 (have-col
7411 (save-excursion
7412 (goto-char beg)
7413 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7414 (col (org-table-current-column))
7415 (forcenew (car (assoc newchar org-recalc-marks)))
7416 epos new)
7417 (when l1
7418 (message "Change region to what mark? Type # * ! $ or SPC: ")
7419 (setq newchar (char-to-string (read-char-exclusive))
7420 forcenew (car (assoc newchar org-recalc-marks))))
7421 (if (and newchar (not forcenew))
7422 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7423 newchar))
7424 (if l1 (goto-line l1))
7425 (save-excursion
7426 (beginning-of-line 1)
7427 (unless (looking-at org-table-dataline-regexp)
7428 (error "Not at a table data line")))
7429 (unless have-col
7430 (org-table-goto-column 1)
7431 (org-table-insert-column)
7432 (org-table-goto-column (1+ col)))
7433 (setq epos (point-at-eol))
7434 (save-excursion
7435 (beginning-of-line 1)
7436 (org-table-get-field
7437 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7438 (concat " "
7439 (setq new (or forcenew
7440 (cadr (member (match-string 1) marks))))
7441 " ")
7442 " # ")))
7443 (if (and l1 l2)
7444 (progn
7445 (goto-line l1)
7446 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7447 (and (looking-at org-table-dataline-regexp)
7448 (org-table-get-field 1 (concat " " new " "))))
7449 (goto-line l1)))
7450 (if (not (= epos (point-at-eol))) (org-table-align))
7451 (goto-line l)
7452 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7453
7454 (defun org-table-maybe-recalculate-line ()
7455 "Recompute the current line if marked for it, and if we haven't just done it."
7456 (interactive)
7457 (and org-table-allow-automatic-line-recalculation
7458 (not (and (memq last-command org-recalc-commands)
7459 (equal org-last-recalc-line (org-current-line))))
7460 (save-excursion (beginning-of-line 1)
7461 (looking-at org-table-auto-recalculate-regexp))
7462 (fboundp 'calc-eval)
7463 (org-table-recalculate) t))
7464
7465 (defvar org-table-formula-debug nil
7466 "Non-nil means, debug table formulas.
7467 When nil, simply write \"#ERROR\" in corrupted fields.")
7468
7469 (defvar modes)
7470 (defsubst org-set-calc-mode (var &optional value)
7471 (if (stringp var)
7472 (setq var (assoc var '(("D" calc-angle-mode deg)
7473 ("R" calc-angle-mode rad)
7474 ("F" calc-prefer-frac t)
7475 ("S" calc-symbolic-mode t)))
7476 value (nth 2 var) var (nth 1 var)))
7477 (if (memq var modes)
7478 (setcar (cdr (memq var modes)) value)
7479 (cons var (cons value modes)))
7480 modes)
7481
7482 (defun org-table-eval-formula (&optional arg equation
7483 suppress-align suppress-const
7484 suppress-store)
7485 "Replace the table field value at the cursor by the result of a calculation.
7486
7487 This function makes use of Dave Gillespie's calc package, in my view the
7488 most exciting program ever written for GNU Emacs. So you need to have calc
7489 installed in order to use this function.
7490
7491 In a table, this command replaces the value in the current field with the
7492 result of a formula. It also installes the formula as the \"current\" column
7493 formula, by storing it in a special line below the table. When called
7494 with a `C-u' prefix, the current field must ba a named field, and the
7495 formula is installed as valid in only this specific field.
7496
7497 When called, the command first prompts for a formula, which is read in
7498 the minibuffer. Previously entered formulas are available through the
7499 history list, and the last used formula is offered as a default.
7500 These stored formulas are adapted correctly when moving, inserting, or
7501 deleting columns with the corresponding commands.
7502
7503 The formula can be any algebraic expression understood by the calc package.
7504 For details, see the Org-mode manual.
7505
7506 This function can also be called from Lisp programs and offers
7507 additional Arguments: EQUATION can be the formula to apply. If this
7508 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7509 used to speed-up recursive calls by by-passing unnecessary aligns.
7510 SUPPRESS-CONST suppresses the interpretation of constants in the
7511 formula, assuming that this has been done already outside the fuction.
7512 SUPPRESS-STORE means the formula should not be stored, either because
7513 it is already stored, or because it is a modified equation that should
7514 not overwrite the stored one."
7515 (interactive "P")
7516 (require 'calc)
7517 (org-table-check-inside-data-field)
7518 (org-table-get-specials)
7519 (let* (fields
7520 (ndown (if (integerp arg) arg 1))
7521 (org-table-automatic-realign nil)
7522 (case-fold-search nil)
7523 (down (> ndown 1))
7524 (formula (if (and equation suppress-store)
7525 equation
7526 (org-table-get-formula equation (equal arg '(4)))))
7527 (n0 (org-table-current-column))
7528 (modes (copy-sequence org-calc-default-modes))
7529 n form fmt x ev orig c)
7530 ;; Parse the format string. Since we have a lot of modes, this is
7531 ;; a lot of work. However, I think calc still uses most of the time.
7532 (if (string-match ";" formula)
7533 (let ((tmp (org-split-string formula ";")))
7534 (setq formula (car tmp)
7535 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7536 (nth 1 tmp)))
7537 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7538 (setq c (string-to-char (match-string 1 fmt))
7539 n (string-to-number (or (match-string 1 fmt) "")))
7540 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7541 (setq modes (org-set-calc-mode
7542 'calc-float-format
7543 (list (cdr (assoc c '((?n. float) (?f. fix)
7544 (?s. sci) (?e. eng))))
7545 n))))
7546 (setq fmt (replace-match "" t t fmt)))
7547 (while (string-match "[DRFS]" fmt)
7548 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7549 (setq fmt (replace-match "" t t fmt)))
7550 (unless (string-match "\\S-" fmt)
7551 (setq fmt nil))))
7552 (if (and (not suppress-const) org-table-formula-use-constants)
7553 (setq formula (org-table-formula-substitute-names formula)))
7554 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7555 (while (> ndown 0)
7556 (setq fields (org-split-string
7557 (buffer-substring
7558 (point-at-bol) (point-at-eol)) " *| *"))
7559 (if org-table-formula-numbers-only
7560 (setq fields (mapcar
7561 (lambda (x) (number-to-string (string-to-number x)))
7562 fields)))
7563 (setq ndown (1- ndown))
7564 (setq form (copy-sequence formula))
7565 ;; Insert the references to fields in same row
7566 (while (string-match "\\$\\([0-9]+\\)?" form)
7567 (setq n (if (match-beginning 1)
7568 (string-to-number (match-string 1 form))
7569 n0)
7570 x (nth (1- n) fields))
7571 (unless x (error "Invalid field specifier \"%s\""
7572 (match-string 0 form)))
7573 (if (equal x "") (setq x "0"))
7574 (setq form (replace-match (concat "(" x ")") t t form)))
7575 ;; Insert ranges in current column
7576 (while (string-match "\\&[-I0-9]+" form)
7577 (setq form (replace-match
7578 (save-match-data
7579 (org-table-get-vertical-vector (match-string 0 form)
7580 nil n0))
7581 t t form)))
7582 (setq ev (calc-eval (cons form modes)
7583 (if org-table-formula-numbers-only 'num)))
7584
7585 (when org-table-formula-debug
7586 (with-output-to-temp-buffer "*Help*"
7587 (princ (format "Substitution history of formula
7588 Orig: %s
7589 $xyz-> %s
7590 $1-> %s\n" orig formula form))
7591 (if (listp ev)
7592 (princ (format " %s^\nError: %s"
7593 (make-string (car ev) ?\-) (nth 1 ev)))
7594 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7595 ev (or fmt "NONE")
7596 (if fmt (format fmt (string-to-number ev)) ev)))))
7597 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7598 (unless (and (interactive-p) (not ndown))
7599 (unless (let (inhibit-redisplay)
7600 (y-or-n-p "Debugging Formula. Continue to next? "))
7601 (org-table-align)
7602 (error "Abort"))
7603 (delete-window (get-buffer-window "*Help*"))
7604 (message "")))
7605 (if (listp ev) (setq fmt nil ev "#ERROR"))
7606 (org-table-justify-field-maybe
7607 (if fmt (format fmt (string-to-number ev)) ev))
7608 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7609 (call-interactively 'org-return)
7610 (setq ndown 0)))
7611 (and down (org-table-maybe-recalculate-line))
7612 (or suppress-align (and org-table-may-need-update
7613 (org-table-align)))))
7614
7615 (defun org-table-recalculate (&optional all noalign)
7616 "Recalculate the current table line by applying all stored formulas."
7617 (interactive "P")
7618 (or (memq this-command org-recalc-commands)
7619 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7620 (unless (org-at-table-p) (error "Not at a table"))
7621 (org-table-get-specials)
7622 (let* ((eqlist (sort (org-table-get-stored-formulas)
7623 (lambda (a b) (string< (car a) (car b)))))
7624 (inhibit-redisplay t)
7625 (line-re org-table-dataline-regexp)
7626 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7627 (thiscol (org-table-current-column))
7628 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7629 ;; Insert constants in all formulas
7630 (setq eqlist
7631 (mapcar (lambda (x)
7632 (setcdr x (org-table-formula-substitute-names (cdr x)))
7633 x)
7634 eqlist))
7635 ;; Split the equation list
7636 (while (setq eq (pop eqlist))
7637 (if (<= (string-to-char (car eq)) ?9)
7638 (push eq eqlnum)
7639 (push eq eqlname)))
7640 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7641 (if all
7642 (progn
7643 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7644 (goto-char (setq beg (org-table-begin)))
7645 (if (re-search-forward org-table-calculate-mark-regexp end t)
7646 ;; This is a table with marked lines, only compute selected lines
7647 (setq line-re org-table-recalculate-regexp)
7648 ;; Move forward to the first non-header line
7649 (if (and (re-search-forward org-table-dataline-regexp end t)
7650 (re-search-forward org-table-hline-regexp end t)
7651 (re-search-forward org-table-dataline-regexp end t))
7652 (setq beg (match-beginning 0))
7653 nil))) ;; just leave beg where it is
7654 (setq beg (point-at-bol)
7655 end (move-marker (make-marker) (1+ (point-at-eol)))))
7656 (goto-char beg)
7657 (and all (message "Re-applying formulas to full table..."))
7658 (while (re-search-forward line-re end t)
7659 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7660 ;; Unprotected line, recalculate
7661 (and all (message "Re-applying formulas to full table...(line %d)"
7662 (setq cnt (1+ cnt))))
7663 (setq org-last-recalc-line (org-current-line))
7664 (setq eql eqlnum)
7665 (while (setq entry (pop eql))
7666 (goto-line org-last-recalc-line)
7667 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7668 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7669 (goto-line thisline)
7670 (org-table-goto-column thiscol)
7671 (or noalign (and org-table-may-need-update (org-table-align))
7672 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7673 ;; Now do the names fields
7674 (while (setq eq (pop eqlname))
7675 (setq name (car eq)
7676 a (assoc name org-table-named-field-locations))
7677 (when a
7678 (message "Re-applying formula to named field: %s" name)
7679 (goto-line (nth 1 a))
7680 (org-table-goto-column (nth 2 a))
7681 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7682 ;; back to initial position
7683 (goto-line thisline)
7684 (org-table-goto-column thiscol)
7685 (or noalign (and org-table-may-need-update (org-table-align))
7686 (and all (message "Re-applying formulas...done")))))
7687
7688 (defun org-table-formula-substitute-names (f)
7689 "Replace $const with values in string F."
7690 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7691 ;; First, check for column names
7692 (while (setq start (string-match org-table-column-name-regexp f start))
7693 (setq start (1+ start))
7694 (setq a (assoc (match-string 1 f) org-table-column-names))
7695 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7696 ;; Expand ranges to vectors
7697 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7698 (setq n1 (string-to-number (match-string 1 f))
7699 n2 (string-to-number (match-string 2 f))
7700 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7701 s (concat "[($" (number-to-string (1- nn1)) ")"))
7702 (loop for i from nn1 upto nn2 do
7703 (setq s (concat s ",($" (int-to-string i) ")")))
7704 (setq s (concat s "]"))
7705 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7706 (setq f (replace-match s t t f)))
7707 ;; Parameters and constants
7708 (setq start 0)
7709 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7710 (setq start (1+ start))
7711 (if (setq a (save-match-data
7712 (org-table-get-constant (match-string 1 f))))
7713 (setq f (replace-match (concat "(" a ")") t t f))))
7714 (if org-table-formula-debug
7715 (put-text-property 0 (length f) :orig-formula f1 f))
7716 f))
7717
7718 (defun org-table-get-constant (const)
7719 "Find the value for a parameter or constant in a formula.
7720 Parameters get priority."
7721 (or (cdr (assoc const org-table-local-parameters))
7722 (cdr (assoc const org-table-formula-constants))
7723 (and (fboundp 'constants-get) (constants-get const))
7724 "#UNDEFINED_NAME"))
7725
7726 (defvar org-edit-formulas-map (make-sparse-keymap))
7727 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7728 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7729 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7730
7731 (defvar org-pos)
7732 (defvar org-window-configuration)
7733
7734 (defun org-table-edit-formulas ()
7735 "Edit the formulas of the current table in a separate buffer."
7736 (interactive)
7737 (unless (org-at-table-p)
7738 (error "Not at a table"))
7739 (org-table-get-specials)
7740 (let ((eql (org-table-get-stored-formulas))
7741 (pos (move-marker (make-marker) (point)))
7742 (wc (current-window-configuration))
7743 entry loc s)
7744 (switch-to-buffer-other-window "*Edit Formulas*")
7745 (erase-buffer)
7746 (fundamental-mode)
7747 (set (make-local-variable 'org-pos) pos)
7748 (set (make-local-variable 'org-window-configuration) wc)
7749 (use-local-map org-edit-formulas-map)
7750 (setq s "# Edit formulas and finish with `C-c C-c'.
7751 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7752 # Use `C-c ?' to get information about $name at point.
7753 # To cancel editing, press `C-c C-q'.\n")
7754 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7755 (insert s)
7756 (while (setq entry (pop eql))
7757 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7758 (setq s (format "# Named formula, referring to column %d in line %d\n"
7759 (nth 2 loc) (nth 1 loc)))
7760 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7761 (insert s))
7762 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7763 (remove-text-properties 0 (length s) '(face nil) s)
7764 (insert s))
7765 (goto-char (point-min))
7766 (message "Edit formulas and finish with `C-c C-c'.")))
7767
7768 (defun org-show-variable ()
7769 "Show the location/value of the $ expression at point."
7770 (interactive)
7771 (let (var (pos org-pos) (win (selected-window)) e)
7772 (save-excursion
7773 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7774 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7775 (setq var (match-string 1))
7776 (error "No variable at point")))
7777 (cond
7778 ((setq e (assoc var org-table-named-field-locations))
7779 (switch-to-buffer-other-window (marker-buffer pos))
7780 (goto-line (nth 1 e))
7781 (org-table-goto-column (nth 2 e))
7782 (select-window win)
7783 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7784 ((setq e (assoc var org-table-column-names))
7785 (switch-to-buffer-other-window (marker-buffer pos))
7786 (goto-char pos)
7787 (goto-char (org-table-begin))
7788 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7789 (org-table-end) t)
7790 (progn
7791 (goto-char (match-beginning 1))
7792 (message "Named column (column %s)" (cdr e)))
7793 (error "Column name not found"))
7794 (select-window win))
7795 ((string-match "^[0-9]$" var)
7796 ;; column number
7797 (switch-to-buffer-other-window (marker-buffer pos))
7798 (goto-char pos)
7799 (goto-char (org-table-begin))
7800 (recenter 1)
7801 (if (re-search-forward org-table-dataline-regexp
7802 (org-table-end) t)
7803 (progn
7804 (goto-char (match-beginning 0))
7805 (org-table-goto-column (string-to-number var))
7806 (message "Column %s" var))
7807 (error "Column name not found"))
7808 (select-window win))
7809 ((setq e (assoc var org-table-local-parameters))
7810 (switch-to-buffer-other-window (marker-buffer pos))
7811 (goto-char pos)
7812 (goto-char (org-table-begin))
7813 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7814 (progn
7815 (goto-char (match-beginning 1))
7816 (message "Local parameter."))
7817 (error "Parameter not found"))
7818 (select-window win))
7819 (t
7820 (cond
7821 ((setq e (assoc var org-table-formula-constants))
7822 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7823 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7824 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7825 (t (error "Undefined name $%s" var)))))))
7826
7827 (defun org-finish-edit-formulas (&optional arg)
7828 "Parse the buffer for formula definitions and install them.
7829 With prefix ARG, apply the new formulas to the table."
7830 (interactive "P")
7831 (let ((pos org-pos) eql)
7832 (goto-char (point-min))
7833 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7834 (push (cons (match-string 1) (match-string 2)) eql))
7835 (set-window-configuration org-window-configuration)
7836 (select-window (get-buffer-window (marker-buffer pos)))
7837 (goto-char pos)
7838 (unless (org-at-table-p)
7839 (error "Lost table position - cannot install formulae"))
7840 (org-table-store-formulas eql)
7841 (move-marker pos nil)
7842 (kill-buffer "*Edit Formulas*")
7843 (if arg
7844 (org-table-recalculate 'all)
7845 (message "New formulas installed - press C-u C-c C-c to apply."))))
7846
7847 (defun org-abort-edit-formulas ()
7848 "Abort editing formulas, without installing the changes."
7849 (interactive)
7850 (let ((pos org-pos))
7851 (set-window-configuration org-window-configuration)
7852 (select-window (get-buffer-window (marker-buffer pos)))
7853 (goto-char pos)
7854 (message "Formula editing aborted without installing changes")))
7855
7856 ;;; The orgtbl minor mode
7857
7858 ;; Define a minor mode which can be used in other modes in order to
7859 ;; integrate the org-mode table editor.
7860
7861 ;; This is really a hack, because the org-mode table editor uses several
7862 ;; keys which normally belong to the major mode, for example the TAB and
7863 ;; RET keys. Here is how it works: The minor mode defines all the keys
7864 ;; necessary to operate the table editor, but wraps the commands into a
7865 ;; function which tests if the cursor is currently inside a table. If that
7866 ;; is the case, the table editor command is executed. However, when any of
7867 ;; those keys is used outside a table, the function uses `key-binding' to
7868 ;; look up if the key has an associated command in another currently active
7869 ;; keymap (minor modes, major mode, global), and executes that command.
7870 ;; There might be problems if any of the keys used by the table editor is
7871 ;; otherwise used as a prefix key.
7872
7873 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7874 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7875 ;; addresses this by checking explicitly for both bindings.
7876
7877 ;; The optimized version (see variable `orgtbl-optimized') takes over
7878 ;; all keys which are bound to `self-insert-command' in the *global map*.
7879 ;; Some modes bind other commands to simple characters, for example
7880 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7881 ;; active, this binding is ignored inside tables and replaced with a
7882 ;; modified self-insert.
7883
7884 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7885 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7886 In the optimized version, the table editor takes over all simple keys that
7887 normally just insert a character. In tables, the characters are inserted
7888 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7889 for empty fields). Outside tables, the correct binding of the keys is
7890 restored.
7891
7892 The default for this option is t if the optimized version is also used in
7893 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7894 this variable requires a restart of Emacs to become effective."
7895 :group 'org-table
7896 :type 'boolean)
7897
7898 (defvar orgtbl-mode nil
7899 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7900 table editor in arbitrary modes.")
7901 (make-variable-buffer-local 'orgtbl-mode)
7902
7903 (defvar orgtbl-mode-map (make-keymap)
7904 "Keymap for `orgtbl-mode'.")
7905
7906 ;;;###autoload
7907 (defun turn-on-orgtbl ()
7908 "Unconditionally turn on `orgtbl-mode'."
7909 (orgtbl-mode 1))
7910
7911 ;;;###autoload
7912 (defun orgtbl-mode (&optional arg)
7913 "The `org-mode' table editor as a minor mode for use in other modes."
7914 (interactive)
7915 (if (eq major-mode 'org-mode)
7916 ;; Exit without error, in case some hook functions calls this
7917 ;; by accident in org-mode.
7918 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7919 (setq orgtbl-mode
7920 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7921 (if orgtbl-mode
7922 (progn
7923 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7924 ;; Make sure we are first in minor-mode-map-alist
7925 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7926 (and c (setq minor-mode-map-alist
7927 (cons c (delq c minor-mode-map-alist)))))
7928 (set (make-local-variable (quote org-table-may-need-update)) t)
7929 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
7930 (add-hook 'before-change-functions 'org-before-change-function
7931 nil 'local)
7932 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7933 auto-fill-inhibit-regexp)
7934 (set (make-local-variable 'auto-fill-inhibit-regexp)
7935 (if auto-fill-inhibit-regexp
7936 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7937 "[ \t]*|"))
7938 (easy-menu-add orgtbl-mode-menu)
7939 (run-hooks 'orgtbl-mode-hook))
7940 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7941 (remove-hook 'before-change-functions 'org-before-change-function t)
7942 (easy-menu-remove orgtbl-mode-menu)
7943 (force-mode-line-update 'all))))
7944
7945 ;; Install it as a minor mode.
7946 (put 'orgtbl-mode :included t)
7947 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7948 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7949
7950 (defun orgtbl-make-binding (fun n &rest keys)
7951 "Create a function for binding in the table minor mode.
7952 FUN is the command to call inside a table. N is used to create a unique
7953 command name. KEYS are keys that should be checked in for a command
7954 to execute outside of tables."
7955 (eval
7956 (list 'defun
7957 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7958 '(arg)
7959 (concat "In tables, run `" (symbol-name fun) "'.\n"
7960 "Outside of tables, run the binding of `"
7961 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7962 "'.")
7963 '(interactive "p")
7964 (list 'if
7965 '(org-at-table-p)
7966 (list 'call-interactively (list 'quote fun))
7967 (list 'let '(orgtbl-mode)
7968 (list 'call-interactively
7969 (append '(or)
7970 (mapcar (lambda (k)
7971 (list 'key-binding k))
7972 keys)
7973 '('orgtbl-error))))))))
7974
7975 (defun orgtbl-error ()
7976 "Error when there is no default binding for a table key."
7977 (interactive)
7978 (error "This key is has no function outside tables"))
7979
7980 (defun orgtbl-setup ()
7981 "Setup orgtbl keymaps."
7982 (let ((nfunc 0)
7983 (bindings
7984 (list
7985 '([(meta shift left)] org-table-delete-column)
7986 '([(meta left)] org-table-move-column-left)
7987 '([(meta right)] org-table-move-column-right)
7988 '([(meta shift right)] org-table-insert-column)
7989 '([(meta shift up)] org-table-kill-row)
7990 '([(meta shift down)] org-table-insert-row)
7991 '([(meta up)] org-table-move-row-up)
7992 '([(meta down)] org-table-move-row-down)
7993 '("\C-c\C-w" org-table-cut-region)
7994 '("\C-c\M-w" org-table-copy-region)
7995 '("\C-c\C-y" org-table-paste-rectangle)
7996 '("\C-c-" org-table-insert-hline)
7997 ; '([(shift tab)] org-table-previous-field)
7998 '("\C-m" org-table-next-row)
7999 (list (org-key 'S-return) 'org-table-copy-down)
8000 '([(meta return)] org-table-wrap-region)
8001 '("\C-c\C-q" org-table-wrap-region)
8002 '("\C-c?" org-table-current-column)
8003 '("\C-c " org-table-blank-field)
8004 '("\C-c+" org-table-sum)
8005 '("\C-c|" org-table-toggle-vline-visibility)
8006 '("\C-c=" org-table-eval-formula)
8007 '("\C-c'" org-table-edit-formulas)
8008 '("\C-c*" org-table-recalculate)
8009 '([(control ?#)] org-table-rotate-recalc-marks)))
8010 elt key fun cmd)
8011 (while (setq elt (pop bindings))
8012 (setq nfunc (1+ nfunc))
8013 (setq key (car elt)
8014 fun (nth 1 elt)
8015 cmd (orgtbl-make-binding fun nfunc key))
8016 (define-key orgtbl-mode-map key cmd))
8017 ;; Special treatment needed for TAB and RET
8018 (define-key orgtbl-mode-map [(return)]
8019 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8020 (define-key orgtbl-mode-map "\C-m"
8021 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8022 (define-key orgtbl-mode-map [(tab)]
8023 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8024 (define-key orgtbl-mode-map "\C-i"
8025 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
8026 (define-key orgtbl-mode-map "\C-i"
8027 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8028 (define-key orgtbl-mode-map "\C-c\C-c"
8029 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8030 (when orgtbl-optimized
8031 ;; If the user wants maximum table support, we need to hijack
8032 ;; some standard editing functions
8033 (org-remap orgtbl-mode-map
8034 'self-insert-command 'orgtbl-self-insert-command
8035 'delete-char 'orgtbl-delete-char
8036 'delete-backward-char 'orgtbl-delete-backward-char)
8037 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8038 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8039 '("OrgTbl"
8040 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8041 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8042 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8043 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8044 "--"
8045 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8046 ["Copy Field from Above"
8047 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8048 "--"
8049 ("Column"
8050 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8051 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8052 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8053 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8054 ("Row"
8055 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8056 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8057 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8058 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8059 "--"
8060 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8061 ("Rectangle"
8062 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8063 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8064 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8065 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8066 "--"
8067 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8068 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8069 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8070 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8071 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8072 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8073 ["Sum Column/Rectangle" org-table-sum
8074 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8075 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8076 ["Debug Formulas"
8077 (setq org-table-formula-debug (not org-table-formula-debug))
8078 :style toggle :selected org-table-formula-debug]
8079 ))
8080 t)
8081
8082 (defun orgtbl-tab ()
8083 "Justification and field motion for `orgtbl-mode'."
8084 (interactive)
8085 (org-table-justify-field-maybe)
8086 (org-table-next-field))
8087
8088 (defun orgtbl-ret ()
8089 "Justification and field motion for `orgtbl-mode'."
8090 (interactive)
8091 (org-table-justify-field-maybe)
8092 (org-table-next-row))
8093
8094 (defun orgtbl-self-insert-command (N)
8095 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8096 If the cursor is in a table looking at whitespace, the whitespace is
8097 overwritten, and the table is not marked as requiring realignment."
8098 (interactive "p")
8099 (if (and (org-at-table-p)
8100 (or
8101 (and org-table-auto-blank-field
8102 (member last-command
8103 '(orgtbl-hijacker-command-100
8104 orgtbl-hijacker-command-101
8105 orgtbl-hijacker-command-102
8106 orgtbl-hijacker-command-103
8107 orgtbl-hijacker-command-104
8108 orgtbl-hijacker-command-105))
8109 (org-table-blank-field))
8110 t)
8111 (eq N 1)
8112 (looking-at "[^|\n]* +|"))
8113 (let (org-table-may-need-update)
8114 (goto-char (1- (match-end 0)))
8115 (delete-backward-char 1)
8116 (goto-char (match-beginning 0))
8117 (self-insert-command N))
8118 (setq org-table-may-need-update t)
8119 (let (orgtbl-mode)
8120 (call-interactively (key-binding (vector last-input-event))))))
8121
8122 (defun org-force-self-insert (N)
8123 "Needed to enforce self-insert under remapping."
8124 (interactive "p")
8125 (self-insert-command N))
8126
8127 (defun orgtbl-delete-backward-char (N)
8128 "Like `delete-backward-char', insert whitespace at field end in tables.
8129 When deleting backwards, in tables this function will insert whitespace in
8130 front of the next \"|\" separator, to keep the table aligned. The table will
8131 still be marked for re-alignment, because a narrow field may lead to a
8132 reduced column width."
8133 (interactive "p")
8134 (if (and (org-at-table-p)
8135 (eq N 1)
8136 (string-match "|" (buffer-substring (point-at-bol) (point)))
8137 (looking-at ".*?|"))
8138 (let ((pos (point)))
8139 (backward-delete-char N)
8140 (skip-chars-forward "^|")
8141 (insert " ")
8142 (goto-char (1- pos)))
8143 (delete-backward-char N)))
8144
8145 (defun orgtbl-delete-char (N)
8146 "Like `delete-char', but insert whitespace at field end in tables.
8147 When deleting characters, in tables this function will insert whitespace in
8148 front of the next \"|\" separator, to keep the table aligned. The table
8149 will still be marked for re-alignment, because a narrow field may lead to
8150 a reduced column width."
8151 (interactive "p")
8152 (if (and (org-at-table-p)
8153 (not (bolp))
8154 (not (= (char-after) ?|))
8155 (eq N 1))
8156 (if (looking-at ".*?|")
8157 (let ((pos (point)))
8158 (replace-match (concat
8159 (substring (match-string 0) 1 -1)
8160 " |"))
8161 (goto-char pos)))
8162 (delete-char N)))
8163
8164 ;;; Exporting
8165
8166 (defconst org-level-max 20)
8167
8168 (defun org-export-find-first-heading-line (list)
8169 "Remove all lines from LIST which are before the first headline."
8170 (let ((orig-list list)
8171 (re (concat "^" outline-regexp)))
8172 (while (and list
8173 (not (string-match re (car list))))
8174 (pop list))
8175 (or list orig-list)))
8176
8177 (defun org-skip-comments (lines)
8178 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8179 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8180 (re2 "^\\(\\*+\\)[ \t\n\r]")
8181 rtn line level)
8182 (while (setq line (pop lines))
8183 (cond
8184 ((and (string-match re1 line)
8185 (setq level (- (match-end 1) (match-beginning 1))))
8186 ;; Beginning of a COMMENT subtree. Skip it.
8187 (while (and (setq line (pop lines))
8188 (or (not (string-match re2 line))
8189 (> (- (match-end 1) (match-beginning 1)) level))))
8190 (setq lines (cons line lines)))
8191 ((string-match "^#" line)
8192 ;; an ordinary comment line
8193 )
8194 (t (setq rtn (cons line rtn)))))
8195 (nreverse rtn)))
8196
8197 ;; ASCII
8198
8199 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8200 "Characters for underlining headings in ASCII export.")
8201
8202 (defconst org-html-entities
8203 '(("nbsp")
8204 ("iexcl")
8205 ("cent")
8206 ("pound")
8207 ("curren")
8208 ("yen")
8209 ("brvbar")
8210 ("sect")
8211 ("uml")
8212 ("copy")
8213 ("ordf")
8214 ("laquo")
8215 ("not")
8216 ("shy")
8217 ("reg")
8218 ("macr")
8219 ("deg")
8220 ("plusmn")
8221 ("sup2")
8222 ("sup3")
8223 ("acute")
8224 ("micro")
8225 ("para")
8226 ("middot")
8227 ("odot"."o")
8228 ("star"."*")
8229 ("cedil")
8230 ("sup1")
8231 ("ordm")
8232 ("raquo")
8233 ("frac14")
8234 ("frac12")
8235 ("frac34")
8236 ("iquest")
8237 ("Agrave")
8238 ("Aacute")
8239 ("Acirc")
8240 ("Atilde")
8241 ("Auml")
8242 ("Aring") ("AA"."&Aring;")
8243 ("AElig")
8244 ("Ccedil")
8245 ("Egrave")
8246 ("Eacute")
8247 ("Ecirc")
8248 ("Euml")
8249 ("Igrave")
8250 ("Iacute")
8251 ("Icirc")
8252 ("Iuml")
8253 ("ETH")
8254 ("Ntilde")
8255 ("Ograve")
8256 ("Oacute")
8257 ("Ocirc")
8258 ("Otilde")
8259 ("Ouml")
8260 ("times")
8261 ("Oslash")
8262 ("Ugrave")
8263 ("Uacute")
8264 ("Ucirc")
8265 ("Uuml")
8266 ("Yacute")
8267 ("THORN")
8268 ("szlig")
8269 ("agrave")
8270 ("aacute")
8271 ("acirc")
8272 ("atilde")
8273 ("auml")
8274 ("aring")
8275 ("aelig")
8276 ("ccedil")
8277 ("egrave")
8278 ("eacute")
8279 ("ecirc")
8280 ("euml")
8281 ("igrave")
8282 ("iacute")
8283 ("icirc")
8284 ("iuml")
8285 ("eth")
8286 ("ntilde")
8287 ("ograve")
8288 ("oacute")
8289 ("ocirc")
8290 ("otilde")
8291 ("ouml")
8292 ("divide")
8293 ("oslash")
8294 ("ugrave")
8295 ("uacute")
8296 ("ucirc")
8297 ("uuml")
8298 ("yacute")
8299 ("thorn")
8300 ("yuml")
8301 ("fnof")
8302 ("Alpha")
8303 ("Beta")
8304 ("Gamma")
8305 ("Delta")
8306 ("Epsilon")
8307 ("Zeta")
8308 ("Eta")
8309 ("Theta")
8310 ("Iota")
8311 ("Kappa")
8312 ("Lambda")
8313 ("Mu")
8314 ("Nu")
8315 ("Xi")
8316 ("Omicron")
8317 ("Pi")
8318 ("Rho")
8319 ("Sigma")
8320 ("Tau")
8321 ("Upsilon")
8322 ("Phi")
8323 ("Chi")
8324 ("Psi")
8325 ("Omega")
8326 ("alpha")
8327 ("beta")
8328 ("gamma")
8329 ("delta")
8330 ("epsilon")
8331 ("varepsilon"."&epsilon;")
8332 ("zeta")
8333 ("eta")
8334 ("theta")
8335 ("iota")
8336 ("kappa")
8337 ("lambda")
8338 ("mu")
8339 ("nu")
8340 ("xi")
8341 ("omicron")
8342 ("pi")
8343 ("rho")
8344 ("sigmaf") ("varsigma"."&sigmaf;")
8345 ("sigma")
8346 ("tau")
8347 ("upsilon")
8348 ("phi")
8349 ("chi")
8350 ("psi")
8351 ("omega")
8352 ("thetasym") ("vartheta"."&thetasym;")
8353 ("upsih")
8354 ("piv")
8355 ("bull") ("bullet"."&bull;")
8356 ("hellip") ("dots"."&hellip;")
8357 ("prime")
8358 ("Prime")
8359 ("oline")
8360 ("frasl")
8361 ("weierp")
8362 ("image")
8363 ("real")
8364 ("trade")
8365 ("alefsym")
8366 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8367 ("uarr") ("uparrow"."&uarr;")
8368 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8369 ("darr")("downarrow"."&darr;")
8370 ("harr") ("leftrightarrow"."&harr;")
8371 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8372 ("lArr") ("Leftarrow"."&lArr;")
8373 ("uArr") ("Uparrow"."&uArr;")
8374 ("rArr") ("Rightarrow"."&rArr;")
8375 ("dArr") ("Downarrow"."&dArr;")
8376 ("hArr") ("Leftrightarrow"."&hArr;")
8377 ("forall")
8378 ("part") ("partial"."&part;")
8379 ("exist") ("exists"."&exist;")
8380 ("empty") ("emptyset"."&empty;")
8381 ("nabla")
8382 ("isin") ("in"."&isin;")
8383 ("notin")
8384 ("ni")
8385 ("prod")
8386 ("sum")
8387 ("minus")
8388 ("lowast") ("ast"."&lowast;")
8389 ("radic")
8390 ("prop") ("proptp"."&prop;")
8391 ("infin") ("infty"."&infin;")
8392 ("ang") ("angle"."&ang;")
8393 ("and") ("vee"."&and;")
8394 ("or") ("wedge"."&or;")
8395 ("cap")
8396 ("cup")
8397 ("int")
8398 ("there4")
8399 ("sim")
8400 ("cong") ("simeq"."&cong;")
8401 ("asymp")("approx"."&asymp;")
8402 ("ne") ("neq"."&ne;")
8403 ("equiv")
8404 ("le")
8405 ("ge")
8406 ("sub") ("subset"."&sub;")
8407 ("sup") ("supset"."&sup;")
8408 ("nsub")
8409 ("sube")
8410 ("supe")
8411 ("oplus")
8412 ("otimes")
8413 ("perp")
8414 ("sdot") ("cdot"."&sdot;")
8415 ("lceil")
8416 ("rceil")
8417 ("lfloor")
8418 ("rfloor")
8419 ("lang")
8420 ("rang")
8421 ("loz") ("Diamond"."&loz;")
8422 ("spades") ("spadesuit"."&spades;")
8423 ("clubs") ("clubsuit"."&clubs;")
8424 ("hearts") ("diamondsuit"."&hearts;")
8425 ("diams") ("diamondsuit"."&diams;")
8426 ("quot")
8427 ("amp")
8428 ("lt")
8429 ("gt")
8430 ("OElig")
8431 ("oelig")
8432 ("Scaron")
8433 ("scaron")
8434 ("Yuml")
8435 ("circ")
8436 ("tilde")
8437 ("ensp")
8438 ("emsp")
8439 ("thinsp")
8440 ("zwnj")
8441 ("zwj")
8442 ("lrm")
8443 ("rlm")
8444 ("ndash")
8445 ("mdash")
8446 ("lsquo")
8447 ("rsquo")
8448 ("sbquo")
8449 ("ldquo")
8450 ("rdquo")
8451 ("bdquo")
8452 ("dagger")
8453 ("Dagger")
8454 ("permil")
8455 ("lsaquo")
8456 ("rsaquo")
8457 ("euro")
8458
8459 ("arccos"."arccos")
8460 ("arcsin"."arcsin")
8461 ("arctan"."arctan")
8462 ("arg"."arg")
8463 ("cos"."cos")
8464 ("cosh"."cosh")
8465 ("cot"."cot")
8466 ("coth"."coth")
8467 ("csc"."csc")
8468 ("deg"."deg")
8469 ("det"."det")
8470 ("dim"."dim")
8471 ("exp"."exp")
8472 ("gcd"."gcd")
8473 ("hom"."hom")
8474 ("inf"."inf")
8475 ("ker"."ker")
8476 ("lg"."lg")
8477 ("lim"."lim")
8478 ("liminf"."liminf")
8479 ("limsup"."limsup")
8480 ("ln"."ln")
8481 ("log"."log")
8482 ("max"."max")
8483 ("min"."min")
8484 ("Pr"."Pr")
8485 ("sec"."sec")
8486 ("sin"."sin")
8487 ("sinh"."sinh")
8488 ("sup"."sup")
8489 ("tan"."tan")
8490 ("tanh"."tanh")
8491 )
8492 "Entities for TeX->HTML translation.
8493 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8494 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8495 In that case, \"\\ent\" will be translated to \"&other;\".
8496 The list contains HTML entities for Latin-1, Greek and other symbols.
8497 It is supplemented by a number of commonly used TeX macros with appropriate
8498 translations. There is currently no way for users to extend this.")
8499
8500 (defvar org-last-level nil) ; dynamically scoped variable
8501
8502 (defun org-export-as-ascii (arg)
8503 "Export the outline as a pretty ASCII file.
8504 If there is an active region, export only the region.
8505 The prefix ARG specifies how many levels of the outline should become
8506 underlined headlines. The default is 3."
8507 (interactive "P")
8508 (setq-default org-todo-line-regexp org-todo-line-regexp)
8509 (let* ((region
8510 (buffer-substring
8511 (if (org-region-active-p) (region-beginning) (point-min))
8512 (if (org-region-active-p) (region-end) (point-max))))
8513 (lines (org-export-find-first-heading-line
8514 (org-skip-comments (org-split-string region "[\r\n]"))))
8515 (org-startup-with-deadline-check nil)
8516 (level 0) line txt
8517 (umax nil)
8518 (case-fold-search nil)
8519 (filename (concat (file-name-sans-extension (buffer-file-name))
8520 ".txt"))
8521 (buffer (find-file-noselect filename))
8522 (levels-open (make-vector org-level-max nil))
8523 (date (format-time-string "%Y/%m/%d" (current-time)))
8524 (time (format-time-string "%X" (current-time)))
8525 (author user-full-name)
8526 (title (buffer-name))
8527 (options nil)
8528 (email user-mail-address)
8529 (language org-export-default-language)
8530 (text nil)
8531 (todo nil)
8532 (lang-words nil))
8533
8534 (setq org-last-level 1)
8535 (org-init-section-numbers)
8536
8537 (find-file-noselect filename)
8538
8539 ;; Search for the export key lines
8540 (org-parse-key-lines)
8541
8542 (setq lang-words (or (assoc language org-export-language-setup)
8543 (assoc "en" org-export-language-setup)))
8544 (if org-export-ascii-show-new-buffer
8545 (switch-to-buffer-other-window buffer)
8546 (set-buffer buffer))
8547 (erase-buffer)
8548 (fundamental-mode)
8549 (if options (org-parse-export-options options))
8550 (setq umax (if arg (prefix-numeric-value arg)
8551 org-export-headline-levels))
8552
8553 ;; File header
8554 (if title (org-insert-centered title ?=))
8555 (insert "\n")
8556 (if (or author email)
8557 (insert (concat (nth 1 lang-words) ": " (or author "")
8558 (if email (concat " <" email ">") "")
8559 "\n")))
8560 (if (and date time)
8561 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8562 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8563
8564 (insert "\n\n")
8565
8566 (if org-export-with-toc
8567 (progn
8568 (insert (nth 3 lang-words) "\n"
8569 (make-string (length (nth 3 lang-words)) ?=) "\n")
8570 (mapcar '(lambda (line)
8571 (if (string-match org-todo-line-regexp
8572 line)
8573 ;; This is a headline
8574 (progn
8575 (setq level (- (match-end 1) (match-beginning 1))
8576 txt (match-string 3 line)
8577 todo
8578 (or (and (match-beginning 2)
8579 (not (equal (match-string 2 line)
8580 org-done-string)))
8581 ; TODO, not DONE
8582 (and (= level umax)
8583 (org-search-todo-below
8584 line lines level))))
8585 (setq txt (org-html-expand-for-ascii txt))
8586
8587 (if org-export-with-section-numbers
8588 (setq txt (concat (org-section-number level)
8589 " " txt)))
8590 (if (<= level umax)
8591 (progn
8592 (insert
8593 (make-string (* (1- level) 4) ?\ )
8594 (format (if todo "%s (*)\n" "%s\n") txt))
8595 (setq org-last-level level))
8596 ))))
8597 lines)))
8598
8599 (org-init-section-numbers)
8600 (while (setq line (pop lines))
8601 ;; Remove the quoted HTML tags.
8602 (setq line (org-html-expand-for-ascii line))
8603 (cond
8604 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8605 ;; a Headline
8606 (setq level (- (match-end 1) (match-beginning 1))
8607 txt (match-string 2 line))
8608 (org-ascii-level-start level txt umax))
8609 (t (insert line "\n"))))
8610 (normal-mode)
8611 (save-buffer)
8612 (goto-char (point-min))))
8613
8614 (defun org-search-todo-below (line lines level)
8615 "Search the subtree below LINE for any TODO entries."
8616 (let ((rest (cdr (memq line lines)))
8617 (re org-todo-line-regexp)
8618 line lv todo)
8619 (catch 'exit
8620 (while (setq line (pop rest))
8621 (if (string-match re line)
8622 (progn
8623 (setq lv (- (match-end 1) (match-beginning 1))
8624 todo (and (match-beginning 2)
8625 (not (equal (match-string 2 line)
8626 org-done-string))))
8627 ; TODO, not DONE
8628 (if (<= lv level) (throw 'exit nil))
8629 (if todo (throw 'exit t))))))))
8630
8631 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8632 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8633 (defun org-html-expand-for-ascii (line)
8634 "Handle quoted HTML for ASCII export."
8635 (if org-export-html-expand
8636 (while (string-match "@<[^<>\n]*>" line)
8637 ;; We just remove the tags for now.
8638 (setq line (replace-match "" nil nil line))))
8639 line)
8640
8641 (defun org-insert-centered (s &optional underline)
8642 "Insert the string S centered and underline it with character UNDERLINE."
8643 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8644 (insert (make-string ind ?\ ) s "\n")
8645 (if underline
8646 (insert (make-string ind ?\ )
8647 (make-string (length s) underline)
8648 "\n"))))
8649
8650 (defun org-ascii-level-start (level title umax)
8651 "Insert a new level in ASCII export."
8652 (let (char)
8653 (if (> level umax)
8654 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8655 (if (or (not (equal (char-before) ?\n))
8656 (not (equal (char-before (1- (point))) ?\n)))
8657 (insert "\n"))
8658 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8659 (if org-export-with-section-numbers
8660 (setq title (concat (org-section-number level) " " title)))
8661 (insert title "\n" (make-string (string-width title) char) "\n"))))
8662
8663 (defun org-export-copy-visible ()
8664 "Copy the visible part of the buffer to another buffer, for printing.
8665 Also removes the first line of the buffer if it specifies a mode,
8666 and all options lines."
8667 (interactive)
8668 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8669 ".txt"))
8670 (buffer (find-file-noselect filename))
8671 (ore (concat
8672 (org-make-options-regexp
8673 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8674 "STARTUP" "ARCHIVE"
8675 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8676 (if org-noutline-p "\\(\n\\|$\\)" "")))
8677 s e)
8678 (with-current-buffer buffer
8679 (erase-buffer)
8680 (text-mode))
8681 (save-excursion
8682 (setq s (goto-char (point-min)))
8683 (while (not (= (point) (point-max)))
8684 (goto-char (org-find-invisible))
8685 (append-to-buffer buffer s (point))
8686 (setq s (goto-char (org-find-visible)))))
8687 (switch-to-buffer-other-window buffer)
8688 (newline)
8689 (goto-char (point-min))
8690 (if (looking-at ".*-\\*- mode:.*\n")
8691 (replace-match ""))
8692 (while (re-search-forward ore nil t)
8693 (replace-match ""))
8694 (goto-char (point-min))))
8695
8696 (defun org-find-visible ()
8697 (if (featurep 'noutline)
8698 (let ((s (point)))
8699 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8700 (get-char-property s 'invisible)))
8701 s)
8702 (skip-chars-forward "^\n")
8703 (point)))
8704 (defun org-find-invisible ()
8705 (if (featurep 'noutline)
8706 (let ((s (point)))
8707 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8708 (not (get-char-property s 'invisible))))
8709 s)
8710 (skip-chars-forward "^\r")
8711 (point)))
8712
8713 ;; HTML
8714
8715 (defun org-get-current-options ()
8716 "Return a string with current options as keyword options.
8717 Does include HTML export options as well as TODO and CATEGORY stuff."
8718 (format
8719 "#+TITLE: %s
8720 #+AUTHOR: %s
8721 #+EMAIL: %s
8722 #+LANGUAGE: %s
8723 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8724 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8725 #+CATEGORY: %s
8726 #+SEQ_TODO: %s
8727 #+TYP_TODO: %s
8728 #+STARTUP: %s %s
8729 #+ARCHIVE: %s
8730 "
8731 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8732 org-export-headline-levels
8733 org-export-with-section-numbers
8734 org-export-with-toc
8735 org-export-preserve-breaks
8736 org-export-html-expand
8737 org-export-with-fixed-width
8738 org-export-with-tables
8739 org-export-with-sub-superscripts
8740 org-export-with-emphasize
8741 org-export-with-TeX-macros
8742 (file-name-nondirectory (buffer-file-name))
8743 (if (equal org-todo-interpretation 'sequence)
8744 (mapconcat 'identity org-todo-keywords " ")
8745 "TODO FEEDBACK VERIFY DONE")
8746 (if (equal org-todo-interpretation 'type)
8747 (mapconcat 'identity org-todo-keywords " ")
8748 "Me Jason Marie DONE")
8749 (cdr (assoc org-startup-folded
8750 '((nil . "nofold")(t . "fold")(content . "content"))))
8751 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8752 org-archive-location
8753 ))
8754
8755 (defun org-insert-export-options-template ()
8756 "Insert into the buffer a template with information for exporting."
8757 (interactive)
8758 (if (not (bolp)) (newline))
8759 (let ((s (org-get-current-options)))
8760 (and (string-match "#\\+CATEGORY" s)
8761 (setq s (substring s 0 (match-beginning 0))))
8762 (insert s)))
8763
8764 (defun org-toggle-fixed-width-section (arg)
8765 "Toggle the fixed-width export.
8766 If there is no active region, the QUOTE keyword at the current headline is
8767 inserted or removed. When present, it causes the text between this headline
8768 and the next to be exported as fixed-width text, and unmodified.
8769 If there is an active region, this command adds or removes a colon as the
8770 first character of this line. If the first character of a line is a colon,
8771 this line is also exported in fixed-width font."
8772 (interactive "P")
8773 (let* ((cc 0)
8774 (regionp (org-region-active-p))
8775 (beg (if regionp (region-beginning) (point)))
8776 (end (if regionp (region-end)))
8777 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8778 (re "[ \t]*\\(:\\)")
8779 off)
8780 (if regionp
8781 (save-excursion
8782 (goto-char beg)
8783 (setq cc (current-column))
8784 (beginning-of-line 1)
8785 (setq off (looking-at re))
8786 (while (> nlines 0)
8787 (setq nlines (1- nlines))
8788 (beginning-of-line 1)
8789 (cond
8790 (arg
8791 (move-to-column cc t)
8792 (insert ":\n")
8793 (forward-line -1))
8794 ((and off (looking-at re))
8795 (replace-match "" t t nil 1))
8796 ((not off) (move-to-column cc t) (insert ":")))
8797 (forward-line 1)))
8798 (save-excursion
8799 (org-back-to-heading)
8800 (if (looking-at (concat outline-regexp
8801 "\\( +\\<" org-quote-string "\\>\\)"))
8802 (replace-match "" t t nil 1)
8803 (if (looking-at outline-regexp)
8804 (progn
8805 (goto-char (match-end 0))
8806 (insert " " org-quote-string))))))))
8807
8808 (defun org-export-as-html-and-open (arg)
8809 "Export the outline as HTML and immediately open it with a browser.
8810 If there is an active region, export only the region.
8811 The prefix ARG specifies how many levels of the outline should become
8812 headlines. The default is 3. Lower levels will become bulleted lists."
8813 (interactive "P")
8814 (org-export-as-html arg 'hidden)
8815 (org-open-file (buffer-file-name)))
8816
8817 (defun org-export-as-html-batch ()
8818 "Call `org-export-as-html', may be used in batch processing as
8819 emacs --batch
8820 --load=$HOME/lib/emacs/org.el
8821 --eval \"(setq org-export-headline-levels 2)\"
8822 --visit=MyFile --funcall org-export-as-html-batch"
8823 (org-export-as-html org-export-headline-levels 'hidden))
8824
8825 (defun org-export-as-html (arg &optional hidden)
8826 "Export the outline as a pretty HTML file.
8827 If there is an active region, export only the region.
8828 The prefix ARG specifies how many levels of the outline should become
8829 headlines. The default is 3. Lower levels will become bulleted lists."
8830 (interactive "P")
8831 (setq-default org-todo-line-regexp org-todo-line-regexp)
8832 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8833 (setq-default org-done-string org-done-string)
8834 (let* ((region-p (org-region-active-p))
8835 (region
8836 (buffer-substring
8837 (if region-p (region-beginning) (point-min))
8838 (if region-p (region-end) (point-max))))
8839 (all_lines
8840 (org-skip-comments (org-split-string region "[\r\n]")))
8841 (lines (org-export-find-first-heading-line all_lines))
8842 (level 0) (line "") (origline "") txt todo
8843 (umax nil)
8844 (filename (concat (file-name-sans-extension (buffer-file-name))
8845 ".html"))
8846 (buffer (find-file-noselect filename))
8847 (levels-open (make-vector org-level-max nil))
8848 (date (format-time-string "%Y/%m/%d" (current-time)))
8849 (time (format-time-string "%X" (current-time)))
8850 (author user-full-name)
8851 (title (buffer-name))
8852 (options nil)
8853 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
8854 (inquote nil)
8855 (email user-mail-address)
8856 (language org-export-default-language)
8857 (text nil)
8858 (lang-words nil)
8859 (head-count 0) cnt
8860 (start 0)
8861 ;; FIXME: The following returns always nil under XEmacs
8862 (coding-system (and (fboundp 'coding-system-get)
8863 (boundp 'buffer-file-coding-system)
8864 buffer-file-coding-system))
8865 (coding-system-for-write (or coding-system coding-system-for-write))
8866 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
8867 (charset (and coding-system
8868 (coding-system-get coding-system 'mime-charset)))
8869 table-open type
8870 table-buffer table-orig-buffer
8871 )
8872 (message "Exporting...")
8873
8874 (setq org-last-level 1)
8875 (org-init-section-numbers)
8876
8877 ;; Search for the export key lines
8878 (org-parse-key-lines)
8879 (setq lang-words (or (assoc language org-export-language-setup)
8880 (assoc "en" org-export-language-setup)))
8881
8882 ;; Switch to the output buffer
8883 (if (or hidden (not org-export-html-show-new-buffer))
8884 (set-buffer buffer)
8885 (switch-to-buffer-other-window buffer))
8886 (erase-buffer)
8887 (fundamental-mode)
8888 (let ((case-fold-search nil))
8889 (if options (org-parse-export-options options))
8890 (setq umax (if arg (prefix-numeric-value arg)
8891 org-export-headline-levels))
8892
8893 ;; File header
8894 (insert (format
8895 "<html lang=\"%s\"><head>
8896 <title>%s</title>
8897 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
8898 <meta name=generator content=\"Org-mode\">
8899 <meta name=generated content=\"%s %s\">
8900 <meta name=author content=\"%s\">
8901 </head><body>
8902 "
8903 language (org-html-expand title) (or charset "iso-8859-1")
8904 date time author))
8905 (if title (insert (concat "<H1 align=\"center\">"
8906 (org-html-expand title) "</H1>\n")))
8907 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8908 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8909 email "&gt;</a>\n")))
8910 (if (or author email) (insert "<br>\n"))
8911 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8912 date " " time "<br>\n")))
8913 (if text (insert (concat "<p>\n" (org-html-expand text))))
8914 (if org-export-with-toc
8915 (progn
8916 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8917 (insert "<ul>\n")
8918 (mapcar '(lambda (line)
8919 (if (string-match org-todo-line-regexp line)
8920 ;; This is a headline
8921 (progn
8922 (setq level (- (match-end 1) (match-beginning 1))
8923 txt (save-match-data
8924 (org-html-expand
8925 (match-string 3 line)))
8926 todo
8927 (or (and (match-beginning 2)
8928 (not (equal (match-string 2 line)
8929 org-done-string)))
8930 ; TODO, not DONE
8931 (and (= level umax)
8932 (org-search-todo-below
8933 line lines level))))
8934 (if org-export-with-section-numbers
8935 (setq txt (concat (org-section-number level)
8936 " " txt)))
8937 (if (<= level umax)
8938 (progn
8939 (setq head-count (+ head-count 1))
8940 (if (> level org-last-level)
8941 (progn
8942 (setq cnt (- level org-last-level))
8943 (while (>= (setq cnt (1- cnt)) 0)
8944 (insert "<ul>"))
8945 (insert "\n")))
8946 (if (< level org-last-level)
8947 (progn
8948 (setq cnt (- org-last-level level))
8949 (while (>= (setq cnt (1- cnt)) 0)
8950 (insert "</ul>"))
8951 (insert "\n")))
8952 (insert
8953 (format
8954 (if todo
8955 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8956 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8957 head-count txt))
8958 (setq org-last-level level))
8959 ))))
8960 lines)
8961 (while (> org-last-level 0)
8962 (setq org-last-level (1- org-last-level))
8963 (insert "</ul>\n"))
8964 ))
8965 (setq head-count 0)
8966 (org-init-section-numbers)
8967
8968 (while (setq line (pop lines) origline line)
8969 ;; end of quote?
8970 (when (and inquote (string-match "^\\*+" line))
8971 (insert "</pre>\n")
8972 (setq inquote nil))
8973 ;; inquote
8974 (if inquote
8975 (progn
8976 (insert line "\n")
8977 (setq line (org-html-expand line))) ;;????? FIXME: not needed?
8978
8979 ;; Protect the links
8980 (setq start 0)
8981 (while (string-match org-link-maybe-angles-regexp line start)
8982 (setq start (match-end 0))
8983 (setq line (replace-match
8984 (concat "\000" (match-string 1 line) "\000")
8985 t t line)))
8986
8987 ;; replace "<" and ">" by "&lt;" and "&gt;"
8988 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8989 (setq line (org-html-expand line))
8990
8991 ;; Verbatim lines
8992 (if (and org-export-with-fixed-width
8993 (string-match "^[ \t]*:\\(.*\\)" line))
8994 (progn
8995 (let ((l (match-string 1 line)))
8996 (while (string-match " " l)
8997 (setq l (replace-match "&nbsp;" t t l)))
8998 (insert "\n<span style='font-family:Courier'>"
8999 l "</span>"
9000 (if (and lines
9001 (not (string-match "^[ \t]+\\(:.*\\)"
9002 (car lines))))
9003 "<br>\n" "\n"))))
9004
9005 (setq start 0)
9006 (while (string-match org-protected-link-regexp line start)
9007 (setq start (- (match-end 0) 2))
9008 (setq type (match-string 1 line))
9009 (cond
9010 ((member type '("http" "https" "ftp" "mailto" "news"))
9011 ;; standard URL
9012 (setq line (replace-match
9013 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
9014 "<a href=\"\\1:\\2\">\\1:\\2</a>"
9015 nil nil line)))
9016 ((string= type "file")
9017 ;; FILE link
9018 (let* ((filename (match-string 2 line))
9019 (abs-p (file-name-absolute-p filename))
9020 (thefile (if abs-p (expand-file-name filename) filename))
9021 (thefile (save-match-data
9022 (if (string-match ":[0-9]+$" thefile)
9023 (replace-match "" t t thefile)
9024 thefile)))
9025 (file-is-image-p
9026 (save-match-data
9027 (string-match (org-image-file-name-regexp) thefile))))
9028 (setq line (replace-match
9029 (if (and org-export-html-inline-images
9030 file-is-image-p)
9031 (concat "<img src=\"" thefile "\"/>")
9032 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
9033 nil nil line))))
9034
9035 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
9036 (setq line (replace-match
9037 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
9038
9039 ;; TODO items
9040 (if (and (string-match org-todo-line-regexp line)
9041 (match-beginning 2))
9042 (if (equal (match-string 2 line) org-done-string)
9043 (setq line (replace-match
9044 "<span style='color:green'>\\2</span>"
9045 nil nil line 2))
9046 (setq line (replace-match "<span style='color:red'>\\2</span>"
9047 nil nil line 2))))
9048
9049 ;; DEADLINES
9050 (if (string-match org-deadline-line-regexp line)
9051 (progn
9052 (if (save-match-data
9053 (string-match "<a href"
9054 (substring line 0 (match-beginning 0))))
9055 nil ; Don't do the replacement - it is inside a link
9056 (setq line (replace-match "<span style='color:red'>\\&</span>"
9057 nil nil line 1)))))
9058
9059
9060 (cond
9061 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9062 ;; This is a headline
9063 (setq level (- (match-end 1) (match-beginning 1))
9064 txt (match-string 2 line))
9065 (if (<= level umax) (setq head-count (+ head-count 1)))
9066 (org-html-level-start level txt umax
9067 (and org-export-with-toc (<= level umax))
9068 head-count)
9069 ;; QUOTES
9070 (when (string-match quote-re line)
9071 (insert "<pre>")
9072 (setq inquote t)))
9073
9074 ((and org-export-with-tables
9075 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9076 (if (not table-open)
9077 ;; New table starts
9078 (setq table-open t table-buffer nil table-orig-buffer nil))
9079 ;; Accumulate lines
9080 (setq table-buffer (cons line table-buffer)
9081 table-orig-buffer (cons origline table-orig-buffer))
9082 (when (or (not lines)
9083 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9084 (car lines))))
9085 (setq table-open nil
9086 table-buffer (nreverse table-buffer)
9087 table-orig-buffer (nreverse table-orig-buffer))
9088 (insert (org-format-table-html table-buffer table-orig-buffer))))
9089 (t
9090 ;; Normal lines
9091 ;; Lines starting with "-", and empty lines make new paragraph.
9092 ;; FIXME: Should we add + and *?
9093 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
9094 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9095 )))
9096 (if org-export-html-with-timestamp
9097 (insert org-export-html-html-helper-timestamp))
9098 (insert "</body>\n</html>\n")
9099 (debug)
9100 (normal-mode)
9101 (save-buffer)
9102 (goto-char (point-min)))))
9103
9104 (defun org-format-table-html (lines olines)
9105 "Find out which HTML converter to use and return the HTML code."
9106 (if (string-match "^[ \t]*|" (car lines))
9107 ;; A normal org table
9108 (org-format-org-table-html lines)
9109 ;; Table made by table.el - test for spanning
9110 (let* ((hlines (delq nil (mapcar
9111 (lambda (x)
9112 (if (string-match "^[ \t]*\\+-" x) x
9113 nil))
9114 lines)))
9115 (first (car hlines))
9116 (ll (and (string-match "\\S-+" first)
9117 (match-string 0 first)))
9118 (re (concat "^[ \t]*" (regexp-quote ll)))
9119 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9120 hlines))))
9121 (if (and (not spanning)
9122 (not org-export-prefer-native-exporter-for-tables))
9123 ;; We can use my own converter with HTML conversions
9124 (org-format-table-table-html lines)
9125 ;; Need to use the code generator in table.el, with the original text.
9126 (org-format-table-table-html-using-table-generate-source olines)))))
9127
9128 (defun org-format-org-table-html (lines)
9129 "Format a table into html."
9130 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9131 (setq lines (nreverse lines))
9132 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9133 (setq lines (nreverse lines))
9134 (let ((head (and org-export-highlight-first-table-line
9135 (delq nil (mapcar
9136 (lambda (x) (string-match "^[ \t]*|-" x))
9137 (cdr lines)))))
9138 line fields html)
9139 (setq html (concat org-export-html-table-tag "\n"))
9140 (while (setq line (pop lines))
9141 (catch 'next-line
9142 (if (string-match "^[ \t]*|-" line)
9143 (progn
9144 (setq head nil) ;; head ends here, first time around
9145 ;; ignore this line
9146 (throw 'next-line t)))
9147 ;; Break the line into fields
9148 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9149 (setq html (concat
9150 html
9151 "<tr>"
9152 (mapconcat (lambda (x)
9153 (if head
9154 (concat "<th>" x "</th>")
9155 (concat "<td valign=\"top\">" x "</td>")))
9156 fields "")
9157 "</tr>\n"))))
9158 (setq html (concat html "</table>\n"))
9159 html))
9160
9161 (defun org-fake-empty-table-line (line)
9162 "Replace everything except \"|\" with spaces."
9163 (let ((i (length line))
9164 (newstr (copy-sequence line)))
9165 (while (> i 0)
9166 (setq i (1- i))
9167 (if (not (eq (aref newstr i) ?|))
9168 (aset newstr i ?\ )))
9169 newstr))
9170
9171 (defun org-format-table-table-html (lines)
9172 "Format a table generated by table.el into html.
9173 This conversion does *not* use `table-generate-source' from table.el.
9174 This has the advantage that Org-mode's HTML conversions can be used.
9175 But it has the disadvantage, that no cell- or row-spanning is allowed."
9176 (let (line field-buffer
9177 (head org-export-highlight-first-table-line)
9178 fields html empty)
9179 (setq html (concat org-export-html-table-tag "\n"))
9180 (while (setq line (pop lines))
9181 (setq empty "&nbsp")
9182 (catch 'next-line
9183 (if (string-match "^[ \t]*\\+-" line)
9184 (progn
9185 (if field-buffer
9186 (progn
9187 (setq html (concat
9188 html
9189 "<tr>"
9190 (mapconcat
9191 (lambda (x)
9192 (if (equal x "") (setq x empty))
9193 (if head
9194 (concat "<th valign=\"top\">" x
9195 "</th>\n")
9196 (concat "<td valign=\"top\">" x
9197 "</td>\n")))
9198 field-buffer "\n")
9199 "</tr>\n"))
9200 (setq head nil)
9201 (setq field-buffer nil)))
9202 ;; Ignore this line
9203 (throw 'next-line t)))
9204 ;; Break the line into fields and store the fields
9205 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9206 (if field-buffer
9207 (setq field-buffer (mapcar
9208 (lambda (x)
9209 (concat x "<br>" (pop fields)))
9210 field-buffer))
9211 (setq field-buffer fields))))
9212 (setq html (concat html "</table>\n"))
9213 html))
9214
9215 (defun org-format-table-table-html-using-table-generate-source (lines)
9216 "Format a table into html, using `table-generate-source' from table.el.
9217 This has the advantage that cell- or row-spanning is allowed.
9218 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9219 (require 'table)
9220 (with-current-buffer (get-buffer-create " org-tmp1 ")
9221 (erase-buffer)
9222 (insert (mapconcat 'identity lines "\n"))
9223 (goto-char (point-min))
9224 (if (not (re-search-forward "|[^+]" nil t))
9225 (error "Error processing table"))
9226 (table-recognize-table)
9227 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9228 (table-generate-source 'html " org-tmp2 ")
9229 (set-buffer " org-tmp2 ")
9230 (buffer-substring (point-min) (point-max))))
9231
9232 (defun org-html-expand (string)
9233 "Prepare STRING for HTML export. Applies all active conversions."
9234 ;; First check if there is a link in the line - if yes, apply conversions
9235 ;; only before the start of the link.
9236 (let* ((m (string-match org-link-regexp string))
9237 (s (if m (substring string 0 m) string))
9238 (r (if m (substring string m) "")))
9239 ;; convert < to &lt; and > to &gt;
9240 (while (string-match "<" s)
9241 (setq s (replace-match "&lt;" t t s)))
9242 (while (string-match ">" s)
9243 (setq s (replace-match "&gt;" t t s)))
9244 (if org-export-html-expand
9245 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9246 (setq s (replace-match "<\\1>" nil nil s))))
9247 (if org-export-with-emphasize
9248 (setq s (org-export-html-convert-emphasize s)))
9249 (if org-export-with-sub-superscripts
9250 (setq s (org-export-html-convert-sub-super s)))
9251 (if org-export-with-TeX-macros
9252 (let ((start 0) wd ass)
9253 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9254 (setq wd (match-string 1 s))
9255 (if (setq ass (assoc wd org-html-entities))
9256 (setq s (replace-match (or (cdr ass)
9257 (concat "&" (car ass) ";"))
9258 t t s))
9259 (setq start (+ start (length wd)))))))
9260 (concat s r)))
9261
9262 (defun org-create-multibrace-regexp (left right n)
9263 "Create a regular expression which will match a balanced sexp.
9264 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9265 as single character strings.
9266 The regexp returned will match the entire expression including the
9267 delimiters. It will also define a single group which contains the
9268 match except for the outermost delimiters. The maximum depth of
9269 stacked delimiters is N. Escaping delimiters is not possible."
9270 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9271 (or "\\|")
9272 (re nothing)
9273 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9274 (while (> n 1)
9275 (setq n (1- n)
9276 re (concat re or next)
9277 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9278 (concat left "\\(" re "\\)" right)))
9279
9280 (defvar org-match-substring-regexp
9281 (concat
9282 "\\([^\\]\\)\\([_^]\\)\\("
9283 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9284 "\\|"
9285 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9286 "\\|"
9287 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9288 "The regular expression matching a sub- or superscript.")
9289
9290 (defun org-export-html-convert-sub-super (string)
9291 "Convert sub- and superscripts in STRING to HTML."
9292 (let (key c)
9293 (while (string-match org-match-substring-regexp string)
9294 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9295 (setq c (or (match-string 8 string)
9296 (match-string 6 string)
9297 (match-string 5 string)))
9298 (setq string (replace-match
9299 (concat (match-string 1 string)
9300 "<" key ">" c "</" key ">")
9301 t t string)))
9302 (while (string-match "\\\\\\([_^]\\)" string)
9303 (setq string (replace-match (match-string 1 string) t t string))))
9304 string)
9305
9306 (defun org-export-html-convert-emphasize (string)
9307 (while (string-match
9308 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9309 string)
9310 (setq string (replace-match
9311 (concat "<b>" (match-string 3 string) "</b>")
9312 t t string 2)))
9313 (while (string-match
9314 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9315 string)
9316 (setq string (replace-match
9317 (concat "<i>" (match-string 3 string) "</i>")
9318 t t string 2)))
9319 (while (string-match
9320 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9321 string)
9322 (setq string (replace-match
9323 (concat "<u>" (match-string 3 string) "</u>")
9324 t t string 2)))
9325 string)
9326
9327 (defun org-parse-key-lines ()
9328 "Find the special key lines with the information for exporters."
9329 (save-excursion
9330 (goto-char 0)
9331 (let ((re (org-make-options-regexp
9332 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9333 key)
9334 (while (re-search-forward re nil t)
9335 (setq key (match-string 1))
9336 (cond ((string-equal key "TITLE")
9337 (setq title (match-string 2)))
9338 ((string-equal key "AUTHOR")
9339 (setq author (match-string 2)))
9340 ((string-equal key "EMAIL")
9341 (setq email (match-string 2)))
9342 ((string-equal key "LANGUAGE")
9343 (setq language (match-string 2)))
9344 ((string-equal key "TEXT")
9345 (setq text (concat text "\n" (match-string 2))))
9346 ((string-equal key "OPTIONS")
9347 (setq options (match-string 2))))))))
9348
9349 (defun org-parse-export-options (s)
9350 "Parse the export options line."
9351 (let ((op '(("H" . org-export-headline-levels)
9352 ("num" . org-export-with-section-numbers)
9353 ("toc" . org-export-with-toc)
9354 ("\\n" . org-export-preserve-breaks)
9355 ("@" . org-export-html-expand)
9356 (":" . org-export-with-fixed-width)
9357 ("|" . org-export-with-tables)
9358 ("^" . org-export-with-sub-superscripts)
9359 ("*" . org-export-with-emphasize)
9360 ("TeX" . org-export-with-TeX-macros)))
9361 o)
9362 (while (setq o (pop op))
9363 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9364 s)
9365 (set (make-local-variable (cdr o))
9366 (car (read-from-string (match-string 1 s))))))))
9367
9368 (defun org-html-level-start (level title umax with-toc head-count)
9369 "Insert a new level in HTML export."
9370 (let ((l (1+ (max level umax))))
9371 (while (<= l org-level-max)
9372 (if (aref levels-open (1- l))
9373 (progn
9374 (org-html-level-close l)
9375 (aset levels-open (1- l) nil)))
9376 (setq l (1+ l)))
9377 (if (> level umax)
9378 (progn
9379 (if (aref levels-open (1- level))
9380 (insert "<li>" title "<p>\n")
9381 (aset levels-open (1- level) t)
9382 (insert "<ul><li>" title "<p>\n")))
9383 (if org-export-with-section-numbers
9384 (setq title (concat (org-section-number level) " " title)))
9385 (setq level (+ level 1))
9386 (if with-toc
9387 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9388 level head-count title level))
9389 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9390
9391 (defun org-html-level-close (&rest args)
9392 "Terminate one level in HTML export."
9393 (insert "</ul>"))
9394
9395
9396 ;; Variable holding the vector with section numbers
9397 (defvar org-section-numbers (make-vector org-level-max 0))
9398
9399 (defun org-init-section-numbers ()
9400 "Initialize the vector for the section numbers."
9401 (let* ((level -1)
9402 (numbers (nreverse (org-split-string "" "\\.")))
9403 (depth (1- (length org-section-numbers)))
9404 (i depth) number-string)
9405 (while (>= i 0)
9406 (if (> i level)
9407 (aset org-section-numbers i 0)
9408 (setq number-string (or (car numbers) "0"))
9409 (if (string-match "\\`[A-Z]\\'" number-string)
9410 (aset org-section-numbers i
9411 (- (string-to-char number-string) ?A -1))
9412 (aset org-section-numbers i (string-to-number number-string)))
9413 (pop numbers))
9414 (setq i (1- i)))))
9415
9416 (defun org-section-number (&optional level)
9417 "Return a string with the current section number.
9418 When LEVEL is non-nil, increase section numbers on that level."
9419 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9420 (when level
9421 (when (> level -1)
9422 (aset org-section-numbers
9423 level (1+ (aref org-section-numbers level))))
9424 (setq idx (1+ level))
9425 (while (<= idx depth)
9426 (if (not (= idx 1))
9427 (aset org-section-numbers idx 0))
9428 (setq idx (1+ idx))))
9429 (setq idx 0)
9430 (while (<= idx depth)
9431 (setq n (aref org-section-numbers idx))
9432 (setq string (concat string (if (not (string= string "")) "." "")
9433 (int-to-string n)))
9434 (setq idx (1+ idx)))
9435 (save-match-data
9436 (if (string-match "\\`\\([@0]\\.\\)+" string)
9437 (setq string (replace-match "" nil nil string)))
9438 (if (string-match "\\(\\.0\\)+\\'" string)
9439 (setq string (replace-match "" nil nil string))))
9440 string))
9441
9442
9443
9444
9445
9446 (defun org-export-icalendar-this-file ()
9447 "Export current file as an iCalendar file.
9448 The iCalendar file will be located in the same directory as the Org-mode
9449 file, but with extension `.ics'."
9450 (interactive)
9451 (org-export-icalendar nil (buffer-file-name)))
9452
9453 ;;;###autoload
9454 (defun org-export-icalendar-all-agenda-files ()
9455 "Export all files in `org-agenda-files' to iCalendar .ics files.
9456 Each iCalendar file will be located in the same directory as the Org-mode
9457 file, but with extension `.ics'."
9458 (interactive)
9459 (apply 'org-export-icalendar nil org-agenda-files))
9460
9461 ;;;###autoload
9462 (defun org-export-icalendar-combine-agenda-files ()
9463 "Export all files in `org-agenda-files' to a single combined iCalendar file.
9464 The file is stored under the name `org-combined-agenda-icalendar-file'."
9465 (interactive)
9466 (apply 'org-export-icalendar t org-agenda-files))
9467
9468 (defun org-export-icalendar (combine &rest files)
9469 "Create iCalendar files for all elements of FILES.
9470 If COMBINE is non-nil, combine all calendar entries into a single large
9471 file and store it under the name `org-combined-agenda-icalendar-file'."
9472 (save-excursion
9473 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
9474 (when combine
9475 (setq ical-file org-combined-agenda-icalendar-file
9476 ical-buffer (org-get-agenda-file-buffer ical-file))
9477 (set-buffer ical-buffer) (erase-buffer))
9478 (while (setq file (pop files))
9479 (catch 'nextfile
9480 (org-check-agenda-file file)
9481 (unless combine
9482 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
9483 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
9484 (set-buffer ical-buffer) (erase-buffer))
9485 (set-buffer (org-get-agenda-file-buffer file))
9486 (setq category (or org-category
9487 (file-name-sans-extension
9488 (file-name-nondirectory (buffer-file-name)))))
9489 (if (symbolp category) (setq category (symbol-name category)))
9490 (let ((standard-output ical-buffer))
9491 (if combine
9492 (and (not started) (setq started t)
9493 (org-start-icalendar-file "OrgMode"))
9494 (org-start-icalendar-file category))
9495 (org-print-icalendar-entries combine category)
9496 (when (or (and combine (not files)) (not combine))
9497 (org-finish-icalendar-file)
9498 (set-buffer ical-buffer)
9499 (save-buffer)
9500 (run-hooks 'org-after-save-iCalendar-file-hook)))))
9501 (org-release-buffers org-agenda-new-buffers))))
9502
9503 (defvar org-after-save-iCalendar-file-hook nil
9504 "Hook run after an iCalendar file has been saved.
9505 The iCalendar buffer is still current when this hook is run.
9506 A good way to use this is to tell a desktop calenndar application to re-read
9507 the iCalendar file.")
9508
9509 (defun org-print-icalendar-entries (&optional combine category)
9510 "Print iCalendar entries for the current Org-mode file to `standard-output'.
9511 When COMBINE is non nil, add the category to each line."
9512 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
9513 (dts (org-ical-ts-to-string
9514 (format-time-string (cdr org-time-stamp-formats) (current-time))
9515 "DTSTART"))
9516 hd ts ts2 state (inc t) pos scheduledp deadlinep donep tmp pri)
9517 (save-excursion
9518 (goto-char (point-min))
9519 (while (re-search-forward org-ts-regexp nil t)
9520 (setq pos (match-beginning 0)
9521 ts (match-string 0)
9522 inc t
9523 hd (org-get-heading))
9524 (if (looking-at re2)
9525 (progn
9526 (goto-char (match-end 0))
9527 (setq ts2 (match-string 1) inc nil))
9528 (setq ts2 ts
9529 tmp (buffer-substring (max (point-min)
9530 (- pos org-ds-keyword-length))
9531 pos)
9532 deadlinep (string-match org-deadline-regexp tmp)
9533 scheduledp (string-match org-scheduled-regexp tmp)
9534 donep (org-entry-is-done-p)))
9535 (if (or (string-match org-tr-regexp hd)
9536 (string-match org-ts-regexp hd))
9537 (setq hd (replace-match "" t t hd)))
9538 (if combine
9539 (setq hd (concat hd " (category " category ")")))
9540 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
9541 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
9542 (princ (format "BEGIN:VEVENT
9543 %s
9544 %s
9545 SUMMARY:%s
9546 END:VEVENT\n"
9547 (org-ical-ts-to-string ts "DTSTART")
9548 (org-ical-ts-to-string ts2 "DTEND" inc)
9549 hd)))
9550 (when org-icalendar-include-todo
9551 (goto-char (point-min))
9552 (while (re-search-forward org-todo-line-regexp nil t)
9553 (setq state (match-string 1))
9554 (unless (equal state org-done-string)
9555 (setq hd (match-string 3))
9556 (if (string-match org-priority-regexp hd)
9557 (setq pri (string-to-char (match-string 2 hd))
9558 hd (concat (substring hd 0 (match-beginning 1))
9559 (substring hd (- (match-end 1)))))
9560 (setq pri org-default-priority))
9561 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
9562 (- org-lowest-priority ?A))))))
9563
9564 (princ (format "BEGIN:VTODO
9565 %s
9566 SUMMARY:%s
9567 SEQUENCE:1
9568 PRIORITY:%d
9569 END:VTODO\n"
9570 dts hd pri))))))))
9571
9572 (defun org-start-icalendar-file (name)
9573 "Start an iCalendar file by inserting the header."
9574 (let ((user user-full-name)
9575 (calname "something")
9576 (name (or name "unknown"))
9577 (timezone "FIXME"))
9578 (princ
9579 (format "BEGIN:VCALENDAR
9580 VERSION:2.0
9581 X-WR-CALNAME:%s
9582 PRODID:-//%s//Emacs with Org-mode//EN
9583 X-WR-TIMEZONE:Europe/Amsterdam
9584 CALSCALE:GREGORIAN\n" name user timezone))))
9585
9586 (defun org-finish-icalendar-file ()
9587 "Finish an iCalendar file by inserting the END statement."
9588 (princ "END:VCALENDAR\n"))
9589
9590 (defun org-ical-ts-to-string (s keyword &optional inc)
9591 "Take a time string S and convert it to iCalendar format.
9592 KEYWORD is added in front, to make a complete line like DTSTART....
9593 When INC is non-nil, increase the hour by two (if time string contains
9594 a time), or the day by one (if it does not contain a time)."
9595 (let ((t1 (org-parse-time-string s 'nodefault))
9596 t2 fmt have-time time)
9597 (if (and (car t1) (nth 1 t1) (nth 2 t1))
9598 (setq t2 t1 have-time t)
9599 (setq t2 (org-parse-time-string s)))
9600 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
9601 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
9602 (when inc
9603 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
9604 (setq time (encode-time s mi h d m y)))
9605 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
9606 (concat keyword (format-time-string fmt time))))
9607
9608
9609 ;;; Key bindings
9610
9611 ;; - Bindings in Org-mode map are currently
9612 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9613 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9614 ;; e (?) useful from outline-mode
9615 ;; i k @ expendable from outline-mode
9616 ;; 0123456789 ! %^& ()_{} " `' free
9617
9618 ;; Make `C-c C-x' a prefix key
9619 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
9620
9621 ;; TAB key with modifiers
9622 (define-key org-mode-map "\C-i" 'org-cycle)
9623 (define-key org-mode-map [(meta tab)] 'org-complete)
9624 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
9625 ;; The following line is necessary under Suse GNU/Linux
9626 (unless org-xemacs-p
9627 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9628 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9629
9630 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9631 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
9632 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9633 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
9634 (define-key org-mode-map [(meta return)] 'org-meta-return)
9635 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
9636 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
9637
9638 ;; Cursor keys with modifiers
9639 (define-key org-mode-map [(meta left)] 'org-metaleft)
9640 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
9641 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
9642 (define-key org-mode-map [(meta right)] 'org-metaright)
9643 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
9644 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
9645 (define-key org-mode-map [(meta up)] 'org-metaup)
9646 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
9647 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
9648 (define-key org-mode-map [(meta down)] 'org-metadown)
9649 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
9650 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
9651
9652 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9653 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
9654 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9655 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
9656 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9657 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
9658 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9659 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
9660 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9661 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
9662 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9663 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
9664 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9665 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-timestamp-down-day)
9666 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9667 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-timestamp-up-day)
9668
9669 ;; All the other keys
9670 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9671 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9672 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9673 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9674 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9675 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9676 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9677 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9678 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9679 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9680 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9681 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9682 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9683 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9684 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9685 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
9686 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9687 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9688 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9689 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9690 (define-key org-mode-map "\C-c[" 'org-add-file)
9691 (define-key org-mode-map "\C-c]" 'org-remove-file)
9692 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9693 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9694 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9695 (define-key org-mode-map "\C-m" 'org-return)
9696 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9697 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9698 (define-key org-mode-map "\C-c+" 'org-table-sum)
9699 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9700 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9701 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9702 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9703 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9704 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9705 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9706 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9707 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9708 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9709 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9710 ;; OPML support is only an option for the future
9711 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9712 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9713 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
9714 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
9715 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
9716 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
9717 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9718 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9719 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9720 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
9721 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
9722
9723 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
9724 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
9725 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
9726
9727 (defsubst org-table-p () (org-at-table-p))
9728
9729 (defun org-self-insert-command (N)
9730 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9731 If the cursor is in a table looking at whitespace, the whitespace is
9732 overwritten, and the table is not marked as requiring realignment."
9733 (interactive "p")
9734 (if (and (org-table-p)
9735 (or
9736 (and org-table-auto-blank-field
9737 (member last-command
9738 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
9739 (org-table-blank-field))
9740 t)
9741 (eq N 1)
9742 (looking-at "[^|\n]* +|"))
9743 (let (org-table-may-need-update)
9744 (goto-char (1- (match-end 0)))
9745 (delete-backward-char 1)
9746 (goto-char (match-beginning 0))
9747 (self-insert-command N))
9748 (setq org-table-may-need-update t)
9749 (self-insert-command N)))
9750
9751 ;; FIXME:
9752 ;; The following two functions might still be optimized to trigger
9753 ;; re-alignment less frequently.
9754
9755 (defun org-delete-backward-char (N)
9756 "Like `delete-backward-char', insert whitespace at field end in tables.
9757 When deleting backwards, in tables this function will insert whitespace in
9758 front of the next \"|\" separator, to keep the table aligned. The table will
9759 still be marked for re-alignment, because a narrow field may lead to a
9760 reduced column width."
9761 (interactive "p")
9762 (if (and (org-table-p)
9763 (eq N 1)
9764 (string-match "|" (buffer-substring (point-at-bol) (point)))
9765 (looking-at ".*?|"))
9766 (let ((pos (point)))
9767 (backward-delete-char N)
9768 (skip-chars-forward "^|")
9769 (insert " ")
9770 (goto-char (1- pos)))
9771 (backward-delete-char N)))
9772
9773 (defun org-delete-char (N)
9774 "Like `delete-char', but insert whitespace at field end in tables.
9775 When deleting characters, in tables this function will insert whitespace in
9776 front of the next \"|\" separator, to keep the table aligned. The table
9777 will still be marked for re-alignment, because a narrow field may lead to
9778 a reduced column width."
9779 (interactive "p")
9780 (if (and (org-table-p)
9781 (not (bolp))
9782 (not (= (char-after) ?|))
9783 (eq N 1))
9784 (if (looking-at ".*?|")
9785 (let ((pos (point)))
9786 (replace-match (concat
9787 (substring (match-string 0) 1 -1)
9788 " |"))
9789 (goto-char pos)))
9790 (delete-char N)))
9791
9792 ;; How to do this: Measure non-white length of current string
9793 ;; If equal to column width, we should realign.
9794
9795 (defun org-remap (map &rest commands)
9796 "In MAP, remap the functions given in COMMANDS.
9797 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
9798 (let (new old)
9799 (while commands
9800 (setq old (pop commands) new (pop commands))
9801 (if (fboundp 'command-remapping)
9802 (define-key map (vector 'remap old) new)
9803 (substitute-key-definition old new map global-map)))))
9804
9805 (when (eq org-enable-table-editor 'optimized)
9806 ;; If the user wants maximum table support, we need to hijack
9807 ;; some standard editing functions
9808 (org-remap org-mode-map
9809 'self-insert-command 'org-self-insert-command
9810 'delete-char 'org-delete-char
9811 'delete-backward-char 'org-delete-backward-char)
9812 (define-key org-mode-map "|" 'org-force-self-insert))
9813
9814 (defun org-shiftcursor-error ()
9815 "Throw an error because Shift-Cursor command was applied in wrong context."
9816 (error "This command is only active in tables and on headlines"))
9817
9818 (defun org-shifttab ()
9819 "Global visibility cycling or move to previous table field.
9820 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
9821 See the individual commands for more information."
9822 (interactive)
9823 (cond
9824 ((org-at-table-p) (org-table-previous-field))
9825 (t (org-cycle '(4)))))
9826
9827 (defun org-shiftmetaleft ()
9828 "Promote subtree or delete table column.
9829 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
9830 See the individual commands for more information."
9831 (interactive)
9832 (cond
9833 ((org-at-table-p) (org-table-delete-column))
9834 ((org-on-heading-p) (org-promote-subtree))
9835 (t (org-shiftcursor-error))))
9836
9837 (defun org-shiftmetaright ()
9838 "Demote subtree or insert table column.
9839 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
9840 See the individual commands for more information."
9841 (interactive)
9842 (cond
9843 ((org-at-table-p) (org-table-insert-column))
9844 ((org-on-heading-p) (org-demote-subtree))
9845 (t (org-shiftcursor-error))))
9846
9847 (defun org-shiftmetaup (&optional arg)
9848 "Move subtree up or kill table row.
9849 Calls `org-move-subtree-up' or `org-table-kill-row', depending on context.
9850 See the individual commands for more information."
9851 (interactive "P")
9852 (cond
9853 ((org-at-table-p) (org-table-kill-row))
9854 ((org-on-heading-p) (org-move-subtree-up arg))
9855 (t (org-shiftcursor-error))))
9856 (defun org-shiftmetadown (&optional arg)
9857 "Move subtree down or insert table row.
9858 Calls `org-move-subtree-down' or `org-table-insert-row', depending on context.
9859 See the individual commands for more information."
9860 (interactive "P")
9861 (cond
9862 ((org-at-table-p) (org-table-insert-row arg))
9863 ((org-on-heading-p) (org-move-subtree-down arg))
9864 (t (org-shiftcursor-error))))
9865
9866 (defun org-metaleft (&optional arg)
9867 "Promote heading or move table column to left.
9868 Calls `org-do-promote' or `org-table-move-column', depending on context.
9869 See the individual commands for more information."
9870 (interactive "P")
9871 (cond
9872 ((org-at-table-p) (org-table-move-column 'left))
9873 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9874 (t (backward-word (prefix-numeric-value arg)))))
9875
9876 (defun org-metaright (&optional arg)
9877 "Demote subtree or move table column to right.
9878 Calls `org-do-demote' or `org-table-move-column', depending on context.
9879 See the individual commands for more information."
9880 (interactive "P")
9881 (cond
9882 ((org-at-table-p) (org-table-move-column nil))
9883 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9884 (t (forward-word (prefix-numeric-value arg)))))
9885
9886 (defun org-metaup (&optional arg)
9887 "Move subtree up or move table row up.
9888 Calls `org-move-subtree-up' or `org-table-move-row', depending on context.
9889 See the individual commands for more information."
9890 (interactive "P")
9891 (cond
9892 ((org-at-table-p) (org-table-move-row 'up))
9893 ((org-on-heading-p) (org-move-subtree-up arg))
9894 (t (org-shiftcursor-error))))
9895
9896 (defun org-metadown (&optional arg)
9897 "Move subtree down or move table row down.
9898 Calls `org-move-subtree-down' or `org-table-move-row', depending on context.
9899 See the individual commands for more information."
9900 (interactive "P")
9901 (cond
9902 ((org-at-table-p) (org-table-move-row nil))
9903 ((org-on-heading-p) (org-move-subtree-down arg))
9904 (t (org-shiftcursor-error))))
9905
9906 (defun org-shiftup (&optional arg)
9907 "Increase item in timestamp or increase priority of current item.
9908 Calls `org-timestamp-up' or `org-priority-up', depending on context.
9909 See the individual commands for more information."
9910 (interactive "P")
9911 (cond
9912 ((org-at-timestamp-p) (org-timestamp-up arg))
9913 (t (org-priority-up))))
9914
9915 (defun org-shiftdown (&optional arg)
9916 "Decrease item in timestamp or decrease priority of current item.
9917 Calls `org-timestamp-down' or `org-priority-down', depending on context.
9918 See the individual commands for more information."
9919 (interactive "P")
9920 (cond
9921 ((org-at-timestamp-p) (org-timestamp-down arg))
9922 (t (org-priority-down))))
9923
9924 (defun org-copy-special ()
9925 "Copy region in table or copy current subtree.
9926 Calls `org-table-copy' or `org-copy-subtree', depending on context.
9927 See the individual commands for more information."
9928 (interactive)
9929 (call-interactively
9930 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9931
9932 (defun org-cut-special ()
9933 "Cut region in table or cut current subtree.
9934 Calls `org-table-copy' or `org-cut-subtree', depending on context.
9935 See the individual commands for more information."
9936 (interactive)
9937 (call-interactively
9938 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9939
9940 (defun org-paste-special (arg)
9941 "Paste rectangular region into table, or past subtree relative to level.
9942 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
9943 See the individual commands for more information."
9944 (interactive "P")
9945 (if (org-at-table-p)
9946 (org-table-paste-rectangle)
9947 (org-paste-subtree arg)))
9948
9949 (defun org-ctrl-c-ctrl-c (&optional arg)
9950 "Call realign table, or recognize a table.el table, or update keywords.
9951 When the cursor is inside a table created by the table.el package,
9952 activate that table. Otherwise, if the cursor is at a normal table
9953 created with org.el, re-align that table. This command works even if
9954 the automatic table editor has been turned off.
9955 If the cursor is in one of the special #+KEYWORD lines, this triggers
9956 scanning the buffer for these lines and updating the information.
9957 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
9958 (interactive "P")
9959 (let ((org-enable-table-editor t))
9960 (cond
9961 ((org-at-table.el-p)
9962 (require 'table)
9963 (beginning-of-line 1)
9964 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9965 (table-recognize-table))
9966 ((org-at-table-p)
9967 (org-table-maybe-eval-formula)
9968 (if arg
9969 (org-table-recalculate t)
9970 (org-table-maybe-recalculate-line))
9971 (org-table-align))
9972 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9973 (cond
9974 ((equal (match-string 1) "TBLFM")
9975 ;; Recalculate the table before this line
9976 (save-excursion
9977 (beginning-of-line 1)
9978 (skip-chars-backward " \r\n\t")
9979 (if (org-at-table-p) (org-table-recalculate t))))
9980 (t
9981 (org-mode-restart))))
9982 ((org-region-active-p)
9983 (org-table-convert-region (region-beginning) (region-end) arg))
9984 ((and (region-beginning) (region-end))
9985 (if (y-or-n-p "Convert inactive region to table? ")
9986 (org-table-convert-region (region-beginning) (region-end) arg)
9987 (error "Abort")))
9988 (t (error "No table at point, and no region to make one")))))
9989
9990 (defun org-mode-restart ()
9991 "Restart Org-mode, to scan again for special lines.
9992 Also updates the keyword regular expressions."
9993 (interactive)
9994 (let ((org-inhibit-startup t)) (org-mode))
9995 (message "Org-mode restarted to refresh keyword and special line setup"))
9996
9997 (defun org-return ()
9998 "Goto next table row or insert a newline.
9999 Calls `org-table-next-row' or `newline', depending on context.
10000 See the individual commands for more information."
10001 (interactive)
10002 (cond
10003 ((org-at-table-p)
10004 (org-table-justify-field-maybe)
10005 (org-table-next-row))
10006 (t (newline))))
10007
10008 (defun org-meta-return (&optional arg)
10009 "Insert a new heading or wrap a region in a table.
10010 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
10011 See the individual commands for more information."
10012 (interactive "P")
10013 (cond
10014 ((org-at-table-p)
10015 (org-table-wrap-region arg))
10016 (t (org-insert-heading))))
10017
10018 ;;; Menu entries
10019
10020 ;; Define the Org-mode menus
10021 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
10022 '("Tbl"
10023 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
10024 ["Next Field" org-cycle (org-at-table-p)]
10025 ["Previous Field" org-shifttab (org-at-table-p)]
10026 ["Next Row" org-return (org-at-table-p)]
10027 "--"
10028 ["Blank Field" org-table-blank-field (org-at-table-p)]
10029 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
10030 "--"
10031 ("Column"
10032 ["Move Column Left" org-metaleft (org-at-table-p)]
10033 ["Move Column Right" org-metaright (org-at-table-p)]
10034 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
10035 ["Insert Column" org-shiftmetaright (org-at-table-p)])
10036 ("Row"
10037 ["Move Row Up" org-metaup (org-at-table-p)]
10038 ["Move Row Down" org-metadown (org-at-table-p)]
10039 ["Delete Row" org-shiftmetaup (org-at-table-p)]
10040 ["Insert Row" org-shiftmetadown (org-at-table-p)]
10041 "--"
10042 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
10043 ("Rectangle"
10044 ["Copy Rectangle" org-copy-special (org-at-table-p)]
10045 ["Cut Rectangle" org-cut-special (org-at-table-p)]
10046 ["Paste Rectangle" org-paste-special (org-at-table-p)]
10047 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
10048 "--"
10049 ("Calculate"
10050 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
10051 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10052 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
10053 "--"
10054 ["Recalculate line" org-table-recalculate (org-at-table-p)]
10055 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
10056 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
10057 "--"
10058 ["Sum Column/Rectangle" org-table-sum
10059 (or (org-at-table-p) (org-region-active-p))]
10060 ["Which Column?" org-table-current-column (org-at-table-p)])
10061 ["Debug Formulas"
10062 (setq org-table-formula-debug (not org-table-formula-debug))
10063 :style toggle :selected org-table-formula-debug]
10064 "--"
10065 ["Invisible Vlines" org-table-toggle-vline-visibility
10066 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
10067 "--"
10068 ["Create" org-table-create (and (not (org-at-table-p))
10069 org-enable-table-editor)]
10070 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
10071 ["Import from File" org-table-import (not (org-at-table-p))]
10072 ["Export to File" org-table-export (org-at-table-p)]
10073 "--"
10074 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
10075
10076 (easy-menu-define org-org-menu org-mode-map "Org menu"
10077 '("Org"
10078 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
10079 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
10080 ["Sparse Tree" org-occur t]
10081 ["Show All" show-all t]
10082 "--"
10083 ["New Heading" org-insert-heading t]
10084 ("Navigate Headings"
10085 ["Up" outline-up-heading t]
10086 ["Next" outline-next-visible-heading t]
10087 ["Previous" outline-previous-visible-heading t]
10088 ["Next Same Level" outline-forward-same-level t]
10089 ["Previous Same Level" outline-backward-same-level t]
10090 "--"
10091 ["Jump" org-goto t])
10092 ("Edit Structure"
10093 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
10094 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
10095 "--"
10096 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
10097 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
10098 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
10099 "--"
10100 ["Promote Heading" org-metaleft (not (org-at-table-p))]
10101 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
10102 ["Demote Heading" org-metaright (not (org-at-table-p))]
10103 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
10104 "--"
10105 ["Archive Subtree" org-archive-subtree t])
10106 "--"
10107 ("TODO Lists"
10108 ["TODO/DONE/-" org-todo t]
10109 ["Show TODO Tree" org-show-todo-tree t]
10110 "--"
10111 ["Set Priority" org-priority t]
10112 ["Priority Up" org-shiftup t]
10113 ["Priority Down" org-shiftdown t])
10114 ("Dates and Scheduling"
10115 ["Timestamp" org-time-stamp t]
10116 ["Timestamp (inactive)" org-time-stamp-inactive t]
10117 ("Change Date"
10118 ["1 Day Later" org-timestamp-up-day t]
10119 ["1 Day Earlier" org-timestamp-down-day t]
10120 ["1 ... Later" org-shiftup t]
10121 ["1 ... Earlier" org-shiftdown t])
10122 ["Compute Time Range" org-evaluate-time-range t]
10123 ["Schedule Item" org-schedule t]
10124 ["Deadline" org-deadline t]
10125 "--"
10126 ["Goto Calendar" org-goto-calendar t]
10127 ["Date from Calendar" org-date-from-calendar t])
10128 "--"
10129 ("Timeline/Agenda"
10130 ["Show TODO Tree this File" org-show-todo-tree t]
10131 ["Check Deadlines this File" org-check-deadlines t]
10132 ["Timeline Current File" org-timeline t]
10133 "--"
10134 ["Agenda" org-agenda t])
10135 ("File List for Agenda")
10136 "--"
10137 ("Hyperlinks"
10138 ["Store Link (Global)" org-store-link t]
10139 ["Insert Link" org-insert-link t]
10140 ["Follow Link" org-open-at-point t])
10141 "--"
10142 ("Export"
10143 ["ASCII" org-export-as-ascii t]
10144 ["Extract Visible Text" org-export-copy-visible t]
10145 ["HTML" org-export-as-html t]
10146 ["HTML and Open" org-export-as-html-and-open t]
10147 ; ["OPML" org-export-as-opml nil]
10148 "--"
10149 ["iCalendar this file" org-export-icalendar-this-file t]
10150 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
10151 :active t :keys "C-c C-x C-i"]
10152 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
10153 "--"
10154 ["Option Template" org-insert-export-options-template t]
10155 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
10156 "--"
10157 ("Documentation"
10158 ["Show Version" org-version t]
10159 ["Info Documentation" org-info t])
10160 ("Customize"
10161 ["Browse Org Group" org-customize t]
10162 "--"
10163 ["Build Full Customize Menu" org-create-customize-menu
10164 (fboundp 'customize-menu-create)])
10165 "--"
10166 ["Refresh setup" org-mode-restart t]
10167 ))
10168
10169 (defun org-info (&optional node)
10170 "Read documentation for Org-mode in the info system.
10171 With optional NODE, go directly to that node."
10172 (interactive)
10173 (require 'info)
10174 (Info-goto-node (format "(org)%s" (or node ""))))
10175
10176 (defun org-install-agenda-files-menu ()
10177 (easy-menu-change
10178 '("Org") "File List for Agenda"
10179 (append
10180 (list
10181 ["Edit File List" (customize-variable 'org-agenda-files) t]
10182 ["Add Current File to List" org-add-file t]
10183 ["Remove Current File from List" org-remove-file t]
10184 "--")
10185 (mapcar 'org-file-menu-entry org-agenda-files))))
10186
10187 ;;; Documentation
10188
10189 (defun org-customize ()
10190 "Call the customize function with org as argument."
10191 (interactive)
10192 (customize-browse 'org))
10193
10194 (defun org-create-customize-menu ()
10195 "Create a full customization menu for Org-mode, insert it into the menu."
10196 (interactive)
10197 (if (fboundp 'customize-menu-create)
10198 (progn
10199 (easy-menu-change
10200 '("Org") "Customize"
10201 `(["Browse Org group" org-customize t]
10202 "--"
10203 ,(customize-menu-create 'org)
10204 ["Set" Custom-set t]
10205 ["Save" Custom-save t]
10206 ["Reset to Current" Custom-reset-current t]
10207 ["Reset to Saved" Custom-reset-saved t]
10208 ["Reset to Standard Settings" Custom-reset-standard t]))
10209 (message "\"Org\"-menu now contains full customization menu"))
10210 (error "Cannot expand menu (outdated version of cus-edit.el)")))
10211
10212 ;;; Miscellaneous stuff
10213
10214 (defun org-move-line-down (arg)
10215 "Move the current line down. With prefix argument, move it past ARG lines."
10216 (interactive "p")
10217 (let ((col (current-column))
10218 beg end pos)
10219 (beginning-of-line 1) (setq beg (point))
10220 (beginning-of-line 2) (setq end (point))
10221 (beginning-of-line (+ 1 arg))
10222 (setq pos (move-marker (make-marker) (point)))
10223 (insert (delete-and-extract-region beg end))
10224 (goto-char pos)
10225 (move-to-column col)))
10226
10227 (defun org-move-line-up (arg)
10228 "Move the current line up. With prefix argument, move it past ARG lines."
10229 (interactive "p")
10230 (let ((col (current-column))
10231 beg end pos)
10232 (beginning-of-line 1) (setq beg (point))
10233 (beginning-of-line 2) (setq end (point))
10234 (beginning-of-line (- arg))
10235 (setq pos (move-marker (make-marker) (point)))
10236 (insert (delete-and-extract-region beg end))
10237 (goto-char pos)
10238 (move-to-column col)))
10239
10240 ;; Functions needed for Emacs/XEmacs region compatibility
10241
10242 (defun org-region-active-p ()
10243 "Is `transient-mark-mode' on and the region active?
10244 Works on both Emacs and XEmacs."
10245 (if org-ignore-region
10246 nil
10247 (if org-xemacs-p
10248 (and zmacs-regions (region-active-p))
10249 (and transient-mark-mode mark-active))))
10250
10251 (defun org-add-to-invisibility-spec (arg)
10252 "Add elements to `buffer-invisibility-spec'.
10253 See documentation for `buffer-invisibility-spec' for the kind of elements
10254 that can be added."
10255 (cond
10256 ((fboundp 'add-to-invisibility-spec)
10257 (add-to-invisibility-spec arg))
10258 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
10259 (setq buffer-invisibility-spec (list arg)))
10260 (t
10261 (setq buffer-invisibility-spec
10262 (cons arg buffer-invisibility-spec)))))
10263
10264 (defun org-remove-from-invisibility-spec (arg)
10265 "Remove elements from `buffer-invisibility-spec'."
10266 (if (fboundp 'remove-from-invisibility-spec)
10267 (remove-from-invisibility-spec arg)
10268 (if (consp buffer-invisibility-spec)
10269 (setq buffer-invisibility-spec
10270 (delete arg buffer-invisibility-spec)))))
10271
10272 (defun org-in-invisibility-spec-p (arg)
10273 "Is ARG a member of `buffer-invisibility-spec'?."
10274 (if (consp buffer-invisibility-spec)
10275 (member arg buffer-invisibility-spec)
10276 nil))
10277
10278 (defun org-image-file-name-regexp ()
10279 "Return regexp matching the file names of images."
10280 (if (fboundp 'image-file-name-regexp)
10281 (image-file-name-regexp)
10282 (let ((image-file-name-extensions
10283 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
10284 "xbm" "xpm" "pbm" "pgm" "ppm")))
10285 (concat "\\."
10286 (regexp-opt (nconc (mapcar 'upcase
10287 image-file-name-extensions)
10288 image-file-name-extensions)
10289 t)
10290 "\\'"))))
10291
10292 ;; Functions needed for compatibility with old outline.el
10293
10294 ;; The following functions capture almost the entire compatibility code
10295 ;; between the different versions of outline-mode. The only other place
10296 ;; where this is important are the font-lock-keywords. Search for
10297 ;; `org-noutline-p' to find it.
10298
10299 ;; C-a should go to the beginning of a *visible* line, also in the
10300 ;; new outline.el. I guess this should be patched into Emacs?
10301 (defun org-beginning-of-line ()
10302 "Go to the beginning of the current line. If that is invisible, continue
10303 to a visible line beginning. This makes the function of C-a more intuitive."
10304 (interactive)
10305 (beginning-of-line 1)
10306 (if (bobp)
10307 nil
10308 (backward-char 1)
10309 (if (org-invisible-p)
10310 (while (and (not (bobp)) (org-invisible-p))
10311 (backward-char 1)
10312 (beginning-of-line 1))
10313 (forward-char 1))))
10314 (when org-noutline-p
10315 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
10316
10317 (defun org-invisible-p ()
10318 "Check if point is at a character currently not visible."
10319 (if org-noutline-p
10320 ;; Early versions of noutline don't have `outline-invisible-p'.
10321 (if (fboundp 'outline-invisible-p)
10322 (outline-invisible-p)
10323 (get-char-property (point) 'invisible))
10324 (save-excursion
10325 (skip-chars-backward "^\r\n")
10326 (equal (char-before) ?\r))))
10327
10328 (defun org-back-to-heading (&optional invisible-ok)
10329 "Move to previous heading line, or beg of this line if it's a heading.
10330 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
10331 (if org-noutline-p
10332 (outline-back-to-heading invisible-ok)
10333 (if (looking-at outline-regexp)
10334 t
10335 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
10336 outline-regexp)
10337 nil t)
10338 (if invisible-ok
10339 (progn (goto-char (match-end 1))
10340 (looking-at outline-regexp)))
10341 (error "Before first heading")))))
10342
10343 (defun org-on-heading-p (&optional invisible-ok)
10344 "Return t if point is on a (visible) heading line.
10345 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
10346 (if org-noutline-p
10347 (outline-on-heading-p 'invisible-ok)
10348 (save-excursion
10349 (skip-chars-backward "^\n\r")
10350 (and (looking-at outline-regexp)
10351 (or invisible-ok
10352 (bobp)
10353 (equal (char-before) ?\n))))))
10354
10355 (defun org-up-heading-all (arg)
10356 "Move to the heading line of which the present line is a subheading.
10357 This function considers both visible and invisible heading lines.
10358 With argument, move up ARG levels."
10359 (if org-noutline-p
10360 (if (fboundp 'outline-up-heading-all)
10361 (outline-up-heading-all arg) ; emacs 21 version of outline.el
10362 (outline-up-heading arg t)) ; emacs 22 version of outline.el
10363 (org-back-to-heading t)
10364 (looking-at outline-regexp)
10365 (if (<= (- (match-end 0) (match-beginning 0)) arg)
10366 (error "Cannot move up %d levels" arg)
10367 (re-search-backward
10368 (concat "[\n\r]" (regexp-quote
10369 (make-string (- (match-end 0) (match-beginning 0) arg)
10370 ?*))
10371 "[^*]"))
10372 (forward-char 1))))
10373
10374 (defun org-show-hidden-entry ()
10375 "Show an entry where even the heading is hidden."
10376 (save-excursion
10377 (if (not org-noutline-p)
10378 (progn
10379 (org-back-to-heading t)
10380 (org-flag-heading nil)))
10381 (org-show-entry)))
10382
10383 (defun org-check-occur-regexp (regexp)
10384 "If REGEXP starts with \"^\", modify it to check for \\r as well.
10385 Of course, only for the old outline mode."
10386 (if org-noutline-p
10387 regexp
10388 (if (string-match "^\\^" regexp)
10389 (concat "[\n\r]" (substring regexp 1))
10390 regexp)))
10391
10392 (defun org-flag-heading (flag &optional entry)
10393 "Flag the current heading. FLAG non-nil means make invisible.
10394 When ENTRY is non-nil, show the entire entry."
10395 (save-excursion
10396 (org-back-to-heading t)
10397 (if (not org-noutline-p)
10398 ;; Make the current headline visible
10399 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
10400 ;; Check if we should show the entire entry
10401 (if entry
10402 (progn
10403 (org-show-entry)
10404 (save-excursion ;; FIXME: Is this the fix for points in the -|
10405 ;; middle of text? |
10406 (and (outline-next-heading) ;; |
10407 (org-flag-heading nil)))) ; show the next heading _|
10408 (outline-flag-region (max 1 (1- (point)))
10409 (save-excursion (outline-end-of-heading) (point))
10410 (if org-noutline-p
10411 flag
10412 (if flag ?\r ?\n))))))
10413
10414 (defun org-show-subtree ()
10415 "Show everything after this heading at deeper levels."
10416 (outline-flag-region
10417 (point)
10418 (save-excursion
10419 (outline-end-of-subtree) (outline-next-heading) (point))
10420 (if org-noutline-p nil ?\n)))
10421
10422 (defun org-show-entry ()
10423 "Show the body directly following this heading.
10424 Show the heading too, if it is currently invisible."
10425 (interactive)
10426 (save-excursion
10427 (org-back-to-heading t)
10428 (outline-flag-region
10429 (1- (point))
10430 (save-excursion
10431 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
10432 (or (match-beginning 1) (point-max)))
10433 (if org-noutline-p nil ?\n))))
10434
10435
10436 (defun org-make-options-regexp (kwds)
10437 "Make a regular expression for keyword lines."
10438 (concat
10439 (if org-noutline-p "^" "[\n\r]")
10440 "#?[ \t]*\\+\\("
10441 (mapconcat 'regexp-quote kwds "\\|")
10442 "\\):[ \t]*"
10443 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10444
10445 ;; Make `bookmark-jump' show the jump location if it was hidden.
10446 (eval-after-load "bookmark"
10447 '(if (boundp 'bookmark-after-jump-hook)
10448 ;; We can use the hook
10449 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
10450 ;; Hook not available, use advice
10451 (defadvice bookmark-jump (after org-make-visible activate)
10452 "Make the position visible."
10453 (org-bookmark-jump-unhide))))
10454
10455 (defun org-bookmark-jump-unhide ()
10456 "Unhide the current position, to show the bookmark location."
10457 (and (eq major-mode 'org-mode)
10458 (or (org-invisible-p)
10459 (save-excursion (goto-char (max (point-min) (1- (point))))
10460 (org-invisible-p)))
10461 (org-show-hierarchy-above)))
10462
10463 ;;; Finish up
10464
10465 (provide 'org)
10466
10467 (run-hooks 'org-load-hook)
10468
10469 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10470 ;;; org.el ends here