]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Install to the CVS repository what I forgot to install in my
[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.17
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.17
84 ;; - HTML export specifies character set depending on coding-system.
85 ;;
86 ;; Version 3.16
87 ;; - In tables, directly after the field motion commands like TAB and RET,
88 ;; typing a character will blank the field. Can be turned off with
89 ;; variable `org-table-auto-blank-field'.
90 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
91 ;; and are not linked to the calendar.
92 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
93 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
94 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
95 ;; standard meaning of C-h after a prefix key (show prefix bindings).
96 ;;
97 ;; Version 3.15
98 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
99 ;; of unmodified entry text. `C-c :' toggles this keyword.
100 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
101 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
102 ;; color, to reduce the amount of aggressive color in the buffer.
103 ;;
104 ;; Version 3.14
105 ;; - Formulas for individual fields in table.
106 ;; - Automatic recalculation in calculating tables.
107 ;; - Named fields and columns in tables.
108 ;; - Fixed bug with calling `org-archive' several times in a row.
109 ;;
110 ;; Version 3.13
111 ;; - Efficiency improvements: Fewer table re-alignments needed.
112 ;; - New special lines in tables, for defining names for individual cells.
113 ;;
114 ;; Version 3.12
115 ;; - Tables can store formulas (one per column) and compute fields.
116 ;; Not quite like a full spreadsheet, but very powerful.
117 ;; - table.el keybinding is now `C-c ~'.
118 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
119 ;; - Small changes to keys in agenda buffer. Affected keys:
120 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
121 ;; - Bug fixes.
122 ;;
123 ;; Version 3.11
124 ;; - Links inserted with C-c C-l are now by default enclosed in angle
125 ;; brackets. See the new variable `org-link-format'.
126 ;; - ">" terminates a link, this is a way to have several links in a line.
127 ;; Both "<" and ">" are no longer allowed as characters in a link.
128 ;; - Archiving of finished tasks.
129 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
130 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
131 ;; - Compatibility problems with viper-mode fixed.
132 ;; - Improved html export of tables.
133 ;; - Various clean-up changes.
134 ;;
135 ;; Version 3.10
136 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
137 ;;
138 ;; Version 3.09
139 ;; - Time-of-day specifications in agenda are extracted and placed
140 ;; into the prefix. Timed entries can be placed into a time grid for
141 ;; day.
142 ;;
143 ;; Version 3.08
144 ;; - "|" no longer allowed as part of a link, to allow links in tables.
145 ;; - The prefix of items in the agenda buffer can be configured.
146 ;; - Cleanup.
147 ;;
148 ;; Version 3.07
149 ;; - Some folding incinsistencies removed.
150 ;; - BBDB links to company-only entries.
151 ;; - Bug fixes and global cleanup.
152 ;;
153 ;; Version 3.06
154 ;; - M-S-RET inserts a new TODO heading.
155 ;; - New startup option `content'.
156 ;; - Better visual response when TODO items in agenda change status.
157 ;; - Window positioning after visibility state changes optimized and made
158 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
159 ;;
160 ;; Version 3.05
161 ;; - Agenda entries from the diary are linked to the diary file, so
162 ;; adding and editing diary entries can be done directly from the agenda.
163 ;; - Many calendar/diary commands available directly from agenda.
164 ;; - Field copying in tables with S-RET does increment.
165 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
166 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
167 ;;
168 ;; Version 3.04
169 ;; - Table editor optimized to need fewer realignments, and to keep
170 ;; table shape when typing in fields.
171 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
172 ;; into arbitrary major modes.
173 ;; - Fixed bug with realignment in XEmacs.
174 ;; - Startup options can be set with special #+STARTUP line.
175 ;; - Heading following a match in org-occur can be suppressed.
176 ;;
177 ;; Version 3.03
178 ;; - Copyright transfer to the FSF.
179 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
180 ;; - Timeline now always contains today, and `.' jumps to it.
181 ;; - Table editor:
182 ;; - cut and paste of rectangular regions in tables
183 ;; - command to convert org-mode table to table.el table and back
184 ;; - command to treat several cells like a paragraph and fill it
185 ;; - command to convert a buffer region to a table
186 ;; - import/export tables as tab-separated files (exchange with Excel)
187 ;; - Agenda:
188 ;; - Sorting mechanism for agenda items rewritten from scratch.
189 ;; - Sorting fully configurable.
190 ;; - Entries specifying a time are sorted together.
191 ;; - Completion also covers option keywords after `#-'.
192 ;; - Bug fixes.
193 ;;
194 ;; Version 3.01
195 ;; - New reference card, thanks to Philip Rooke for creating it.
196 ;; - Single file agenda renamed to "Timeline". It no longer shows
197 ;; warnings about upcoming deadlines/overdue scheduled items.
198 ;; That functionality is now limited to the (multifile) agenda.
199 ;; - When reading a date, the calendar can be manipulated with keys.
200 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
201 ;; - Minor bug fixes and documentation improvements.
202
203 ;;; Code:
204
205 (eval-when-compile (require 'cl) (require 'calendar))
206 (require 'outline)
207 (require 'time-date)
208 (require 'easymenu)
209
210 (defvar calc-embedded-close-formula)
211 (defvar calc-embedded-open-formula)
212 (defvar font-lock-unfontify-region-function)
213
214 ;;; Customization variables
215
216 (defvar org-version "3.17"
217 "The version number of the file org.el.")
218 (defun org-version ()
219 (interactive)
220 (message "Org-mode version %s" org-version))
221
222 ;; The following two constants are for compatibility with different Emacs
223 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
224 ;; The compatibility code in org.el is based on these two constants.
225 (defconst org-xemacs-p (featurep 'xemacs)
226 "Are we running xemacs?")
227 (defconst org-noutline-p (featurep 'noutline)
228 "Are we using the new outline mode?")
229
230 (defgroup org nil
231 "Outline-based notes management and organizer "
232 :tag "Org"
233 :group 'outlines
234 :group 'hypermedia
235 :group 'calendar)
236
237 (defgroup org-startup nil
238 "Options concerning startup of Org-mode."
239 :tag "Org Startup"
240 :group 'org)
241
242 (defcustom org-CUA-compatible nil
243 "Non-nil means use alternative key bindings for S-<cursor movement>.
244 Org-mode used S-<cursor movement> for changing timestamps and priorities.
245 S-<cursor movement> is also used for example by `CUA-mode' to select text.
246 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
247 alternative bindings. Setting this variable to t will replace the following
248 keys both in Org-mode and in the Org-agenda buffer.
249
250 S-RET -> C-S-RET
251 S-up -> M-p
252 S-down -> M-n
253 S-left -> M--
254 S-right -> M-+
255
256 If you do not like the alternative keys, take a look at the variable
257 `org-disputed-keys'.
258
259 This option is only relevant at load-time of Org-mode. Changing it requires
260 a restart of Emacs to become effective."
261 :group 'org-startup
262 :type 'boolean)
263
264 (defvar org-disputed-keys
265 '((S-up [(shift up)] [(meta ?p)])
266 (S-down [(shift down)] [(meta ?n)])
267 (S-left [(shift left)] [(meta ?-)])
268 (S-right [(shift right)] [(meta ?+)])
269 (S-return [(shift return)] [(control shift return)]))
270 "Keys for which Org-mode and other modes compete.
271 This is an alist, cars are symbols for lookup, 1st element is the default key,
272 second element will be used when `org-CUA-compatible' is t.")
273
274 (defun org-key (key)
275 "Select a key according to `org-CUA-compatible'."
276 (nth (if org-CUA-compatible 2 1)
277 (or (assq key org-disputed-keys)
278 (error "Invalid Key %s in `org-key'" key))))
279
280 (defcustom org-startup-folded t
281 "Non-nil means, entering Org-mode will switch to OVERVIEW.
282 This can also be configured on a per-file basis by adding one of
283 the following lines anywhere in the buffer:
284
285 #+STARTUP: fold
286 #+STARTUP: nofold
287 #+STARTUP: content"
288 :group 'org-startup
289 :type '(choice
290 (const :tag "nofold: show all" nil)
291 (const :tag "fold: overview" t)
292 (const :tag "content: all headlines" content)))
293
294 (defcustom org-startup-truncated t
295 "Non-nil means, entering Org-mode will set `truncate-lines'.
296 This is useful since some lines containing links can be very long and
297 uninteresting. Also tables look terrible when wrapped."
298 :group 'org-startup
299 :type 'boolean)
300
301 (defcustom org-startup-with-deadline-check nil
302 "Non-nil means, entering Org-mode will run the deadline check.
303 This means, if you start editing an org file, you will get an
304 immediate reminder of any due deadlines.
305 This can also be configured on a per-file basis by adding one of
306 the following lines anywhere in the buffer:
307
308 #+STARTUP: dlcheck
309 #+STARTUP: nodlcheck"
310 :group 'org-startup
311 :type 'boolean)
312
313 (defcustom org-insert-mode-line-in-empty-file nil
314 "Non-nil means insert the first line setting Org-mode in empty files.
315 When the function `org-mode' is called interactively in an empty file, this
316 normally means that the file name does not automatically trigger Org-mode.
317 To ensure that the file will always be in Org-mode in the future, a
318 line enforcing Org-mode will be inserted into the buffer, if this option
319 has been set."
320 :group 'org-startup
321 :type 'boolean)
322
323 (defgroup org-keywords nil
324 "Options concerning TODO items in Org-mode."
325 :tag "Org Keywords"
326 :group 'org)
327
328 (defcustom org-todo-keywords '("TODO" "DONE")
329 "List of TODO entry keywords.
330 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
331 considered to mean that the entry is \"done\". All the other mean that
332 action is required, and will make the entry show up in todo lists, diaries
333 etc.
334 The command \\[org-todo] cycles an entry through these states, and an
335 additional state where no keyword is present. For details about this
336 cycling, see also the variable `org-todo-interpretation'
337 Changes become only effective after restarting Emacs."
338 :group 'org-keywords
339 :type '(repeat (string :tag "Keyword")))
340
341 (defcustom org-todo-interpretation 'sequence
342 "Controls how TODO keywords are interpreted.
343 \\<org-mode-map>Possible values are `sequence' and `type'.
344 This variable is only relevant if `org-todo-keywords' contains more than two
345 states. There are two ways how these keywords can be used:
346
347 - As a sequence in the process of working on a TODO item, for example
348 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
349 org-todo-interpretation 'sequence)
350
351 - As different types of TODO items, for example
352 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
353 org-todo-interpretation 'type)
354
355 When the states are interpreted as a sequence, \\[org-todo] always cycles
356 to the next state, in order to walk through all different states. So with
357 \\[org-todo], you turn an empty entry into the state TODO. When you started
358 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
359 later to VERIFY and finally to DONE.
360
361 When the states are interpreted as types, \\[org-todo] still cycles through
362 when it is called several times in direct succession, in order to initially
363 select the type. However, if not called immediately after a previous
364 \\[org-todo], it switches from each type directly to DONE. So with the
365 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
366 RELAXED. If you later return to this entry and press \\[org-todo] again,
367 RELAXED will not be changed REMIND, but directly to DONE.
368
369 You can create a large number of types. To initially select a
370 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
371 type with completion. Of course, you can also type the keyword
372 directly into the buffer. M-TAB completes TODO keywords at the
373 beginning of a headline."
374 :group 'org-keywords
375 :type '(choice (const sequence)
376 (const type)))
377
378 (defcustom org-default-priority ?B
379 "The default priority of TODO items.
380 This is the priority an item get if no explicit priority is given."
381 :group 'org-keywords
382 :type 'character)
383
384 (defcustom org-lowest-priority ?C
385 "The lowest priority of TODO items. A character like ?A, ?B etc."
386 :group 'org-keywords
387 :type 'character)
388
389 (defcustom org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 A deadline is this string, followed by a time stamp. Should be a word,
392 terminated by a colon. You can insert a schedule keyword and
393 a timestamp with \\[org-deadline].
394 Changes become only effective after restarting Emacs."
395 :group 'org-keywords
396 :type 'string)
397
398 (defcustom org-scheduled-string "SCHEDULED:"
399 "String to mark scheduled TODO entries.
400 A schedule is this string, followed by a time stamp. Should be a word,
401 terminated by a colon. You can insert a schedule keyword and
402 a timestamp with \\[org-schedule].
403 Changes become only effective after restarting Emacs."
404 :group 'org-keywords
405 :type 'string)
406
407 (defcustom org-comment-string "COMMENT"
408 "Entries starting with this keyword will never be exported.
409 An entry can be toggled between COMMENT and normal with
410 \\[org-toggle-comment].
411 Changes become only effective after restarting Emacs."
412 :group 'org-keywords
413 :type 'string)
414
415 (defcustom org-quote-string "QUOTE"
416 "Entries starting with this keyword will be exported in fixed-width font.
417 Quoting applies only to the text in the entry following the headline, and does
418 not extend beyond the next headline, even if that is lower level.
419 An entry can be toggled between QUOTE and normal with
420 \\[org-toggle-fixed-width-section]"
421 :group 'org-keywords
422 :type 'string)
423
424 (defcustom org-after-todo-state-change-hook nil
425 "Hook which is run after the state of a TODO item was changed.
426 The new state (a string with a todo keyword, or nil) is available in the
427 Lisp variable `state'."
428 :group 'org-keywords
429 :type 'hook)
430
431 ;; Variables for pre-computed regular expressions, all buffer local
432 (defvar org-todo-kwd-priority-p nil
433 "Do TODO items have priorities?")
434 (make-variable-buffer-local 'org-todo-kwd-priority-p)
435 (defvar org-todo-kwd-max-priority nil
436 "Maximum priority of TODO items.")
437 (make-variable-buffer-local 'org-todo-kwd-max-priority)
438 (defvar org-ds-keyword-length 12
439 "Maximum length of the Deadline and SCHEDULED keywords.")
440 (make-variable-buffer-local 'org-ds-keyword-length)
441 (defvar org-done-string nil
442 "The last string in `org-todo-keywords', indicating an item is DONE.")
443 (make-variable-buffer-local 'org-done-string)
444 (defvar org-todo-regexp nil
445 "Matches any of the TODO state keywords.")
446 (make-variable-buffer-local 'org-todo-regexp)
447 (defvar org-not-done-regexp nil
448 "Matches any of the TODO state keywords except the last one.")
449 (make-variable-buffer-local 'org-not-done-regexp)
450 (defvar org-todo-line-regexp nil
451 "Matches a headline and puts TODO state into group 2 if present.")
452 (make-variable-buffer-local 'org-todo-line-regexp)
453 (defvar org-nl-done-regexp nil
454 "Matches newline followed by a headline with the DONE keyword.")
455 (make-variable-buffer-local 'org-nl-done-regexp)
456 (defvar org-looking-at-done-regexp nil
457 "Matches the DONE keyword a point.")
458 (make-variable-buffer-local 'org-looking-at-done-regexp)
459 (defvar org-deadline-regexp nil
460 "Matches the DEADLINE keyword.")
461 (make-variable-buffer-local 'org-deadline-regexp)
462 (defvar org-deadline-time-regexp nil
463 "Matches the DEADLINE keyword together with a time stamp.")
464 (make-variable-buffer-local 'org-deadline-time-regexp)
465 (defvar org-deadline-line-regexp nil
466 "Matches the DEADLINE keyword and the rest of the line.")
467 (make-variable-buffer-local 'org-deadline-line-regexp)
468 (defvar org-scheduled-regexp nil
469 "Matches the SCHEDULED keyword.")
470 (make-variable-buffer-local 'org-scheduled-regexp)
471 (defvar org-scheduled-time-regexp nil
472 "Matches the SCHEDULED keyword together with a time stamp.")
473 (make-variable-buffer-local 'org-scheduled-time-regexp)
474
475 (defvar org-category nil
476 "Variable used by org files to set a category for agenda display.
477 Such files should use a file variable to set it, for example
478
479 -*- mode: org; org-category: \"ELisp\"
480
481 or contain a special line
482
483 #+CATEGORY: ELisp
484
485 If the file does not specify a category, then file's base name
486 is used instead.")
487
488 (defgroup org-time nil
489 "Options concerning time stamps and deadlines in Org-mode."
490 :tag "Org Time"
491 :group 'org)
492
493 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
494 "Formats for `format-time-string' which are used for time stamps.
495 It is not recommended to change this constant.")
496
497
498 (defcustom org-deadline-warning-days 30
499 "No. of days before expiration during which a deadline becomes active.
500 This variable governs the display in the org file."
501 :group 'org-time
502 :type 'number)
503
504 (defcustom org-popup-calendar-for-date-prompt t
505 "Non-nil means, pop up a calendar when prompting for a date.
506 In the calendar, the date can be selected with mouse-1. However, the
507 minibuffer will also be active, and you can simply enter the date as well.
508 When nil, only the minibuffer will be available."
509 :group 'org-time
510 :type 'number)
511
512 (defcustom org-calendar-follow-timestamp-change t
513 "Non-nil means, make the calendar window follow timestamp changes.
514 When a timestamp is modified and the calendar window is visible, it will be
515 moved to the new date."
516 :group 'org-time
517 :type 'boolean)
518
519 (defgroup org-agenda nil
520 "Options concerning agenda display Org-mode."
521 :tag "Org Agenda"
522 :group 'org)
523
524 (defcustom org-agenda-files nil
525 "A list of org files for agenda/diary display.
526 Entries are added to this list with \\[org-add-file] and removed with
527 \\[org-remove-file]. You can also use customize to edit the list."
528 :group 'org-agenda
529 :type '(repeat file))
530
531 (defcustom org-select-timeline-window t
532 "Non-nil means, after creating a timeline, move cursor into Timeline window.
533 When nil, cursor will remain in the current window."
534 :group 'org-agenda
535 :type 'boolean)
536
537 (defcustom org-select-agenda-window t
538 "Non-nil means, after creating an agenda, move cursor into Agenda window.
539 When nil, cursor will remain in the current window."
540 :group 'org-agenda
541 :type 'boolean)
542
543 (defcustom org-fit-agenda-window t
544 "Non-nil means, change window size of agenda to fit content."
545 :group 'org-agenda
546 :type 'boolean)
547
548 (defcustom org-agenda-show-all-dates t
549 "Non-nil means, `org-agenda' shows every day in the selected range.
550 When nil, only the days which actually have entries are shown."
551 :group 'org-agenda
552 :type 'boolean)
553
554 ;; FIXME: First day of month works only for current month because it would
555 ;; require a variable ndays treatment.
556 (defcustom org-agenda-start-on-weekday 1
557 "Non-nil means, start the overview always on the specified weekday.
558 0 Denotes Sunday, 1 denotes Monday etc.
559 When nil, always start on the current day."
560 :group 'org-agenda
561 :type '(choice (const :tag "Today" nil)
562 (const :tag "First day of month" t)
563 (number :tag "Weekday No.")))
564
565 (defcustom org-agenda-ndays 7
566 "Number of days to include in overview display."
567 :group 'org-agenda
568 :type 'number)
569
570 (defcustom org-agenda-include-all-todo t
571 "Non-nil means, the agenda will always contain all TODO entries.
572 When nil, date-less entries will only be shown if `org-agenda' is called
573 with a prefix argument.
574 When non-nil, the TODO entries will be listed at the top of the agenda, before
575 the entries for specific days."
576 :group 'org-agenda
577 :type 'boolean)
578
579 (defcustom org-agenda-include-diary nil
580 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
581 :group 'org-agenda
582 :type 'boolean)
583
584 (defcustom org-calendar-to-agenda-key [?c]
585 "The key to be installed in `calendar-mode-map' for switching to the agenda.
586 The command `org-calendar-goto-agenda' will be bound to this key. The
587 default is the character `c' because then`c' can be used to switch back and
588 force between agenda and calendar."
589 :group 'org-agenda
590 :type 'sexp)
591
592 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
593 "Sorting structure for the agenda items of a single day.
594 This is a list of symbols which will be used in sequence to determine
595 if an entry should be listed before another entry. The following
596 symbols are recognized.
597
598 time-up Put entries with time-of-day indications first, early first
599 time-down Put entries with time-of-day indications first, late first
600 category-keep Keep the default order of categories, corresponding to the
601 sequence in `org-agenda-files'.
602 category-up Sort alphabetically by category, A-Z.
603 category-down Sort alphabetically by category, Z-A.
604 priority-up Sort numerically by priority, high priority last.
605 priority-down Sort numerically by priority, high priority first.
606
607 The different possibilities will be tried in sequence, and testing stops
608 if one comparison returns a \"not-equal\". For example, the default
609 '(time-up category-keep priority-down)
610 means: Pull out all entries having a specified time of day and sort them,
611 in order to make a time schedule for the current day the first thing in the
612 agenda listing for the day. Of the entries without a time indication, keep
613 the grouped in categories, don't sort the categories, but keep them in
614 the sequence given in `org-agenda-files'. Within each category sort by
615 priority.
616
617 Leaving out `category-keep' would mean that items will be sorted across
618 categories by priority."
619 :group 'org-agenda
620 :type '(repeat
621 (choice
622 (const time-up)
623 (const time-down)
624 (const category-keep)
625 (const category-up)
626 (const category-down)
627 (const priority-up)
628 (const priority-down))))
629
630 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
631 "Format specification for the prefix of items in the agenda buffer.
632 This format works similar to a printf format, with the following meaning:
633
634 %c the category of the item, \"Diary\" for entries from the diary, or
635 as given by the CATEGORY keyword or derived from the file name.
636 %t the time-of-day specification if one applies to the entry, in the
637 format HH:MM
638 %s Scheduling/Deadline information, a short string
639
640 All specifiers work basically like the standard `%s' of printf, but may
641 contain two additional characters: A question mark just after the `%' and
642 a whitespace/punctuation character just before the final letter.
643
644 If the first character after `%' is a question mark, the entire field
645 will only be included if the corresponding value applies to the
646 current entry. This is useful for fields which should have fixed
647 width when present, but zero width when absent. For example,
648 \"%?-12t\" will result in a 12 character time field if a time of the
649 day is specified, but will completely disappear in entries which do
650 not contain a time.
651
652 If there is punctuation or whitespace character just before the final
653 format letter, this character will be appended to the field value if
654 the value is not empty. For example, the format \"%-12:c\" leads to
655 \"Diary: \" if the category is \"Diary\". If the category were be
656 empty, no additional colon would be interted.
657
658 The default value of this option is \" %-12:c%?-12t% s\", meaning:
659 - Indent the line with two space characters
660 - Give the category in a 12 chars wide field, padded with whitespace on
661 the right (because of `-'). Append a colon if there is a category
662 (because of `:').
663 - If there is a time-of-day, put it into a 12 chars wide field. If no
664 time, don't put in an empty field, just skip it (because of '?').
665 - Finally, put the scheduling information and append a whitespace.
666
667 As another example, if you don't want the time-of-day of entries in
668 the prefix, you could use:
669
670 (setq org-agenda-prefix-format \" %-11:c% s\")
671
672 See also the variable `org-agenda-remove-times-when-in-prefix'."
673 :type 'string
674 :group 'org-agenda)
675
676 (defcustom org-timeline-prefix-format " % s"
677 "Like `org-agenda-prefix-format', but for the timeline of a single file."
678 :type 'string
679 :group 'org-agenda)
680
681 (defvar org-prefix-format-compiled nil
682 "The compiled version of the most recently used prefix format.
683 Depending on which command was used last, this may be the compiled version
684 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
685
686 (defcustom org-agenda-use-time-grid t
687 "Non-nil means, show a time grid in the agenda schedule.
688 A time grid is a set of lines for specific times (like every two hours between
689 8:00 and 20:00. The items scheduled for a day at specific times are
690 sorted in between these lines.
691 For deails about when the grid will be shown, and what it will look like, see
692 the variable `org-agenda-time-grid'."
693 :group 'org-agenda
694 :type 'boolean)
695
696 (defcustom org-agenda-time-grid
697 '((daily today require-timed)
698 "----------------"
699 (800 1000 1200 1400 1600 1800 2000))
700
701 "The settings for time grid for agenda display.
702 This is a list of three items. The first item is again a list. It contains
703 symbols specifying conditions when the grid should be displayed:
704
705 daily if the agenda shows a single day
706 weekly if the agenda shows an entire week
707 today show grid on current date, independent of daily/weekly display
708 require-timed show grid only if at least on item has a time specification
709
710 The second item is a string which will be places behing the grid time.
711
712 The third item is a list of integers, indicating the times that should have
713 a grid line."
714 :group 'org-agenda
715 :type
716 '(list
717 (set :greedy t :tag "Grid Display Options"
718 (const :tag "Show grid in single day agenda display" daily)
719 (const :tag "Show grid in weekly agenda display" weekly)
720 (const :tag "Always show grid for today" today)
721 (const :tag "Show grid only if any timed entries are present"
722 require-timed)
723 (const :tag "Skip grid times already present in an entry"
724 remove-match))
725 (string :tag "Grid String")
726 (repeat :tag "Grid Times" (integer :tag "Time"))))
727
728 (defcustom org-agenda-remove-times-when-in-prefix t
729 "Non-nil means, remove duplicate time specifications in agenda items.
730 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
731 time-of-day specification in a headline or diary entry is extracted and
732 placed into the prefix. If this option is non-nil, the original specification
733 \(a timestamp or -range, or just a plain time(range) specification like
734 11:30-4pm) will be removed for agenda display. This makes the agenda less
735 cluttered.
736 The option can be t or nil. It may also be the symbol `beg', indicating
737 that the time should only be removed what it is located at the beginning of
738 the headline/diary entry."
739 :group 'org-agenda
740 :type '(choice
741 (const :tag "Always" t)
742 (const :tag "Never" nil)
743 (const :tag "When at beginning of entry" beg)))
744
745 (defcustom org-sort-agenda-notime-is-late t
746 "Non-nil means, items without time are considered late.
747 This is only relevant for sorting. When t, items which have no explicit
748 time like 15:30 will be considered as 24:01, i.e. later than any items which
749 do have a time. When nil, the default time is before 0:00. You can use this
750 option to decide if the schedule for today should come before or after timeless
751 agenda entries."
752 :group 'org-agenda
753 :type 'boolean)
754
755 (defgroup org-structure nil
756 "Options concerning structure editing in Org-mode."
757 :tag "Org Structure"
758 :group 'org)
759
760 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
761 "Hook that is run after `org-cycle' has changed the buffer visibility.
762 The function(s) in this hook must accept a single argument which indicates
763 the new state that was set by the most recent `org-cycle' command. The
764 argument is a symbol. After a global state change, it can have the values
765 `overview', `content', or `all'. After a local state change, it can have
766 the values `folded', `children', or `subtree'."
767 :group 'org-structure
768 :type 'hook)
769
770 (defcustom org-occur-hook '(org-first-headline-recenter)
771 "Hook that is run after `org-occur' has constructed a sparse tree.
772 This can be used to recenter the window to show as much of the structure
773 as possible."
774 :group 'org-structure
775 :type 'hook)
776
777 (defcustom org-level-color-stars-only nil
778 "Non-nil means fontify only the stars in each headline.
779 When nil, the entire headline is fontified.
780 After changin this, requires restart of Emacs to become effective."
781 :group 'org-structure
782 :type 'boolean)
783
784 (defcustom org-adapt-indentation t
785 "Non-nil means, adapt indentation when promoting and demoting.
786 When this is set and the *entire* text in an entry is indented, the
787 indentation is increased by one space in a demotion command, and
788 decreased by one in a promotion command. If any line in the entry
789 body starts at column 0, indentation is not changed at all."
790 :group 'org-structure
791 :type 'boolean)
792
793 (defcustom org-enable-fixed-width-editor t
794 "Non-nil means, lines starting with \":\" are treated as fixed-width.
795 This currently only means, they are never auto-wrapped.
796 When nil, such lines will be treated like ordinary lines.
797 See also the QUOTE keyword."
798 :group 'org-structure
799 :type 'boolean)
800
801 (defcustom org-cycle-emulate-tab t
802 "Where should `org-cycle' emulate TAB.
803 nil Never
804 white Only in completely white lines
805 t Everywhere except in headlines"
806 :group 'org-structure
807 :type '(choice (const :tag "Never" nil)
808 (const :tag "Only in completely white lines" white)
809 (const :tag "Everywhere except in headlines" t)
810 ))
811
812 (defcustom org-show-following-heading t
813 "Non-nil means, show heading following match in `org-occur'.
814 When doing an `org-occur' it is useful to show the headline which
815 follows the match, even if they do not match the regexp. This makes it
816 easier to edit directly inside the sparse tree. However, if you use
817 org-occur mainly as an overview, the following headlines are
818 unnecessary clutter."
819 :group 'org-structure
820 :type 'boolean)
821
822 (defcustom org-archive-location "%s_archive::"
823 "The location where subtrees should be archived.
824 This string consists of two parts, separated by a double-colon.
825
826 The first part is a file name - when omitted, archiving happens in the same
827 file. %s will be replaced by the current file name (without directory part).
828 Archiving to a different file is useful to keep archived entries from
829 contributing to the Org-mode Agenda.
830
831 The part after the double colon is a headline. The archived entries will be
832 filed under that headline. When omitted, the subtrees are simply filed away
833 at the end of the file, as top-level entries.
834
835 Here are a few examples:
836 \"%s_archive::\"
837 If the current file is Projects.org, archive in file
838 Projects.org_archive, as top-level trees. This is the default.
839
840 \"::* Archived Tasks\"
841 Archive in the current file, under the top-level headline
842 \"* Archived Tasks\".
843
844 \"~/org/archive.org::\"
845 Archive in file ~/org/archive.org (absolute path), as top-level trees.
846
847 \"basement::** Finished Tasks\"
848 Archive in file ./basement (relative path), as level 3 trees
849 below the level 2 heading \"** Finished Tasks\".
850
851 You may set this option on a per-file basis by adding to the buffer a
852 line like
853
854 #+ARCHIVE: basement::** Finished Tasks"
855 :group 'org-structure
856 :type 'string)
857
858 (defcustom org-archive-mark-done t
859 "Non-nil means, mark archived entries as DONE."
860 :group 'org-structure
861 :type 'boolean)
862
863 (defcustom org-archive-stamp-time t
864 "Non-nil means, add a time stamp to archived entries.
865 The time stamp will be added directly after the TODO state keyword in the
866 first line, so it is probably best to use this in combinations with
867 `org-archive-mark-done'."
868 :group 'org-structure
869 :type 'boolean)
870
871 (defgroup org-link nil
872 "Options concerning links in Org-mode."
873 :tag "Org Link"
874 :group 'org)
875
876 (defcustom org-link-format "<%s>"
877 "Default format for linkes in the buffer.
878 This is a format string for printf, %s will be replaced by the link text.
879 If you want to make sure that your link is always properly terminated,
880 include angle brackets into this format, like \"<%s>\". Some people also
881 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
882 :group 'org-link
883 :type '(choice
884 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
885 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
886 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
887 (string :tag "Other" :value "<%s>")))
888
889 (defcustom org-allow-space-in-links t
890 "Non-nil means, file names in links may contain space characters.
891 When nil, it becomes possible to put several links into a line.
892 Note that in tables, a link never extends accross fields, so in a table
893 it is always possible to put several links into a line.
894 Changing this varable requires a re-launch of Emacs of become effective."
895 :group 'org-link
896 :type 'boolean)
897
898 (defcustom org-line-numbers-in-file-links t
899 "Non-nil means, file links from `org-store-link' contain line numbers.
900 The line number will be added to the file name with :NNN and interpreted
901 by the command `org-open-at-point'.
902 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
903 negates this setting for the duration of the command."
904 :group 'org-link
905 :type 'boolean)
906
907 (defcustom org-keep-stored-link-after-insertion nil
908 "Non-nil means, keep link in list for entire session.
909
910 The command `org-store-link' adds a link pointing to the current
911 location to an internal list. These links accumulate during a session.
912 The command `org-insert-link' can be used to insert links into any
913 Org-mode file (offering completion for all stored links). When this
914 option is nil, every link which has been inserted once using \\[org-insert-link]
915 will be removed from the list, to make completing the unused links
916 more efficient."
917 :group 'org-link
918 :type 'boolean)
919
920 (defcustom org-link-frame-setup
921 '((vm . vm-visit-folder-other-frame)
922 (gnus . gnus-other-frame)
923 (file . find-file-other-window))
924 "Setup the frame configuration for following links.
925 When following a link with Emacs, it may often be useful to display
926 this link in another window or frame. This variable can be used to
927 set this up for the different types of links.
928 For VM, use any of
929 `vm-visit-folder'
930 `vm-visit-folder-other-frame'
931 For Gnus, use any of
932 `gnus'
933 `gnus-other-frame'
934 For FILE, use any of
935 `find-file'
936 `find-file-other-window'
937 `find-file-other-frame'
938 For the calendar, use the variable `calendar-setup'.
939 For BBDB, it is currently only possible to display the matches in
940 another window."
941 :group 'org-link
942 :type '(list
943 (cons (const vm)
944 (choice
945 (const vm-visit-folder)
946 (const vm-visit-folder-other-window)
947 (const vm-visit-folder-other-frame)))
948 (cons (const gnus)
949 (choice
950 (const gnus)
951 (const gnus-other-frame)))
952 (cons (const file)
953 (choice
954 (const find-file)
955 (const find-file-other-window)
956 (const find-file-other-frame)))))
957
958 (defcustom org-usenet-links-prefer-google nil
959 "Non-nil means, `org-store-link' will create web links to google groups.
960 When nil, Gnus will be used for such links.
961 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
962 negates this setting for the duration of the command."
963 :group 'org-link
964 :type 'boolean)
965
966 (defcustom org-open-non-existing-files nil
967 "Non-nil means, `org-open-file' will open non-existing file.
968 When nil, an error will be generated."
969 :group 'org-link
970 :type 'boolean)
971
972 (defcustom org-confirm-shell-links t
973 "Non-nil means, ask for confirmation before executing shell links.
974 The default is true, to keep new users from shooting into their own foot."
975 :group 'org-link
976 :type 'boolean)
977
978 (defconst org-file-apps-defaults-gnu
979 '((t . emacs)
980 ("jpg" . "xv %s")
981 ("gif" . "xv %s")
982 ("ppm" . "xv %s")
983 ("pgm" . "xv %s")
984 ("pbm" . "xv %s")
985 ("tif" . "xv %s")
986 ("png" . "xv %s")
987 ("ps" . "gv %s")
988 ("ps.gz" . "gv %s")
989 ("eps" . "gv %s")
990 ("eps.gz" . "gv %s")
991 ("dvi" . "xdvi %s")
992 ("mpeg" . "plaympeg %s")
993 ("mp3" . "plaympeg %s")
994 ("fig" . "xfig %s")
995 ("pdf" . "acroread %s")
996 ("doc" . "soffice %s")
997 ("ppt" . "soffice %s")
998 ("pps" . "soffice %s")
999 ("html" . "netscape -remote openURL(%s,new-window)")
1000 ("htm" . "netscape -remote openURL(%s,new-window)")
1001 ("xs" . "soffice %s"))
1002 "Default file applications on a UNIX/LINUX system.
1003 See `org-file-apps'.")
1004
1005 (defconst org-file-apps-defaults-macosx
1006 '((t . "open %s")
1007 ("ps" . "gv %s")
1008 ("ps.gz" . "gv %s")
1009 ("eps" . "gv %s")
1010 ("eps.gz" . "gv %s")
1011 ("dvi" . "xdvi %s")
1012 ("fig" . "xfig %s"))
1013 "Default file applications on a MacOS X system.
1014 The system \"open\" is known as a default, but we use X11 applications
1015 for some files for which the OS does not have a good default.
1016 See `org-file-apps'.")
1017
1018 (defconst org-file-apps-defaults-windowsnt
1019 '((t . (w32-shell-execute "open" file)))
1020 "Default file applications on a Windows NT system.
1021 The system \"open\" is used for most files.
1022 See `org-file-apps'.")
1023
1024 (defcustom org-file-apps
1025 '(
1026 ("txt" . emacs)
1027 ("tex" . emacs)
1028 ("ltx" . emacs)
1029 ("org" . emacs)
1030 ("el" . emacs)
1031 )
1032 "External applications for opening `file:path' items in a document.
1033 Org-mode uses system defaults for different file types, but
1034 you can use this variable to set the application for a given file
1035 extension. The entries in this list are cons cells with a file extension
1036 and the corresponding command. Possible values for the command are:
1037 `emacs' The file will be visited by the current Emacs process.
1038 `default' Use the default application for this file type.
1039 string A command to be executed by a shell; %s will be replaced
1040 by the path to the file.
1041 sexp A Lisp form which will be evaluated. The file path will
1042 be available in the Lisp variable `file'.
1043 For more examples, see the system specific constants
1044 `org-file-apps-defaults-macosx'
1045 `org-file-apps-defaults-windowsnt'
1046 `org-file-apps-defaults-gnu'."
1047 :group 'org-link
1048 :type '(repeat
1049 (cons (string :tag "Extension")
1050 (choice :value ""
1051 (const :tag "Visit with Emacs" 'emacs)
1052 (const :tag "Use system default" 'default)
1053 (string :tag "Command")
1054 (sexp :tag "Lisp form")))))
1055
1056
1057 (defgroup org-remember nil
1058 "Options concerning interaction with remember.el."
1059 :tag "Org Remember"
1060 :group 'org)
1061
1062 (defcustom org-directory "~/org"
1063 "Directory with org files.
1064 This directory will be used as default to prompt for org files.
1065 Used by the hooks for remember.el."
1066 :group 'org-remember
1067 :type 'directory)
1068
1069 (defcustom org-default-notes-file "~/.notes"
1070 "Default target for storing notes.
1071 Used by the hooks for remember.el. This can be a string, or nil to mean
1072 the value of `remember-data-file'."
1073 :group 'org-remember
1074 :type '(choice
1075 (const :tag "Default from remember-data-file" nil)
1076 file))
1077
1078 (defcustom org-reverse-note-order nil
1079 "Non-nil means, store new notes at the beginning of a file or entry.
1080 When nil, new notes will be filed to the end of a file or entry."
1081 :group 'org-remember
1082 :type '(choice
1083 (const :tag "Reverse always" t)
1084 (const :tag "Reverse never" nil)
1085 (repeat :tag "By file name regexp"
1086 (cons regexp boolean))))
1087
1088 (defgroup org-table nil
1089 "Options concerning tables in Org-mode."
1090 :tag "Org Table"
1091 :group 'org)
1092
1093 (defcustom org-enable-table-editor 'optimized
1094 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1095 When nil, such lines will be treated like ordinary lines.
1096
1097 When equal to the symbol `optimized', the table editor will be optimized to
1098 do the following
1099 - Use automatic overwrite mode in front of whitespace in table fields.
1100 This make the structure of the table stay in tact as long as the edited
1101 field does not exceed the column width.
1102 - Minimize the number of realigns. Normally, the table is aligned each time
1103 TAB or RET are pressed to move to another field. With optimization this
1104 happens only if changes to a field might have changed the column width.
1105 Optimization requires replacing the functions `self-insert-command',
1106 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1107 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1108 very good at guessing when a re-align will be necessary, but you can always
1109 force one with \\[org-ctrl-c-ctrl-c].
1110
1111 If you would like to use the optimized version in Org-mode, but the
1112 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1113
1114 This variable can be used to turn on and off the table editor during a session,
1115 but in order to toggle optimization, a restart is required.
1116
1117 See also the variable `org-table-auto-blank-field'."
1118 :group 'org-table
1119 :type '(choice
1120 (const :tag "off" nil)
1121 (const :tag "on" t)
1122 (const :tag "on, optimized" optimized)))
1123
1124 (defcustom org-table-auto-blank-field t
1125 "Non-nil means, automatically blank table field when starting to type into it.
1126 This only happens when typing immediately after a field motion
1127 command (TAB, S-TAB or RET).
1128 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1129 :group 'org-table
1130 :type 'boolean)
1131
1132 (defcustom org-table-default-size "5x2"
1133 "The default size for newly created tables, Columns x Rows."
1134 :group 'org-table
1135 :type 'string)
1136
1137 (defcustom org-table-automatic-realign t
1138 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1139 When nil, aligning is only done with \\[org-table-align], or after column
1140 removal/insertion."
1141 :group 'org-table
1142 :type 'boolean)
1143
1144 (defcustom org-table-spaces-around-separators '(1 . 1)
1145 "The number of spaces to be placed before and after separators."
1146 :group 'org-table
1147 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1148
1149 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1150 "The number of spaces to be placed before and after separators.
1151 This option applies when the column separators have been made invisible."
1152 :group 'org-table
1153 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1154
1155 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1156 "Regular expression for recognizing numbers in table columns.
1157 If a table column contains mostly numbers, it will be aligned to the
1158 right. If not, it will be aligned to the left.
1159
1160 The default value of this option is a regular expression which allows
1161 anything which looks remotely like a number as used in scientific
1162 context. For example, all of the following will be considered a
1163 number:
1164 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1165
1166 Other options offered by the customize interface are more restrictive."
1167 :group 'org-table
1168 :type '(choice
1169 (const :tag "Positive Integers"
1170 "^[0-9]+$")
1171 (const :tag "Integers"
1172 "^[-+]?[0-9]+$")
1173 (const :tag "Floating Point Numbers"
1174 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1175 (const :tag "Floating Point Number or Integer"
1176 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1177 (const :tag "Exponential, Floating point, Integer"
1178 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1179 (const :tag "Very General Number-Like"
1180 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1181 (string :tag "Regexp:")))
1182
1183 (defcustom org-table-number-fraction 0.5
1184 "Fraction of numbers in a column required to make the column align right.
1185 In a column all non-white fields are considered. If at least this
1186 fraction of fields is matched by `org-table-number-fraction',
1187 alignment to the right border applies."
1188 :group 'org-table
1189 :type 'number)
1190
1191 (defcustom org-export-highlight-first-table-line t
1192 "Non-nil means, highlight the first table line.
1193 In HTML export, this means use <th> instead of <td>.
1194 In tables created with table.el, this applies to the first table line.
1195 In Org-mode tables, all lines before the first horizontal separator
1196 line will be formatted with <th> tags."
1197 :group 'org-table
1198 :type 'boolean)
1199
1200 (defcustom org-table-tab-recognizes-table.el t
1201 "Non-nil means, TAB will automatically notice a table.el table.
1202 When it sees such a table, it moves point into it and - if necessary -
1203 calls `table-recognize-table'."
1204 :group 'org-table
1205 :type 'boolean)
1206
1207 (defgroup org-table-calculation nil
1208 "Options concerning tables in Org-mode."
1209 :tag "Org Table Calculation"
1210 :group 'org)
1211
1212 (defcustom org-table-copy-increment t
1213 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1214 :group 'org-table-calculation
1215 :type 'boolean)
1216
1217 (defcustom org-calc-default-modes
1218 '(calc-internal-prec 12
1219 calc-float-format (float 5)
1220 calc-angle-mode deg
1221 calc-prefer-frac nil
1222 calc-symbolic-mode nil
1223 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1224 calc-display-working-message t
1225 )
1226 "List with Calc mode settings for use in calc-eval for table formulas.
1227 The list must contain alternating symbols (calc modes variables and values.
1228 Don't remove any of the default settings, just change the values. Org-mode
1229 relies on the variables to be present in the list."
1230 :group 'org-table-calculation
1231 :type 'plist)
1232
1233 (defcustom org-table-formula-evaluate-inline t
1234 "Non-nil means, TAB and RET evaluate a formula in current table field.
1235 If the current field starts with an equal sign, it is assumed to be a formula
1236 which should be evaluated as described in the manual and in the documentation
1237 string of the command `org-table-eval-formula'. This feature requires the
1238 Emacs calc package.
1239 When this variable is nil, formula calculation is only available through
1240 the command \\[org-table-eval-formula]."
1241 :group 'org-table-calculation
1242 :type 'boolean)
1243
1244
1245 (defcustom org-table-formula-use-constants t
1246 "Non-nil means, interpret constants in formulas in tables.
1247 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1248 by the value given in `org-table-formula-constants', or by a value obtained
1249 from the `constants.el' package."
1250 :group 'org-table-calculation
1251 :type 'boolean)
1252
1253 (defcustom org-table-formula-constants nil
1254 "Alist with constant names and values, for use in table formulas.
1255 The car of each element is a name of a constant, without the `$' before it.
1256 The cdr is the value as a string. For example, if you'd like to use the
1257 speed of light in a formula, you would configure
1258
1259 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1260
1261 and then use it in an equation like `$1*$c'."
1262 :group 'org-table-calculation
1263 :type '(repeat
1264 (cons (string :tag "name")
1265 (string :tag "value"))))
1266
1267 (defcustom org-table-formula-numbers-only nil
1268 "Non-nil means, calculate only with numbers in table formulas.
1269 Then all input fields will be converted to a number, and the result
1270 must also be a number. When nil, calc's full potential is available
1271 in table calculations, including symbolics etc."
1272 :group 'org-table-calculation
1273 :type 'boolean)
1274
1275 (defcustom org-table-allow-automatic-line-recalculation t
1276 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1277 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1278 :group 'org-table-calculation
1279 :type 'boolean)
1280
1281 (defgroup org-export nil
1282 "Options for exporting org-listings."
1283 :tag "Org Export"
1284 :group 'org)
1285
1286 (defcustom org-export-language-setup
1287 '(("en" "Author" "Date" "Table of Contents")
1288 ("da" "Ophavsmand" "Dato" "Indhold")
1289 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1290 ("es" "Autor" "Fecha" "\xccndice")
1291 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1292 ("it" "Autore" "Data" "Indice")
1293 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1294 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1295 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1296 "Terms used in export text, translated to different languages.
1297 Use the variable `org-export-default-language' to set the language,
1298 or use the +OPTION lines for a per-file setting."
1299 :group 'org-export
1300 :type '(repeat
1301 (list
1302 (string :tag "HTML language tag")
1303 (string :tag "Author")
1304 (string :tag "Date")
1305 (string :tag "Table of Contents"))))
1306
1307 (defcustom org-export-default-language "en"
1308 "The default language of HTML export, as a string.
1309 This should have an association in `org-export-language-setup'"
1310 :group 'org-export
1311 :type 'string)
1312
1313 (defcustom org-export-headline-levels 3
1314 "The last level which is still exported as a headline.
1315 Inferior levels will produce itemize lists when exported.
1316 Note that a numeric prefix argument to an exporter function overrides
1317 this setting.
1318
1319 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1320 :group 'org-export
1321 :type 'number)
1322
1323 (defcustom org-export-with-section-numbers t
1324 "Non-nil means, add section numbers to headlines when exporting.
1325
1326 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1327 :group 'org-export
1328 :type 'boolean)
1329
1330 (defcustom org-export-with-toc t
1331 "Non-nil means, create a table of contents in exported files.
1332 The TOC contains headlines with levels up to`org-export-headline-levels'.
1333
1334 Headlines which contain any TODO items will be marked with \"(*)\" in
1335 ASCII export, and with red color in HTML output.
1336
1337 In HTML output, the TOC will be clickable.
1338
1339 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1340 :group 'org-export
1341 :type 'boolean)
1342
1343 (defcustom org-export-preserve-breaks nil
1344 "Non-nil means, preserve all line breaks when exporting.
1345 Normally, in HTML output paragraphs will be reformatted. In ASCII
1346 export, line breaks will always be preserved, regardless of this variable.
1347
1348 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1349 :group 'org-export
1350 :type 'boolean)
1351
1352 (defcustom org-export-html-inline-images t
1353 "Non-nil means, inline images into exported HTML pages.
1354 The link will still be to the original location of the image file.
1355 So if you are moving the page, lets say to your public HTML site,
1356 you will have to move the image and maybe change the link."
1357 :group 'org-export
1358 :type 'boolean)
1359
1360 (defcustom org-export-html-expand t
1361 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1362 When nil, these tags will be exported as plain text and therefore
1363 not be interpreted by a browser.
1364
1365 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1366 :group 'org-export
1367 :type 'boolean)
1368
1369 (defcustom org-export-with-fixed-width t
1370 "Non-nil means, lines starting with \":\" will be in fixed width font.
1371 This can be used to have pre-formatted text, fragments of code etc. For
1372 example
1373 : ;; Some Lisp examples
1374 : (while (defc cnt)
1375 : (ding))
1376 will be looking just like this in also HTML. In ASCII export, this option
1377 has no effect.
1378
1379 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1380 :group 'org-export
1381 :type 'boolean)
1382
1383 (defcustom org-export-with-tables t
1384 "If non-nil, lines starting with \"|\" define a table.
1385 For example:
1386
1387 | Name | Address | Birthday |
1388 |-------------+----------+-----------|
1389 | Arthur Dent | England | 29.2.2100 |
1390
1391 In ASCII export, this option has no effect.
1392
1393 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1394 :group 'org-export
1395 :type 'boolean)
1396
1397 (defcustom org-export-prefer-native-exporter-for-tables nil
1398 "Non-nil means, always export tables created with table.el natively.
1399 Natively means, use the HTML code generator in table.el.
1400 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1401 the table does not use row- or column-spanning). This has the
1402 advantage, that the automatic HTML conversions for math symbols and
1403 sub/superscripts can be applied. Org-mode's HTML generator is also
1404 much faster."
1405 :group 'org-export
1406 :type 'boolean)
1407
1408 (defcustom org-export-html-table-tag
1409 "<table border=1 cellspacing=0 cellpadding=6>"
1410 "The HTML tag used to start a table.
1411 This must be a <table> tag, but you may change the options like
1412 borders and spacing."
1413 :group 'org-export
1414 :type 'string)
1415
1416 (defcustom org-export-with-emphasize t
1417 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1418 If the export target supports emphasizing text, the word will be
1419 typeset in bold, italic, or underlined, respectively. Works only for
1420 single words, but you can say: I *really* *mean* *this*.
1421 In ASCII export, this option has no effect.
1422
1423 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1424 :group 'org-export
1425 :type 'boolean)
1426
1427 (defcustom org-match-sexp-depth 3
1428 "Number of stacked braces for sub/superscript matching.
1429 This has to be set before loading org.el to be effective."
1430 :group 'org-export
1431 :type 'integer)
1432
1433 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1434 (defcustom org-export-with-sub-superscripts t
1435 "Non-nil means, interpret \"_\" and \"^\" for export.
1436 When this option is turned on, you can use TeX-like syntax for sub- and
1437 superscripts. Several characters after \"_\" or \"^\" will be
1438 considered as a single item - so grouping with {} is normally not
1439 needed. For example, the following things will be parsed as single
1440 sub- or superscripts.
1441
1442 10^24 or 10^tau several digits will be considered 1 item
1443 10^-12 or 10^-tau a leading sign with digits or a word
1444 x^2-y^3 will be read as x^2 - y^3, because items are
1445 terminated by almost any nonword/nondigit char.
1446 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1447
1448 Still, ambiguity is possible - so when in doubt use {} to enclose the
1449 sub/superscript.
1450 In ASCII export, this option has no effect.
1451
1452 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1453 :group 'org-export
1454 :type 'boolean)
1455
1456 (defcustom org-export-with-TeX-macros t
1457 "Non-nil means, interpret simple TeX-like macros when exporting.
1458 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1459 No only real TeX macros will work here, but the standard HTML entities
1460 for math can be used as macro names as well. For a list of supported
1461 names in HTML export, see the constant `org-html-entities'.
1462 In ASCII export, this option has no effect.
1463
1464 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1465 :group 'org-export
1466 :type 'boolean)
1467
1468 (defcustom org-export-html-with-timestamp nil
1469 "If non-nil, write `org-export-html-html-helper-timestamp'
1470 into the exported html text. Otherwise, the buffer will just be saved
1471 to a file."
1472 :group 'org-export
1473 :type 'boolean)
1474
1475 (defcustom org-export-html-html-helper-timestamp
1476 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1477 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1478 :group 'org-export
1479 :type 'string)
1480
1481 (defcustom org-export-ascii-show-new-buffer t
1482 "Non-nil means, popup buffer containing the exported ASCII text.
1483 Otherwise the buffer will just be saved to a file and stay hidden."
1484 :group 'org-export
1485 :type 'boolean)
1486
1487 (defcustom org-export-html-show-new-buffer nil
1488 "Non-nil means, popup buffer containing the exported html text.
1489 Otherwise, the buffer will just be saved to a file and stay hidden."
1490 :group 'org-export
1491 :type 'boolean)
1492
1493 (defgroup org-faces nil
1494 "Faces for highlighting in Org-mode."
1495 :tag "Org Faces"
1496 :group 'org)
1497
1498 (defface org-level-1 ;; font-lock-function-name-face
1499 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1500 (((class color) (background light)) (:foreground "Blue"))
1501 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1502 (t (:inverse-video t :bold t)))
1503 "Face used for level 1 headlines."
1504 :group 'org-faces)
1505
1506 (defface org-level-2 ;; font-lock-variable-name-face
1507 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1508 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1509 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1510 (t (:bold t :italic t)))
1511 "Face used for level 2 headlines."
1512 :group 'org-faces)
1513
1514 (defface org-level-3 ;; font-lock-keyword-face
1515 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1516 (((class color) (background light)) (:foreground "Purple"))
1517 (((class color) (background dark)) (:foreground "Cyan"))
1518 (t (:bold t)))
1519 "Face used for level 3 headlines."
1520 :group 'org-faces)
1521
1522 (defface org-level-4 ;; font-lock-comment-face
1523 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1524 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1525 (((class color) (background light)) (:foreground "Firebrick"))
1526 (((class color) (background dark)) (:foreground "chocolate1"))
1527 (t (:bold t :italic t)))
1528 "Face used for level 4 headlines."
1529 :group 'org-faces)
1530
1531 (defface org-level-5 ;; font-lock-type-face
1532 '((((type tty) (class color)) (:foreground "green"))
1533 (((class color) (background light)) (:foreground "ForestGreen"))
1534 (((class color) (background dark)) (:foreground "PaleGreen"))
1535 (t (:bold t :underline t)))
1536 "Face used for level 5 headlines."
1537 :group 'org-faces)
1538
1539 (defface org-level-6 ;; font-lock-constant-face
1540 '((((type tty) (class color)) (:foreground "magenta"))
1541 (((class color) (background light)) (:foreground "CadetBlue"))
1542 (((class color) (background dark)) (:foreground "Aquamarine"))
1543 (t (:bold t :underline t)))
1544 "Face used for level 6 headlines."
1545 :group 'org-faces)
1546
1547 (defface org-level-7 ;; font-lock-builtin-face
1548 '((((type tty) (class color)) (:foreground "blue" :weight light))
1549 (((class color) (background light)) (:foreground "Orchid"))
1550 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1551 (t (:bold t)))
1552 "Face used for level 7 headlines."
1553 :group 'org-faces)
1554
1555 (defface org-level-8 ;; font-lock-string-face
1556 '((((type tty) (class color)) (:foreground "green"))
1557 (((class color) (background light)) (:foreground "RosyBrown"))
1558 (((class color) (background dark)) (:foreground "LightSalmon"))
1559 (t (:italic t)))
1560 "Face used for level 8 headlines."
1561 :group 'org-faces)
1562
1563 (defface org-special-keyword ;; font-lock-string-face
1564 '((((type tty) (class color)) (:foreground "green"))
1565 (((class color) (background light)) (:foreground "RosyBrown"))
1566 (((class color) (background dark)) (:foreground "LightSalmon"))
1567 (t (:italic t)))
1568 "Face used for level 8 headlines."
1569 :group 'org-faces)
1570
1571 (defface org-warning ;; font-lock-warning-face
1572 '((((type tty) (class color)) (:foreground "red"))
1573 (((class color) (background light)) (:foreground "Red" :bold t))
1574 (((class color) (background dark)) (:foreground "Red1" :bold t))
1575 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1576 (t (:inverse-video t :bold t)))
1577 "Face for deadlines and TODO keywords."
1578 :group 'org-faces)
1579
1580 (defcustom org-fontify-done-headline nil
1581 "Non-nil means, change the face of a headline if it is marked DONE.
1582 Normally, only the TODO/DONE keyword indicates the state of a headline.
1583 When this is non-nil, the headline after the keyword is set to the
1584 `org-headline-done' as an additional indication."
1585 :group 'org-faces
1586 :type 'boolean)
1587
1588 (defface org-headline-done ;; font-lock-string-face
1589 '((((type tty) (class color)) (:foreground "green"))
1590 (((class color) (background light)) (:foreground "RosyBrown"))
1591 (((class color) (background dark)) (:foreground "LightSalmon"))
1592 (t (:italic t)))
1593 "Face used to indicate that a headline is DONE. See also the variable
1594 `org-fontify-done-headline'."
1595 :group 'org-faces)
1596
1597 ;; Inheritance does not yet work for xemacs. So we just copy...
1598
1599 (defface org-deadline-announce
1600 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1601 (((class color) (background light)) (:foreground "Blue"))
1602 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1603 (t (:inverse-video t :bold t)))
1604 "Face for upcoming deadlines."
1605 :group 'org-faces)
1606
1607 (defface org-scheduled-today
1608 '((((type tty) (class color)) (:foreground "green"))
1609 (((class color) (background light)) (:foreground "DarkGreen"))
1610 (((class color) (background dark)) (:foreground "PaleGreen"))
1611 (t (:bold t :underline t)))
1612 "Face for items scheduled for a certain day."
1613 :group 'org-faces)
1614
1615 (defface org-scheduled-previously
1616 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1617 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1618 (((class color) (background light)) (:foreground "Firebrick"))
1619 (((class color) (background dark)) (:foreground "chocolate1"))
1620 (t (:bold t :italic t)))
1621 "Face for items scheduled previously, and not yet done."
1622 :group 'org-faces)
1623
1624 (defface org-formula
1625 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1626 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1627 (((class color) (background light)) (:foreground "Firebrick"))
1628 (((class color) (background dark)) (:foreground "chocolate1"))
1629 (t (:bold t :italic t)))
1630 "Face for items scheduled previously, and not yet done."
1631 :group 'org-faces)
1632
1633 (defface org-link
1634 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1635 (((class color) (background light)) (:foreground "Purple"))
1636 (((class color) (background dark)) (:foreground "Cyan"))
1637 (t (:bold t)))
1638 "Face for links."
1639 :group 'org-faces)
1640
1641 (defface org-done ;; font-lock-type-face
1642 '((((type tty) (class color)) (:foreground "green"))
1643 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1644 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1645 (t (:bold t :underline t)))
1646 "Face used for DONE."
1647 :group 'org-faces)
1648
1649 (defface org-table ;; font-lock-function-name-face
1650 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1651 (((class color) (background light)) (:foreground "Blue"))
1652 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1653 (t (:inverse-video t :bold t)))
1654 "Face used for tables."
1655 :group 'org-faces)
1656
1657 (defface org-time-grid ;; font-lock-variable-name-face
1658 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1659 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1660 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1661 (t (:bold t :italic t)))
1662 "Face used for level 2 headlines."
1663 :group 'org-faces)
1664
1665 (defvar org-level-faces
1666 '(
1667 org-level-1
1668 org-level-2
1669 org-level-3
1670 org-level-4
1671 org-level-5
1672 org-level-6
1673 org-level-7
1674 org-level-8
1675 ))
1676 (defvar org-n-levels (length org-level-faces))
1677
1678 (defun org-set-regexps-and-options ()
1679 "Precompute regular expressions for current buffer."
1680 (when (eq major-mode 'org-mode)
1681 (let ((re (org-make-options-regexp
1682 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1683 "STARTUP" "ARCHIVE")))
1684 (splitre "[ \t]+")
1685 kwds int key value cat arch)
1686 (save-excursion
1687 (save-restriction
1688 (widen)
1689 (goto-char (point-min))
1690 (while (re-search-forward re nil t)
1691 (setq key (match-string 1) value (match-string 2))
1692 (cond
1693 ((equal key "CATEGORY")
1694 (if (string-match "[ \t]+$" value)
1695 (setq value (replace-match "" t t value)))
1696 (setq cat (intern value)))
1697 ((equal key "SEQ_TODO")
1698 (setq int 'sequence
1699 kwds (append kwds (org-split-string value splitre))))
1700 ((equal key "PRI_TODO")
1701 (setq int 'priority
1702 kwds (append kwds (org-split-string value splitre))))
1703 ((equal key "TYP_TODO")
1704 (setq int 'type
1705 kwds (append kwds (org-split-string value splitre))))
1706 ((equal key "STARTUP")
1707 (let ((opts (org-split-string value splitre))
1708 (set '(("fold" org-startup-folded t)
1709 ("nofold" org-startup-folded nil)
1710 ("content" org-startup-folded content)
1711 ("dlcheck" org-startup-with-deadline-check t)
1712 ("nodlcheck" org-startup-with-deadline-check nil)))
1713 l var val)
1714 (while (setq l (assoc (pop opts) set))
1715 (setq var (nth 1 l) val (nth 2 l))
1716 (set (make-local-variable var) val))))
1717 ((equal key "ARCHIVE")
1718 (string-match " *$" value)
1719 (setq arch (replace-match "" t t value))
1720 (remove-text-properties 0 (length arch)
1721 '(face t fontified t) arch)))
1722 )))
1723 (and cat (set (make-local-variable 'org-category) cat))
1724 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1725 (and arch (set (make-local-variable 'org-archive-location) arch))
1726 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1727 ;; Compute the regular expressions and other local variables
1728 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1729 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1730 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1731 (length org-scheduled-string)))
1732 org-done-string
1733 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1734 org-todo-regexp
1735 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1736 "\\|") "\\)\\>")
1737 org-not-done-regexp
1738 (concat "\\<\\("
1739 (mapconcat 'regexp-quote
1740 (nreverse (cdr (reverse org-todo-keywords)))
1741 "\\|")
1742 "\\)\\>")
1743 org-todo-line-regexp
1744 (concat "^\\(\\*+\\)[ \t]*\\("
1745 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1746 "\\)? *\\(.*\\)")
1747 org-nl-done-regexp
1748 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1749 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1750 org-deadline-regexp (concat "\\<" org-deadline-string)
1751 org-deadline-time-regexp
1752 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1753 org-deadline-line-regexp
1754 (concat "\\<\\(" org-deadline-string "\\).*")
1755 org-scheduled-regexp
1756 (concat "\\<" org-scheduled-string)
1757 org-scheduled-time-regexp
1758 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1759 (org-set-font-lock-defaults)))
1760
1761 ;; Tell the compiler about dynamically scoped variables,
1762 ;; and variables from other packages
1763 (eval-when-compile
1764 (defvar zmacs-regions)
1765 (defvar original-date)
1766 (defvar org-transient-mark-mode)
1767 (defvar org-old-auto-fill-inhibit-regexp)
1768 (defvar orgtbl-mode-menu)
1769 (defvar org-html-entities)
1770 (defvar org-goto-start-pos)
1771 (defvar org-cursor-color)
1772 (defvar org-time-was-given)
1773 (defvar org-ts-what)
1774 (defvar mark-active)
1775 (defvar timecnt)
1776 (defvar levels-open)
1777 (defvar title)
1778 (defvar author)
1779 (defvar email)
1780 (defvar text)
1781 (defvar entry)
1782 (defvar date)
1783 (defvar language)
1784 (defvar options)
1785 (defvar ans1)
1786 (defvar ans2)
1787 (defvar starting-day)
1788 (defvar include-all-loc)
1789 (defvar vm-message-pointer)
1790 (defvar vm-folder-directory)
1791 (defvar wl-summary-buffer-elmo-folder)
1792 (defvar wl-summary-buffer-folder-name)
1793 (defvar gnus-group-name)
1794 (defvar gnus-article-current)
1795 (defvar w3m-current-url)
1796 (defvar org-selected-point)
1797 (defvar calendar-mode-map)
1798 (defvar remember-save-after-remembering)
1799 (defvar remember-data-file))
1800
1801
1802 ;;; Define the mode
1803
1804 (defvar org-mode-map (copy-keymap outline-mode-map)
1805 "Keymap for Org-mode.")
1806
1807 (defvar org-struct-menu)
1808 (defvar org-org-menu)
1809 (defvar org-tbl-menu)
1810
1811 ;; We use a before-change function to check if a table might need
1812 ;; an update.
1813 (defvar org-table-may-need-update t
1814 "Indicates of a table might need an update.
1815 This variable is set by `org-before-change-function'. `org-table-align'
1816 sets it back to nil.")
1817 (defvar org-mode-hook nil)
1818 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1819
1820
1821 ;;;###autoload
1822 (define-derived-mode org-mode outline-mode "Org"
1823 "Outline-based notes management and organizer, alias
1824 \"Carstens outline-mode for keeping track of everything.\"
1825
1826 Org-mode develops organizational tasks around a NOTES file which
1827 contains information about projects as plain text. Org-mode is
1828 implemented on top of outline-mode, which is ideal to keep the content
1829 of large files well structured. It supports ToDo items, deadlines and
1830 time stamps, which magically appear in the diary listing of the Emacs
1831 calendar. Tables are easily created with a built-in table editor.
1832 Plain text URL-like links connect to websites, emails (VM), Usenet
1833 messages (Gnus), BBDB entries, and any files related to the project.
1834 For printing and sharing of notes, an Org-mode file (or a part of it)
1835 can be exported as a structured ASCII or HTML file.
1836
1837 The following commands are available:
1838
1839 \\{org-mode-map}"
1840 (easy-menu-add org-org-menu)
1841 (easy-menu-add org-tbl-menu)
1842 (org-install-agenda-files-menu)
1843 (setq outline-regexp "\\*+")
1844 (if org-startup-truncated (setq truncate-lines t))
1845 (org-set-regexps-and-options)
1846 (set (make-local-variable 'font-lock-unfontify-region-function)
1847 'org-unfontify-region)
1848 ;; Activate before-change-function
1849 (set (make-local-variable 'org-table-may-need-update) t)
1850 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1851 (add-hook 'before-change-functions 'org-before-change-function nil
1852 'local)
1853 ;; Paragraph regular expressions
1854 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1855 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1856 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1857 (set (make-local-variable 'auto-fill-inhibit-regexp)
1858 (concat "\\*\\|#"
1859 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1860 (concat
1861 "\\|[ \t]*["
1862 (if org-enable-table-editor "|" "")
1863 (if org-enable-fixed-width-editor ":" "")
1864 "]"))))
1865 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1866 ;; Settings for Calc embedded mode
1867 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1868 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1869 (if (and org-insert-mode-line-in-empty-file
1870 (interactive-p)
1871 (= (point-min) (point-max)))
1872 (insert " -*- mode: org -*-\n\n"))
1873
1874 ;; Get rid of Outline menus, they are not needed
1875 ;; Need to do this here because define-derived-mode sets up
1876 ;; the keymap so late.
1877 (if org-xemacs-p
1878 (progn
1879 (delete-menu-item '("Headings"))
1880 (delete-menu-item '("Show"))
1881 (delete-menu-item '("Hide"))
1882 (set-menubar-dirty-flag))
1883 (define-key org-mode-map [menu-bar headings] 'undefined)
1884 (define-key org-mode-map [menu-bar hide] 'undefined)
1885 (define-key org-mode-map [menu-bar show] 'undefined))
1886
1887 (unless org-inhibit-startup
1888 (if org-startup-with-deadline-check
1889 (call-interactively 'org-check-deadlines)
1890 (cond
1891 ((eq org-startup-folded t)
1892 (org-cycle '(4)))
1893 ((eq org-startup-folded 'content)
1894 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1895 (org-cycle '(4)) (org-cycle '(4))))))))
1896
1897 (defun org-fill-paragraph (&optional justify)
1898 "Re-align a table, pass through to fill-paragraph if no table."
1899 (save-excursion
1900 (beginning-of-line 1)
1901 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1902
1903 (defsubst org-current-line (&optional pos)
1904 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1905
1906 ;;; Font-Lock stuff
1907
1908 (defvar org-mouse-map (make-sparse-keymap))
1909 (define-key org-mouse-map
1910 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1911 (define-key org-mouse-map
1912 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1913
1914 (require 'font-lock)
1915
1916 (defconst org-non-link-chars "\t\n\r|<>\000")
1917 (defconst org-link-regexp
1918 (if org-allow-space-in-links
1919 (concat
1920 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1921 (concat
1922 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1923 )
1924 "Regular expression for matching links.")
1925 (defconst org-link-maybe-angles-regexp
1926 (concat "<?\\(" org-link-regexp "\\)>?")
1927 "Matches a link and optionally surrounding angle brackets.")
1928 (defconst org-protected-link-regexp
1929 (concat "\000" org-link-regexp "\000")
1930 "Matches a link and optionally surrounding angle brackets.")
1931
1932 (defconst org-ts-lengths
1933 (cons (length (format-time-string (car org-time-stamp-formats)))
1934 (length (format-time-string (cdr org-time-stamp-formats))))
1935 "This holds the lengths of the two different time formats.")
1936 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1937 "Regular expression for fast time stamp matching.")
1938 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1939 "Regular expression matching time strings for analysis.")
1940 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1941 "Regular expression matching time stamps, with groups.")
1942 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1943 "Regular expression matching a time stamp range.")
1944 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1945 org-ts-regexp "\\)?")
1946 "Regular expression matching a time stamp or time stamp range.")
1947
1948 (defun org-activate-links (limit)
1949 "Run through the buffer and add overlays to links."
1950 (if (re-search-forward org-link-regexp limit t)
1951 (progn
1952 (add-text-properties (match-beginning 0) (match-end 0)
1953 (list 'mouse-face 'highlight
1954 'keymap org-mouse-map))
1955 t)))
1956
1957 (defun org-activate-dates (limit)
1958 "Run through the buffer and add overlays to dates."
1959 (if (re-search-forward org-tsr-regexp limit t)
1960 (progn
1961 (add-text-properties (match-beginning 0) (match-end 0)
1962 (list 'mouse-face 'highlight
1963 'keymap org-mouse-map))
1964 t)))
1965
1966 (defun org-font-lock-level ()
1967 (save-excursion
1968 (org-back-to-heading t)
1969 (- (match-end 0) (match-beginning 0))))
1970
1971 (defvar org-font-lock-keywords nil)
1972
1973 (defun org-set-font-lock-defaults ()
1974 (let ((org-font-lock-extra-keywords
1975 (list
1976 '(org-activate-links (0 'org-link))
1977 '(org-activate-dates (0 'org-link))
1978 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1979 '(1 'org-warning t))
1980 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
1981 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1982 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1983 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
1984 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
1985 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1986 ;; (3 'bold))
1987 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1988 ;; (3 'italic))
1989 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1990 ;; (3 'underline))
1991 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1992 ; '(1 'org-warning t))
1993 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
1994 "\\|" org-quote-string "\\)\\>")
1995 '(1 'org-special-keyword t))
1996 '("^#.*" (0 'font-lock-comment-face t))
1997 (if org-fontify-done-headline
1998 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1999 '(1 'org-done t) '(2 'org-headline-done t))
2000 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2001 '(1 'org-done t)))
2002 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2003 (1 'org-table t))
2004 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2005 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2006 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2007 )))
2008 (set (make-local-variable 'org-font-lock-keywords)
2009 (append
2010 (if org-noutline-p ; FIXME: I am not sure if eval will work
2011 ; on XEmacs if noutline is ever ported
2012 `((eval . (list "^\\(\\*+\\).*"
2013 ,(if org-level-color-stars-only 1 0)
2014 '(nth ;; FIXME: 1<->0 ????
2015 (% (- (match-end 1) (match-beginning 1) 1)
2016 org-n-levels)
2017 org-level-faces)
2018 nil t)))
2019 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2020 (,(if org-level-color-stars-only 2 0)
2021 (nth (% (- (match-end 2) (match-beginning 2) 1)
2022 org-n-levels)
2023 org-level-faces)
2024 nil t))))
2025 org-font-lock-extra-keywords))
2026 (set (make-local-variable 'font-lock-defaults)
2027 '(org-font-lock-keywords t nil nil backward-paragraph))
2028 (kill-local-variable 'font-lock-keywords) nil))
2029
2030 (defun org-unfontify-region (beg end &optional maybe_loudly)
2031 "Remove fontification and activation overlays from links."
2032 (font-lock-default-unfontify-region beg end)
2033 (let* ((buffer-undo-list t)
2034 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2035 (inhibit-modification-hooks t)
2036 deactivate-mark buffer-file-name buffer-file-truename)
2037 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2038
2039 ;;; Visibility cycling
2040
2041 (defvar org-cycle-global-status nil)
2042 (defvar org-cycle-subtree-status nil)
2043 (defun org-cycle (&optional arg)
2044 "Visibility cycling for Org-mode.
2045
2046 - When this function is called with a prefix argument, rotate the entire
2047 buffer through 3 states (global cycling)
2048 1. OVERVIEW: Show only top-level headlines.
2049 2. CONTENTS: Show all headlines of all levels, but no body text.
2050 3. SHOW ALL: Show everything.
2051
2052 - When point is at the beginning of a headline, rotate the subtree started
2053 by this line through 3 different states (local cycling)
2054 1. FOLDED: Only the main headline is shown.
2055 2. CHILDREN: The main headline and the direct children are shown. From
2056 this state, you can move to one of the children and
2057 zoom in further.
2058 3. SUBTREE: Show the entire subtree, including body text.
2059
2060 - When there is a numeric prefix, go up to a heading with level ARG, do
2061 a `show-subtree' and return to the previous cursor position. If ARG
2062 is negative, go up that many levels.
2063
2064 - When point is not at the beginning of a headline, execute
2065 `indent-relative', like TAB normally does. See the option
2066 `org-cycle-emulate-tab' for details.
2067
2068 - Special case: if point is the the beginning of the buffer and there is
2069 no headline in line 1, this function will act as if called with prefix arg."
2070 (interactive "P")
2071
2072 (if (or (and (bobp) (not (looking-at outline-regexp)))
2073 (equal arg '(4)))
2074 ;; special case: use global cycling
2075 (setq arg t))
2076
2077 (cond
2078
2079 ((org-at-table-p 'any)
2080 ;; Enter the table or move to the next field in the table
2081 (or (org-table-recognize-table.el)
2082 (progn
2083 (org-table-justify-field-maybe)
2084 (org-table-next-field))))
2085
2086 ((eq arg t) ;; Global cycling
2087
2088 (cond
2089 ((and (eq last-command this-command)
2090 (eq org-cycle-global-status 'overview))
2091 ;; We just created the overview - now do table of contents
2092 ;; This can be slow in very large buffers, so indicate action
2093 (message "CONTENTS...")
2094 (save-excursion
2095 ;; Visit all headings and show their offspring
2096 (goto-char (point-max))
2097 (catch 'exit
2098 (while (and (progn (condition-case nil
2099 (outline-previous-visible-heading 1)
2100 (error (goto-char (point-min))))
2101 t)
2102 (looking-at outline-regexp))
2103 (show-branches)
2104 (if (bobp) (throw 'exit nil))))
2105 (message "CONTENTS...done"))
2106 (setq org-cycle-global-status 'contents)
2107 (run-hook-with-args 'org-cycle-hook 'contents))
2108
2109 ((and (eq last-command this-command)
2110 (eq org-cycle-global-status 'contents))
2111 ;; We just showed the table of contents - now show everything
2112 (show-all)
2113 (message "SHOW ALL")
2114 (setq org-cycle-global-status 'all)
2115 (run-hook-with-args 'org-cycle-hook 'all))
2116
2117 (t
2118 ;; Default action: go to overview
2119 (hide-sublevels 1)
2120 (message "OVERVIEW")
2121 (setq org-cycle-global-status 'overview)
2122 (run-hook-with-args 'org-cycle-hook 'overview))))
2123
2124 ((integerp arg)
2125 ;; Show-subtree, ARG levels up from here.
2126 (save-excursion
2127 (org-back-to-heading)
2128 (outline-up-heading (if (< arg 0) (- arg)
2129 (- (outline-level) arg)))
2130 (org-show-subtree)))
2131
2132 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2133 ;; At a heading: rotate between three different views
2134 (org-back-to-heading)
2135 (let ((goal-column 0) eoh eol eos)
2136 ;; First, some boundaries
2137 (save-excursion
2138 (org-back-to-heading)
2139 (save-excursion
2140 (beginning-of-line 2)
2141 (while (and (not (eobp)) ;; this is like `next-line'
2142 (get-char-property (1- (point)) 'invisible))
2143 (beginning-of-line 2)) (setq eol (point)))
2144 (outline-end-of-heading) (setq eoh (point))
2145 (outline-end-of-subtree) (setq eos (point))
2146 (outline-next-heading))
2147 ;; Find out what to do next and set `this-command'
2148 (cond
2149 ((= eos eoh)
2150 ;; Nothing is hidden behind this heading
2151 (message "EMPTY ENTRY")
2152 (setq org-cycle-subtree-status nil))
2153 ((>= eol eos)
2154 ;; Entire subtree is hidden in one line: open it
2155 (org-show-entry)
2156 (show-children)
2157 (message "CHILDREN")
2158 (setq org-cycle-subtree-status 'children)
2159 (run-hook-with-args 'org-cycle-hook 'children))
2160 ((and (eq last-command this-command)
2161 (eq org-cycle-subtree-status 'children))
2162 ;; We just showed the children, now show everything.
2163 (org-show-subtree)
2164 (message "SUBTREE")
2165 (setq org-cycle-subtree-status 'subtree)
2166 (run-hook-with-args 'org-cycle-hook 'subtree))
2167 (t
2168 ;; Default action: hide the subtree.
2169 (hide-subtree)
2170 (message "FOLDED")
2171 (setq org-cycle-subtree-status 'folded)
2172 (run-hook-with-args 'org-cycle-hook 'folded)))))
2173
2174 ;; TAB emulation
2175 (buffer-read-only (org-back-to-heading))
2176 ((if (and (eq org-cycle-emulate-tab 'white)
2177 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2178 t
2179 (eq org-cycle-emulate-tab t))
2180 (if (and (looking-at "[ \n\r\t]")
2181 (string-match "^[ \t]*$" (buffer-substring
2182 (point-at-bol) (point))))
2183 (progn
2184 (beginning-of-line 1)
2185 (and (looking-at "[ \t]+") (replace-match ""))))
2186 (indent-relative))
2187
2188 (t (save-excursion
2189 (org-back-to-heading)
2190 (org-cycle)))))
2191
2192 (defun org-optimize-window-after-visibility-change (state)
2193 "Adjust the window after a change in outline visibility.
2194 This function is the default value of the hook `org-cycle-hook'."
2195 (cond
2196 ((eq state 'overview) (org-first-headline-recenter 1))
2197 ((eq state 'content) nil)
2198 ((eq state 'all) nil)
2199 ((eq state 'folded) nil)
2200 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2201 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2202
2203 (defun org-subtree-end-visible-p ()
2204 "Is the end of the current subtree visible?"
2205 (pos-visible-in-window-p
2206 (save-excursion (outline-end-of-subtree) (point))))
2207
2208 (defun org-first-headline-recenter (&optional N)
2209 "Move cursor to the first headline and recenter the headline.
2210 Optional argument N means, put the headline into the Nth line of the window."
2211 (goto-char (point-min))
2212 (when (re-search-forward (concat "^" outline-regexp) nil t)
2213 (beginning-of-line)
2214 (recenter (prefix-numeric-value N))))
2215
2216 (defvar org-goto-window-configuration nil)
2217 (defvar org-goto-marker nil)
2218 (defvar org-goto-map (make-sparse-keymap))
2219 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2220 (while (setq cmd (pop cmds))
2221 (substitute-key-definition cmd cmd org-goto-map global-map)))
2222 (define-key org-goto-map "\C-m" 'org-goto-ret)
2223 (define-key org-goto-map [(left)] 'org-goto-left)
2224 (define-key org-goto-map [(right)] 'org-goto-right)
2225 (define-key org-goto-map [(?q)] 'org-goto-quit)
2226 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2227 (define-key org-goto-map "\C-i" 'org-cycle)
2228 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2229 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2230 (define-key org-goto-map "n" 'outline-next-visible-heading)
2231 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2232 (define-key org-goto-map "f" 'outline-forward-same-level)
2233 (define-key org-goto-map "b" 'outline-backward-same-level)
2234 (define-key org-goto-map "u" 'outline-up-heading)
2235 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2236 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2237 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2238 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2239 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2240 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2241 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2242
2243 (defconst org-goto-help
2244 "Select a location to jump to, press RET
2245 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2246
2247 (defun org-goto ()
2248 "Go to a different location of the document, keeping current visibility.
2249
2250 When you want to go to a different location in a document, the fastest way
2251 is often to fold the entire buffer and then dive into the tree. This
2252 method has the disadvantage, that the previous location will be folded,
2253 which may not be what you want.
2254
2255 This command works around this by showing a copy of the current buffer in
2256 overview mode. You can dive into the tree in that copy, to find the
2257 location you want to reach. When pressing RET, the command returns to the
2258 original buffer in which the visibility is still unchanged. It then jumps
2259 to the new location, making it and the headline hierarchy above it visible."
2260 (interactive)
2261 (let* ((org-goto-start-pos (point))
2262 (selected-point
2263 (org-get-location (current-buffer) org-goto-help)))
2264 (if selected-point
2265 (progn
2266 (goto-char selected-point)
2267 (if (org-invisible-p) (org-show-hierarchy-above)))
2268 (error "Quit"))))
2269
2270 (defun org-get-location (buf help)
2271 "Let the user select a location in the Org-mode buffer BUF.
2272 This function uses a recursive edit. It returns the selected position
2273 or nil."
2274 (let (org-selected-point)
2275 (save-excursion
2276 (save-window-excursion
2277 (delete-other-windows)
2278 (switch-to-buffer (get-buffer-create "*org-goto*"))
2279 (with-output-to-temp-buffer "*Help*"
2280 (princ help))
2281 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2282 (setq buffer-read-only nil)
2283 (erase-buffer)
2284 (insert-buffer-substring buf)
2285 (let ((org-startup-truncated t)
2286 (org-startup-folded t)
2287 (org-startup-with-deadline-check nil))
2288 (org-mode))
2289 (setq buffer-read-only t)
2290 (if (boundp 'org-goto-start-pos)
2291 (goto-char org-goto-start-pos)
2292 (goto-char (point-min)))
2293 (org-beginning-of-line)
2294 (message "Select location and press RET")
2295 ;; now we make sure that during selection, ony very few keys work
2296 ;; and that it is impossible to switch to another window.
2297 (let ((gm (current-global-map))
2298 (overriding-local-map org-goto-map))
2299 (unwind-protect
2300 (progn
2301 (use-global-map org-goto-map)
2302 (recursive-edit))
2303 (use-global-map gm)))))
2304 (kill-buffer "*org-goto*")
2305 org-selected-point))
2306
2307 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2308 (defun org-goto-ret (&optional arg)
2309 "Finish org-goto by going to the new location."
2310 (interactive "P")
2311 (setq org-selected-point (point)
2312 current-prefix-arg arg)
2313 (throw 'exit nil))
2314
2315 (defun org-goto-left ()
2316 "Finish org-goto by going to the new location."
2317 (interactive)
2318 (if (org-on-heading-p)
2319 (progn
2320 (beginning-of-line 1)
2321 (setq org-selected-point (point)
2322 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2323 (throw 'exit nil))
2324 (error "Not on a heading")))
2325
2326 (defun org-goto-right ()
2327 "Finish org-goto by going to the new location."
2328 (interactive)
2329 (if (org-on-heading-p)
2330 (progn
2331 (outline-end-of-subtree)
2332 (or (eobp) (forward-char 1))
2333 (setq org-selected-point (point)
2334 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2335 (throw 'exit nil))
2336 (error "Not on a heading")))
2337
2338 (defun org-goto-quit ()
2339 "Finish org-goto without cursor motion."
2340 (interactive)
2341 (setq org-selected-point nil)
2342 (throw 'exit nil))
2343
2344 ;;; Promotion, Demotion, Inserting new headlines
2345
2346 (defvar org-ignore-region nil
2347 "To temporarily disable the active region.")
2348
2349 (defun org-insert-heading ()
2350 "Insert a new heading with same depth at point."
2351 (interactive)
2352 (let* ((head (save-excursion
2353 (condition-case nil
2354 (org-back-to-heading)
2355 (error (outline-next-heading)))
2356 (prog1 (match-string 0)
2357 (funcall outline-level)))))
2358 (unless (bolp) (newline))
2359 (insert head)
2360 (unless (eolp)
2361 (save-excursion (newline-and-indent)))
2362 (unless (equal (char-before) ?\ )
2363 (insert " "))
2364 (run-hooks 'org-insert-heading-hook)))
2365
2366 (defun org-insert-todo-heading (arg)
2367 "Insert a new heading with the same level and TODO state as current heading.
2368 If the heading has no TODO state, or if the state is DONE, use the first
2369 state (TODO by default). Also with prefix arg, force first state."
2370 (interactive "P")
2371 (org-insert-heading)
2372 (save-excursion
2373 (org-back-to-heading)
2374 (outline-previous-heading)
2375 (looking-at org-todo-line-regexp))
2376 (if (or arg
2377 (not (match-beginning 2))
2378 (equal (match-string 2) org-done-string))
2379 (insert (car org-todo-keywords) " ")
2380 (insert (match-string 2) " ")))
2381
2382 (defun org-promote-subtree ()
2383 "Promote the entire subtree.
2384 See also `org-promote'."
2385 (interactive)
2386 (save-excursion
2387 (org-map-tree 'org-promote)))
2388
2389 (defun org-demote-subtree ()
2390 "Demote the entire subtree. See `org-demote'.
2391 See also `org-promote'."
2392 (interactive)
2393 (save-excursion
2394 (org-map-tree 'org-demote)))
2395
2396 (defun org-do-promote ()
2397 "Promote the current heading higher up the tree.
2398 If the region is active in `transient-mark-mode', promote all headings
2399 in the region."
2400 (interactive)
2401 (save-excursion
2402 (if (org-region-active-p)
2403 (org-map-region 'org-promote (region-beginning) (region-end))
2404 (org-promote)))
2405 (org-fix-position-after-promote))
2406
2407 (defun org-do-demote ()
2408 "Demote the current heading lower down the tree.
2409 If the region is active in `transient-mark-mode', demote all headings
2410 in the region."
2411 (interactive)
2412 (save-excursion
2413 (if (org-region-active-p)
2414 (org-map-region 'org-demote (region-beginning) (region-end))
2415 (org-demote)))
2416 (org-fix-position-after-promote))
2417
2418 (defun org-fix-position-after-promote ()
2419 "Make sure that after pro/demotion cursor position is right."
2420 (and (equal (char-after) ?\ )
2421 (equal (char-before) ?*)
2422 (forward-char 1)))
2423
2424 (defun org-promote ()
2425 "Promote the current heading higher up the tree.
2426 If the region is active in `transient-mark-mode', promote all headings
2427 in the region."
2428 (org-back-to-heading t)
2429 (let* ((level (save-match-data (funcall outline-level)))
2430 (up-head (make-string (1- level) ?*)))
2431 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2432 (replace-match up-head nil t)
2433 (if org-adapt-indentation
2434 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2435
2436 (defun org-demote ()
2437 "Demote the current heading lower down the tree.
2438 If the region is active in `transient-mark-mode', demote all headings
2439 in the region."
2440 (org-back-to-heading t)
2441 (let* ((level (save-match-data (funcall outline-level)))
2442 (down-head (make-string (1+ level) ?*)))
2443 (replace-match down-head nil t)
2444 (if org-adapt-indentation
2445 (org-fixup-indentation "^ " " " "^\\S-"))))
2446
2447 (defun org-map-tree (fun)
2448 "Call FUN for every heading underneath the current one."
2449 (org-back-to-heading)
2450 (let ((level (outline-level)))
2451 (save-excursion
2452 (funcall fun)
2453 (while (and (progn
2454 (outline-next-heading)
2455 (> (funcall outline-level) level))
2456 (not (eobp)))
2457 (funcall fun)))))
2458
2459 (defun org-map-region (fun beg end)
2460 "Call FUN for every heading between BEG and END."
2461 (let ((org-ignore-region t))
2462 (save-excursion
2463 (setq end (copy-marker end))
2464 (goto-char beg)
2465 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2466 (< (point) end))
2467 (funcall fun))
2468 (while (and (progn
2469 (outline-next-heading)
2470 (< (point) end))
2471 (not (eobp)))
2472 (funcall fun)))))
2473
2474 (defun org-fixup-indentation (from to prohibit)
2475 "Change the indentation in the current entry by re-replacing FROM with TO.
2476 However, if the regexp PROHIBIT matches at all, don't do anything.
2477 This is being used to change indentation along with the length of the
2478 heading marker. But if there are any lines which are not indented, nothing
2479 is changed at all."
2480 (save-excursion
2481 (let ((end (save-excursion (outline-next-heading)
2482 (point-marker))))
2483 (unless (save-excursion (re-search-forward prohibit end t))
2484 (while (re-search-forward from end t)
2485 (replace-match to)
2486 (beginning-of-line 2)))
2487 (move-marker end nil))))
2488
2489 ;;; Vertical tree motion, cutting and pasting of subtrees
2490
2491 (defun org-move-subtree-up (&optional arg)
2492 "Move the current subtree up past ARG headlines of the same level."
2493 (interactive "p")
2494 (org-move-subtree-down (- (prefix-numeric-value arg))))
2495
2496 (defun org-move-subtree-down (&optional arg)
2497 "Move the current subtree down past ARG headlines of the same level."
2498 (interactive "p")
2499 (setq arg (prefix-numeric-value arg))
2500 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2501 'outline-get-last-sibling))
2502 (ins-point (make-marker))
2503 (cnt (abs arg))
2504 beg end txt folded)
2505 ;; Select the tree
2506 (org-back-to-heading)
2507 (setq beg (point))
2508 (save-match-data
2509 (save-excursion (outline-end-of-heading)
2510 (setq folded (org-invisible-p)))
2511 (outline-end-of-subtree))
2512 (outline-next-heading)
2513 (setq end (point))
2514 ;; Find insertion point, with error handling
2515 (goto-char beg)
2516 (while (> cnt 0)
2517 (or (and (funcall movfunc) (looking-at outline-regexp))
2518 (progn (goto-char beg)
2519 (error "Cannot move past superior level or buffer limit")))
2520 (setq cnt (1- cnt)))
2521 (if (> arg 0)
2522 ;; Moving forward - still need to move over subtree
2523 (progn (outline-end-of-subtree)
2524 (outline-next-heading)
2525 (if (not (or (looking-at (concat "^" outline-regexp))
2526 (bolp)))
2527 (newline))))
2528 (move-marker ins-point (point))
2529 (setq txt (buffer-substring beg end))
2530 (delete-region beg end)
2531 (insert txt)
2532 (goto-char ins-point)
2533 (if folded (hide-subtree))
2534 (move-marker ins-point nil)))
2535
2536 (defvar org-subtree-clip ""
2537 "Clipboard for cut and paste of subtrees.
2538 This is actually only a copy of the kill, because we use the normal kill
2539 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2540
2541 (defvar org-subtree-clip-folded nil
2542 "Was the last copied subtree folded?
2543 This is used to fold the tree back after pasting.")
2544
2545 (defun org-cut-subtree ()
2546 "Cut the current subtree into the clipboard.
2547 This is a short-hand for marking the subtree and then cutting it."
2548 (interactive)
2549 (org-copy-subtree 'cut))
2550
2551 (defun org-copy-subtree (&optional cut)
2552 "Cut the current subtree into the clipboard.
2553 This is a short-hand for marking the subtree and then copying it.
2554 If CUT is non nil, actually cut the subtree."
2555 (interactive)
2556 (let (beg end folded)
2557 (org-back-to-heading)
2558 (setq beg (point))
2559 (save-match-data
2560 (save-excursion (outline-end-of-heading)
2561 (setq folded (org-invisible-p)))
2562 (outline-end-of-subtree))
2563 (if (equal (char-after) ?\n) (forward-char 1))
2564 (setq end (point))
2565 (goto-char beg)
2566 (when (> end beg)
2567 (setq org-subtree-clip-folded folded)
2568 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2569 (setq org-subtree-clip (current-kill 0))
2570 (message "%s: Subtree with %d characters"
2571 (if cut "Cut" "Copied")
2572 (length org-subtree-clip)))))
2573
2574 (defun org-paste-subtree (&optional level tree)
2575 "Paste the clipboard as a subtree, with modification of headline level.
2576 The entire subtree is promoted or demoted in order to match a new headline
2577 level. By default, the new level is derived from the visible headings
2578 before and after the insertion point, and taken to be the inferior headline
2579 level of the two. So if the previous visible heading is level 3 and the
2580 next is level 4 (or vice versa), level 4 will be used for insertion.
2581 This makes sure that the subtree remains an independent subtree and does
2582 not swallow low level entries.
2583
2584 You can also force a different level, either by using a numeric prefix
2585 argument, or by inserting the heading marker by hand. For example, if the
2586 cursor is after \"*****\", then the tree will be shifted to level 5.
2587
2588 If you want to insert the tree as is, just use \\[yank].
2589
2590 If optional TREE is given, use this text instead of the kill ring."
2591 (interactive "P")
2592 (unless (org-kill-is-subtree-p tree)
2593 (error
2594 (substitute-command-keys
2595 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2596 (let* ((txt (or tree (current-kill 0)))
2597 (^re (concat "^\\(" outline-regexp "\\)"))
2598 (re (concat "\\(" outline-regexp "\\)"))
2599 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2600
2601 (old-level (if (string-match ^re txt)
2602 (- (match-end 0) (match-beginning 0))
2603 -1))
2604 (force-level (cond (level (prefix-numeric-value level))
2605 ((string-match
2606 ^re_ (buffer-substring (point-at-bol) (point)))
2607 (- (match-end 0) (match-beginning 0)))
2608 (t nil)))
2609 (previous-level (save-excursion
2610 (condition-case nil
2611 (progn
2612 (outline-previous-visible-heading 1)
2613 (if (looking-at re)
2614 (- (match-end 0) (match-beginning 0))
2615 1))
2616 (error 1))))
2617 (next-level (save-excursion
2618 (condition-case nil
2619 (progn
2620 (outline-next-visible-heading 1)
2621 (if (looking-at re)
2622 (- (match-end 0) (match-beginning 0))
2623 1))
2624 (error 1))))
2625 (new-level (or force-level (max previous-level next-level)))
2626 (shift (if (or (= old-level -1)
2627 (= new-level -1)
2628 (= old-level new-level))
2629 0
2630 (- new-level old-level)))
2631 (shift1 shift)
2632 (delta (if (> shift 0) -1 1))
2633 (func (if (> shift 0) 'org-demote 'org-promote))
2634 beg end)
2635 ;; Remove the forces level indicator
2636 (if force-level
2637 (delete-region (point-at-bol) (point)))
2638 ;; Make sure we start at the beginning of an empty line
2639 (if (not (bolp)) (insert "\n"))
2640 (if (not (looking-at "[ \t]*$"))
2641 (progn (insert "\n") (backward-char 1)))
2642 ;; Paste
2643 (setq beg (point))
2644 (insert txt)
2645 (setq end (point))
2646 (goto-char beg)
2647 ;; Shift if necessary
2648 (if (= shift 0)
2649 (message "Pasted at level %d, without shift" new-level)
2650 (save-restriction
2651 (narrow-to-region beg end)
2652 (while (not (= shift 0))
2653 (org-map-region func (point-min) (point-max))
2654 (setq shift (+ delta shift)))
2655 (goto-char (point-min))
2656 (message "Pasted at level %d, with shift by %d levels"
2657 new-level shift1)))
2658 (if (and (eq org-subtree-clip (current-kill 0))
2659 org-subtree-clip-folded)
2660 ;; The tree was folded before it was killed/copied
2661 (hide-subtree))))
2662
2663 (defun org-kill-is-subtree-p (&optional txt)
2664 "Check if the current kill is an outline subtree, or a set of trees.
2665 Returns nil if kill does not start with a headline, or if the first
2666 headline level is not the largest headline level in the tree.
2667 So this will actually accept several entries of equal levels as well,
2668 which is OK for `org-paste-subtree'.
2669 If optional TXT is given, check this string instead of the current kill."
2670 (let* ((kill (or txt (current-kill 0) ""))
2671 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2672 (- (match-end 0) (match-beginning 0))))
2673 (re (concat "^" outline-regexp))
2674 (start 1))
2675 (if (not start-level)
2676 nil ;; does not even start with a heading
2677 (catch 'exit
2678 (while (setq start (string-match re kill (1+ start)))
2679 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2680 (throw 'exit nil)))
2681 t))))
2682
2683 (defun org-archive-subtree ()
2684 "Move the current subtree to the archive.
2685 The archive can be a certain top-level heading in the current file, or in
2686 a different file. The tree will be moved to that location, the subtree
2687 heading be marked DONE, and the current time will be added."
2688 (interactive)
2689 ;; Save all relevant TODO keyword-relatex variables
2690 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2691 (tr-org-todo-keywords org-todo-keywords)
2692 (tr-org-todo-interpretation org-todo-interpretation)
2693 (tr-org-done-string org-done-string)
2694 (tr-org-todo-regexp org-todo-regexp)
2695 (tr-org-todo-line-regexp org-todo-line-regexp)
2696 (this-buffer (current-buffer))
2697 file heading buffer level newfile-p)
2698 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2699 (progn
2700 (setq file (format (match-string 1 org-archive-location)
2701 (file-name-nondirectory (buffer-file-name)))
2702 heading (match-string 2 org-archive-location)))
2703 (error "Invalid `org-archive-location'"))
2704 (if (> (length file) 0)
2705 (setq newfile-p (not (file-exists-p file))
2706 buffer (find-file-noselect file))
2707 (setq buffer (current-buffer)))
2708 (unless buffer
2709 (error "Cannot access file \"%s\"" file))
2710 (if (and (> (length heading) 0)
2711 (string-match "^\\*+" heading))
2712 (setq level (match-end 0))
2713 (setq heading nil level 0))
2714 (save-excursion
2715 ;; We first only copy, in case something goes wrong
2716 ;; we need to protect this-command, to avoid kill-region sets it,
2717 ;; which would lead to duplication of subtrees
2718 (let (this-command) (org-copy-subtree))
2719 (set-buffer buffer)
2720 ;; Enforce org-mode for the archive buffer
2721 (if (not (eq major-mode 'org-mode))
2722 ;; Force the mode for future visits.
2723 (let ((org-insert-mode-line-in-empty-file t))
2724 (call-interactively 'org-mode)))
2725 (when newfile-p
2726 (goto-char (point-max))
2727 (insert (format "\nArchived entries from file %s\n\n"
2728 (buffer-file-name this-buffer))))
2729 ;; Force the TODO keywords of the original buffer
2730 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2731 (org-todo-keywords tr-org-todo-keywords)
2732 (org-todo-interpretation tr-org-todo-interpretation)
2733 (org-done-string tr-org-done-string)
2734 (org-todo-regexp tr-org-todo-regexp)
2735 (org-todo-line-regexp tr-org-todo-line-regexp))
2736 (goto-char (point-min))
2737 (if heading
2738 (progn
2739 (if (re-search-forward
2740 (concat "\\(^\\|\r\\)"
2741 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2742 nil t)
2743 (goto-char (match-end 0))
2744 ;; Heading not found, just insert it at the end
2745 (goto-char (point-max))
2746 (or (bolp) (insert "\n"))
2747 (insert "\n" heading "\n")
2748 (end-of-line 0))
2749 ;; Make the heading visible, and the following as well
2750 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2751 (if (re-search-forward
2752 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2753 nil t)
2754 (progn (goto-char (match-beginning 0)) (insert "\n")
2755 (beginning-of-line 0))
2756 (goto-char (point-max)) (insert "\n")))
2757 (goto-char (point-max)) (insert "\n"))
2758 ;; Paste
2759 (org-paste-subtree (1+ level))
2760 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2761 (if org-archive-mark-done
2762 (org-todo (length org-todo-keywords)))
2763 ;; Move cursor to right after the TODO keyword
2764 (when org-archive-stamp-time
2765 (beginning-of-line 1)
2766 (looking-at org-todo-line-regexp)
2767 (goto-char (or (match-end 2) (match-beginning 3)))
2768 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2769 (current-time))
2770 ")"))
2771 ;; Save the buffer, if it is not the same buffer.
2772 (if (not (eq this-buffer buffer)) (save-buffer))))
2773 ;; Here we are back in the original buffer. Everything seems to have
2774 ;; worked. So now cut the tree and finish up.
2775 (let (this-command) (org-cut-subtree))
2776 (if (looking-at "[ \t]*$") (kill-line))
2777 (message "Subtree archived %s"
2778 (if (eq this-buffer buffer)
2779 (concat "under heading: " heading)
2780 (concat "in file: " (abbreviate-file-name file))))))
2781
2782 ;;; Completion
2783
2784 (defun org-complete (&optional arg)
2785 "Perform completion on word at point.
2786 At the beginning of a headline, this completes TODO keywords as given in
2787 `org-todo-keywords'.
2788 If the current word is preceded by a backslash, completes the TeX symbols
2789 that are supported for HTML support.
2790 If the current word is preceded by \"#+\", completes special words for
2791 setting file options.
2792 At all other locations, this simply calls `ispell-complete-word'."
2793 (interactive "P")
2794 (catch 'exit
2795 (let* ((end (point))
2796 (beg (save-excursion
2797 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2798 (skip-chars-backward "a-zA-Z0-9_:$")
2799 (point)))
2800 (texp (equal (char-before beg) ?\\))
2801 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2802 beg)
2803 "#+"))
2804 (pattern (buffer-substring-no-properties beg end))
2805 (completion-ignore-case opt)
2806 (type nil)
2807 (table (cond
2808 (opt
2809 (setq type :opt)
2810 (mapcar (lambda (x)
2811 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2812 (cons (match-string 2 x) (match-string 1 x)))
2813 (org-split-string (org-get-current-options) "\n")))
2814 (texp
2815 (setq type :tex)
2816 org-html-entities)
2817 ((string-match "\\`\\*+[ \t]*\\'"
2818 (buffer-substring (point-at-bol) beg))
2819 (setq type :todo)
2820 (mapcar 'list org-todo-keywords))
2821 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2822 (completion (try-completion pattern table)))
2823 (cond ((eq completion t)
2824 (if (equal type :opt)
2825 (insert (substring (cdr (assoc (upcase pattern) table))
2826 (length pattern)))))
2827 ((null completion)
2828 (message "Can't find completion for \"%s\"" pattern)
2829 (ding))
2830 ((not (string= pattern completion))
2831 (delete-region beg end)
2832 (if (string-match " +$" completion)
2833 (setq completion (replace-match "" t t completion)))
2834 (insert completion)
2835 (if (get-buffer-window "*Completions*")
2836 (delete-window (get-buffer-window "*Completions*")))
2837 (if (and (eq type :todo)
2838 (assoc completion table))
2839 (insert " "))
2840 (if (and (equal type :opt) (assoc completion table))
2841 (message "%s" (substitute-command-keys
2842 "Press \\[org-complete] again to insert example settings"))))
2843 (t
2844 (message "Making completion list...")
2845 (let ((list (sort (all-completions pattern table) 'string<)))
2846 (with-output-to-temp-buffer "*Completions*"
2847 (display-completion-list list pattern)))
2848 (message "Making completion list...%s" "done"))))))
2849
2850 ;;; Comments, TODO and DEADLINE
2851
2852 (defun org-toggle-comment ()
2853 "Change the COMMENT state of an entry."
2854 (interactive)
2855 (save-excursion
2856 (org-back-to-heading)
2857 (if (looking-at (concat outline-regexp
2858 "\\( +\\<" org-comment-string "\\>\\)"))
2859 (replace-match "" t t nil 1)
2860 (if (looking-at outline-regexp)
2861 (progn
2862 (goto-char (match-end 0))
2863 (insert " " org-comment-string))))))
2864
2865 (defvar org-last-todo-state-is-todo nil
2866 "This is non-nil when the last TODO state change led to a TODO state.
2867 If the last change removed the TODO tag or switched to DONE, then
2868 this is nil.")
2869
2870 (defun org-todo (&optional arg)
2871 "Change the TODO state of an item.
2872 The state of an item is given by a keyword at the start of the heading,
2873 like
2874 *** TODO Write paper
2875 *** DONE Call mom
2876
2877 The different keywords are specified in the variable `org-todo-keywords'. By
2878 default the available states are \"TODO\" and \"DONE\".
2879 So for this example: when the item starts with TODO, it is changed to DONE.
2880 When it starts with DONE, the DONE is removed. And when neither TODO nor
2881 DONE are present, add TODO at the beginning of the heading.
2882
2883 With prefix arg, use completion to determined the new state. With numeric
2884 prefix arg, switch to that state."
2885 (interactive "P")
2886 (save-excursion
2887 (org-back-to-heading)
2888 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2889 (or (looking-at (concat " +" org-todo-regexp " *"))
2890 (looking-at " *"))
2891 (let* ((this (match-string 1))
2892 (completion-ignore-case t)
2893 (member (member this org-todo-keywords))
2894 (tail (cdr member))
2895 (state (cond
2896 ((equal arg '(4))
2897 ;; Read a state with completion
2898 (completing-read "State: " (mapcar (lambda(x) (list x))
2899 org-todo-keywords)
2900 nil t))
2901 (arg
2902 ;; user requests a specific state
2903 (nth (1- (prefix-numeric-value arg))
2904 org-todo-keywords))
2905 ((null member) (car org-todo-keywords))
2906 ((null tail) nil) ;; -> first entry
2907 ((eq org-todo-interpretation 'sequence)
2908 (car tail))
2909 ((memq org-todo-interpretation '(type priority))
2910 (if (eq this-command last-command)
2911 (car tail)
2912 (if (> (length tail) 0) org-done-string nil)))
2913 (t nil)))
2914 (next (if state (concat " " state " ") " ")))
2915 (replace-match next t t)
2916 (setq org-last-todo-state-is-todo
2917 (not (equal state org-done-string)))
2918 (run-hooks 'org-after-todo-state-change-hook)))
2919 ;; Fixup cursor location if close to the keyword
2920 (if (and (outline-on-heading-p)
2921 (not (bolp))
2922 (save-excursion (beginning-of-line 1)
2923 (looking-at org-todo-line-regexp))
2924 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2925 (progn
2926 (goto-char (or (match-end 2) (match-end 1)))
2927 (just-one-space))))
2928
2929 (defun org-show-todo-tree (arg)
2930 "Make a compact tree which shows all headlines marked with TODO.
2931 The tree will show the lines where the regexp matches, and all higher
2932 headlines above the match."
2933 (interactive "P")
2934 (let ((case-fold-search nil)
2935 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2936 (message "%d TODO entries found"
2937 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2938
2939 (defun org-deadline ()
2940 "Insert the DEADLINE: string to make a deadline.
2941 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2942 to modify it to the correct date."
2943 (interactive)
2944 (insert
2945 org-deadline-string " "
2946 (format-time-string (car org-time-stamp-formats)
2947 (org-read-date nil 'to-time)))
2948 (message "%s" (substitute-command-keys
2949 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2950
2951 (defun org-schedule ()
2952 "Insert the SCHEDULED: string to schedule a TODO item.
2953 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2954 to modify it to the correct date."
2955 (interactive)
2956 (insert
2957 org-scheduled-string " "
2958 (format-time-string (car org-time-stamp-formats)
2959 (org-read-date nil 'to-time)))
2960 (message "%s" (substitute-command-keys
2961 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2962
2963
2964 (defun org-occur (regexp &optional callback)
2965 "Make a compact tree which shows all matches of REGEXP.
2966 The tree will show the lines where the regexp matches, and all higher
2967 headlines above the match. It will also show the heading after the match,
2968 to make sure editing the matching entry is easy.
2969 if CALLBACK is non-nil, it is a function which is called to confirm
2970 that the match should indeed be shown."
2971 (interactive "sRegexp: ")
2972 (setq regexp (org-check-occur-regexp regexp))
2973 (let ((cnt 0))
2974 (save-excursion
2975 (goto-char (point-min))
2976 (hide-sublevels 1)
2977 (while (re-search-forward regexp nil t)
2978 (when (or (not callback)
2979 (funcall callback))
2980 (setq cnt (1+ cnt))
2981 (org-show-hierarchy-above))))
2982 (run-hooks 'org-occur-hook)
2983 (if (interactive-p)
2984 (message "%d match(es) for regexp %s" cnt regexp))
2985 cnt))
2986
2987 (defun org-show-hierarchy-above ()
2988 "Make sure point and the headings hierarchy above is visible."
2989 (if (org-on-heading-p t)
2990 (org-flag-heading nil) ; only show the heading
2991 (org-show-hidden-entry)) ; show entire entry
2992 (save-excursion
2993 (and org-show-following-heading
2994 (outline-next-heading)
2995 (org-flag-heading nil))) ; show the next heading
2996 (save-excursion ; show all higher headings
2997 (while (condition-case nil
2998 (progn (org-up-heading-all 1) t)
2999 (error nil))
3000 (org-flag-heading nil))))
3001
3002 ;;; Priorities
3003
3004 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3005 "Regular expression matching the priority indicator.")
3006
3007 (defvar org-remove-priority-next-time nil)
3008
3009 (defun org-priority-up ()
3010 "Increase the priority of the current item."
3011 (interactive)
3012 (org-priority 'up))
3013
3014 (defun org-priority-down ()
3015 "Decrease the priority of the current item."
3016 (interactive)
3017 (org-priority 'down))
3018
3019 (defun org-priority (&optional action)
3020 "Change the priority of an item by ARG.
3021 ACTION can be set, up, or down."
3022 (interactive)
3023 (setq action (or action 'set))
3024 (let (current new news have remove)
3025 (save-excursion
3026 (org-back-to-heading)
3027 (if (looking-at org-priority-regexp)
3028 (setq current (string-to-char (match-string 2))
3029 have t)
3030 (setq current org-default-priority))
3031 (cond
3032 ((eq action 'set)
3033 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3034 (setq new (read-char-exclusive))
3035 (cond ((equal new ?\ ) (setq remove t))
3036 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3037 (error "Priority must be between `%c' and `%c'"
3038 ?A org-lowest-priority))))
3039 ((eq action 'up)
3040 (setq new (1- current)))
3041 ((eq action 'down)
3042 (setq new (1+ current)))
3043 (t (error "Invalid action")))
3044 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3045 (setq news (format "%c" new))
3046 (if have
3047 (if remove
3048 (replace-match "" t t nil 1)
3049 (replace-match news t t nil 2))
3050 (if remove
3051 (error "No priority cookie found in line")
3052 (looking-at org-todo-line-regexp)
3053 (if (match-end 2)
3054 (progn
3055 (goto-char (match-end 2))
3056 (insert " [#" news "]"))
3057 (goto-char (match-beginning 3))
3058 (insert "[#" news "] ")))))
3059 (if remove
3060 (message "Priority removed")
3061 (message "Priority of current item set to %s" news))))
3062
3063
3064 (defun org-get-priority (s)
3065 "Find priority cookie and return priority."
3066 (save-match-data
3067 (if (not (string-match org-priority-regexp s))
3068 (* 1000 (- org-lowest-priority org-default-priority))
3069 (* 1000 (- org-lowest-priority
3070 (string-to-char (match-string 2 s)))))))
3071
3072 ;;; Timestamps
3073
3074 (defvar org-last-changed-timestamp nil)
3075
3076 (defun org-time-stamp (arg)
3077 "Prompt for a date/time and insert a time stamp.
3078 If the user specifies a time like HH:MM, or if this command is called
3079 with a prefix argument, the time stamp will contain date and time.
3080 Otherwise, only the date will be included. All parts of a date not
3081 specified by the user will be filled in from the current date/time.
3082 So if you press just return without typing anything, the time stamp
3083 will represent the current date/time. If there is already a timestamp
3084 at the cursor, it will be modified."
3085 (interactive "P")
3086 (let ((fmt (if arg (cdr org-time-stamp-formats)
3087 (car org-time-stamp-formats)))
3088 (org-time-was-given nil)
3089 time)
3090 (cond
3091 ((and (org-at-timestamp-p)
3092 (eq last-command 'org-time-stamp)
3093 (eq this-command 'org-time-stamp))
3094 (insert "--")
3095 (setq time (let ((this-command this-command))
3096 (org-read-date arg 'totime)))
3097 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3098 (insert (format-time-string fmt time)))
3099 ((org-at-timestamp-p)
3100 (setq time (let ((this-command this-command))
3101 (org-read-date arg 'totime)))
3102 (and (org-at-timestamp-p) (replace-match
3103 (setq org-last-changed-timestamp
3104 (format-time-string fmt time))
3105 t t))
3106 (message "Timestamp updated"))
3107 (t
3108 (setq time (let ((this-command this-command))
3109 (org-read-date arg 'totime)))
3110 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3111 (insert (format-time-string fmt time))))))
3112
3113 (defun org-time-stamp-inactive (&optional arg)
3114 "Insert an inactive time stamp.
3115 An inactive time stamp is enclosed in square brackets instead of angle
3116 brackets. It is inactive in the sense that it does not trigger agenda entries,
3117 does not link to the calendar and cannot be changed with the S-cursor keys."
3118 (interactive "P")
3119 (let ((fmt (if arg (cdr org-time-stamp-formats)
3120 (car org-time-stamp-formats)))
3121 (org-time-was-given nil)
3122 time)
3123 (setq time (org-read-date arg 'totime))
3124 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3125 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3126 (insert (format-time-string fmt time))))
3127
3128 ;;; FIXME: Make the function take "Fri" as "next friday"
3129 (defun org-read-date (&optional with-time to-time)
3130 "Read a date and make things smooth for the user.
3131 The prompt will suggest to enter an ISO date, but you can also enter anything
3132 which will at least partially be understood by `parse-time-string'.
3133 Unrecognized parts of the date will default to the current day, month ,year,
3134 hour and minute. For example,
3135 3-2-5 --> 2003-02-05
3136 feb 15 --> currentyear-02-15
3137 sep 12 9 --> 2009-09-12
3138 12:45 --> today 12:45
3139 22 sept 0:34 --> currentyear-09-22 0:34
3140 12 --> currentyear-currentmonth-12
3141 etc.
3142 The function understands only English month and weekday abbreviations,
3143 but this can be configured with the variables `parse-time-months' and
3144 `parse-time-weekdays'.
3145
3146 While prompting, a calendar is popped up - you can also select the
3147 date with the mouse (button 1). The calendar shows a period of three
3148 month. To scroll it to other months, use the keys `>' and `<'.
3149 If you don't like the calendar, turn it off with
3150 \(setq org-popup-calendar-for-date-prompt nil).
3151
3152 With optional argument TO-TIME, the date will immediately be converted
3153 to an internal time.
3154 With an optional argument WITH-TIME, the prompt will suggest to also
3155 insert a time. Note that when WITH-TIME is not set, you can still
3156 enter a time, and this function will inform the calling routine about
3157 this change. The calling routine may then choose to change the format
3158 used to insert the time stamp into the buffer to include the time."
3159 (let* ((default-time
3160 ;; Default time is either today, or, when entering a range,
3161 ;; the range start.
3162 (if (save-excursion
3163 (re-search-backward
3164 (concat org-ts-regexp "--\\=")
3165 (- (point) 20) t))
3166 (apply
3167 'encode-time
3168 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3169 (parse-time-string (match-string 1))))
3170 (current-time)))
3171 (timestr (format-time-string
3172 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3173 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3174 ans ans1 ans2
3175 second minute hour day month year tl)
3176
3177 (if org-popup-calendar-for-date-prompt
3178 ;; Also show a calendar for date selection
3179 ;; Copied (with modifications) from planner.el by John Wiegley
3180 (save-excursion
3181 (save-window-excursion
3182 (calendar)
3183 (calendar-forward-day (- (time-to-days default-time)
3184 (calendar-absolute-from-gregorian
3185 (calendar-current-date))))
3186 (let* ((old-map (current-local-map))
3187 (map (copy-keymap calendar-mode-map))
3188 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3189 (define-key map (kbd "RET") 'org-calendar-select)
3190 (define-key map (if org-xemacs-p [button1] [mouse-1])
3191 'org-calendar-select)
3192 (define-key minibuffer-local-map [(meta shift left)]
3193 (lambda () (interactive)
3194 (org-eval-in-calendar '(calendar-backward-month 1))))
3195 (define-key minibuffer-local-map [(meta shift right)]
3196 (lambda () (interactive)
3197 (org-eval-in-calendar '(calendar-forward-month 1))))
3198 (define-key minibuffer-local-map [(shift up)]
3199 (lambda () (interactive)
3200 (org-eval-in-calendar '(calendar-backward-week 1))))
3201 (define-key minibuffer-local-map [(shift down)]
3202 (lambda () (interactive)
3203 (org-eval-in-calendar '(calendar-forward-week 1))))
3204 (define-key minibuffer-local-map [(shift left)]
3205 (lambda () (interactive)
3206 (org-eval-in-calendar '(calendar-backward-day 1))))
3207 (define-key minibuffer-local-map [(shift right)]
3208 (lambda () (interactive)
3209 (org-eval-in-calendar '(calendar-forward-day 1))))
3210 (define-key minibuffer-local-map ">"
3211 (lambda () (interactive)
3212 (org-eval-in-calendar '(scroll-calendar-left 1))))
3213 (define-key minibuffer-local-map "<"
3214 (lambda () (interactive)
3215 (org-eval-in-calendar '(scroll-calendar-right 1))))
3216 (unwind-protect
3217 (progn
3218 (use-local-map map)
3219 (setq ans (read-string prompt "" nil nil))
3220 (setq ans (or ans1 ans2 ans)))
3221 (use-local-map old-map)))))
3222 ;; Naked prompt only
3223 (setq ans (read-string prompt "" nil timestr)))
3224
3225 (if (string-match
3226 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3227 (progn
3228 (setq year (if (match-end 2)
3229 (string-to-number (match-string 2 ans))
3230 (string-to-number (format-time-string "%Y")))
3231 month (string-to-number (match-string 3 ans))
3232 day (string-to-number (match-string 4 ans)))
3233 (if (< year 100) (setq year (+ 2000 year)))
3234 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3235 t t ans))))
3236 (setq tl (parse-time-string ans)
3237 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3238 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3239 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3240 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3241 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3242 second (or (nth 0 tl) 0))
3243 (if (and (boundp 'org-time-was-given)
3244 (nth 2 tl))
3245 (setq org-time-was-given t))
3246 (if (< year 100) (setq year (+ 2000 year)))
3247 (if to-time
3248 (encode-time second minute hour day month year)
3249 (if (or (nth 1 tl) (nth 2 tl))
3250 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3251 (format "%04d-%02d-%02d" year month day)))))
3252
3253 (defun org-eval-in-calendar (form)
3254 "Eval FORM in the calendar window and return to current window.
3255 Also, store the cursor date in variable ans2."
3256 (let ((sw (selected-window)))
3257 (select-window (get-buffer-window "*Calendar*"))
3258 (eval form)
3259 (when (calendar-cursor-to-date)
3260 (let* ((date (calendar-cursor-to-date))
3261 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3262 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3263 (select-window sw)))
3264
3265 (defun org-calendar-select ()
3266 "Return to `org-read-date' with the date currently selected.
3267 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3268 (interactive)
3269 (when (calendar-cursor-to-date)
3270 (let* ((date (calendar-cursor-to-date))
3271 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3272 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3273 (if (active-minibuffer-window) (exit-minibuffer))))
3274
3275 (defun org-check-deadlines (ndays)
3276 "Check if there are any deadlines due or past due.
3277 A deadline is considered due if it happens within `org-deadline-warning-days'
3278 days from today's date. If the deadline appears in an entry marked DONE,
3279 it is not shown. The prefix arg NDAYS can be used to test that many
3280 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3281 (interactive "P")
3282 (let* ((org-warn-days
3283 (cond
3284 ((equal ndays '(4)) 100000)
3285 (ndays (prefix-numeric-value ndays))
3286 (t org-deadline-warning-days)))
3287 (case-fold-search nil)
3288 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3289 (callback
3290 (lambda ()
3291 (and (let ((d1 (time-to-days (current-time)))
3292 (d2 (time-to-days
3293 (org-time-string-to-time (match-string 1)))))
3294 (< (- d2 d1) org-warn-days))
3295 (not (org-entry-is-done-p))))))
3296 (message "%d deadlines past-due or due within %d days"
3297 (org-occur regexp callback)
3298 org-warn-days)))
3299
3300 (defun org-evaluate-time-range (&optional to-buffer)
3301 "Evaluate a time range by computing the difference between start and end.
3302 Normally the result is just printed in the echo area, but with prefix arg
3303 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3304 If the time range is actually in a table, the result is inserted into the
3305 next column.
3306 For time difference computation, a year is assumed to be exactly 365
3307 days in order to avoid rounding problems."
3308 (interactive "P")
3309 (save-excursion
3310 (unless (org-at-date-range-p)
3311 (goto-char (point-at-bol))
3312 (re-search-forward org-tr-regexp (point-at-eol) t))
3313 (if (not (org-at-date-range-p))
3314 (error "Not at a time-stamp range, and none found in current line")))
3315 (let* ((ts1 (match-string 1))
3316 (ts2 (match-string 2))
3317 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3318 (match-end (match-end 0))
3319 (time1 (org-time-string-to-time ts1))
3320 (time2 (org-time-string-to-time ts2))
3321 (t1 (time-to-seconds time1))
3322 (t2 (time-to-seconds time2))
3323 (diff (abs (- t2 t1)))
3324 (negative (< (- t2 t1) 0))
3325 ;; (ys (floor (* 365 24 60 60)))
3326 (ds (* 24 60 60))
3327 (hs (* 60 60))
3328 (fy "%dy %dd %02d:%02d")
3329 (fy1 "%dy %dd")
3330 (fd "%dd %02d:%02d")
3331 (fd1 "%dd")
3332 (fh "%02d:%02d")
3333 y d h m align)
3334 ;; FIXME: Should I re-introduce years, make year refer to same date?
3335 ;; This would be the only useful way to have years, actually.
3336 (if havetime
3337 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3338 y 0
3339 d (floor (/ diff ds)) diff (mod diff ds)
3340 h (floor (/ diff hs)) diff (mod diff hs)
3341 m (floor (/ diff 60)))
3342 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3343 y 0
3344 d (floor (+ (/ diff ds) 0.5))
3345 h 0 m 0))
3346 (if (not to-buffer)
3347 (message (org-make-tdiff-string y d h m))
3348 (when (org-at-table-p)
3349 (goto-char match-end)
3350 (setq align t)
3351 (and (looking-at " *|") (goto-char (match-end 0))))
3352 (if (looking-at
3353 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3354 (replace-match ""))
3355 (if negative (insert " -"))
3356 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3357 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3358 (insert " " (format fh h m))))
3359 (if align (org-table-align))
3360 (message "Time difference inserted"))))
3361
3362 (defun org-make-tdiff-string (y d h m)
3363 (let ((fmt "")
3364 (l nil))
3365 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3366 l (push y l)))
3367 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3368 l (push d l)))
3369 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3370 l (push h l)))
3371 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3372 l (push m l)))
3373 (apply 'format fmt (nreverse l))))
3374
3375 (defun org-time-string-to-time (s)
3376 (apply 'encode-time (org-parse-time-string s)))
3377
3378 (defun org-parse-time-string (s &optional nodefault)
3379 "Parse the standard Org-mode time string.
3380 This should be a lot faster than the normal `parse-time-string'.
3381 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3382 hour and minute fields will be nil if not given."
3383 (if (string-match org-ts-regexp1 s)
3384 (list 0
3385 (if (or (match-beginning 8) (not nodefault))
3386 (string-to-number (or (match-string 8 s) "0")))
3387 (if (or (match-beginning 7) (not nodefault))
3388 (string-to-number (or (match-string 7 s) "0")))
3389 (string-to-number (match-string 4 s))
3390 (string-to-number (match-string 3 s))
3391 (string-to-number (match-string 2 s))
3392 nil nil nil)
3393 (make-list 9 0)))
3394
3395 (defun org-timestamp-up (&optional arg)
3396 "Increase the date item at the cursor by one.
3397 If the cursor is on the year, change the year. If it is on the month or
3398 the day, change that.
3399 With prefix ARG, change by that many units."
3400 (interactive "p")
3401 (org-timestamp-change (prefix-numeric-value arg)))
3402
3403 (defun org-timestamp-down (&optional arg)
3404 "Decrease the date item at the cursor by one.
3405 If the cursor is on the year, change the year. If it is on the month or
3406 the day, change that.
3407 With prefix ARG, change by that many units."
3408 (interactive "p")
3409 (org-timestamp-change (- (prefix-numeric-value arg))))
3410
3411 (defun org-timestamp-up-day (&optional arg)
3412 "Increase the date in the time stamp by one day.
3413 With prefix ARG, change that many days."
3414 (interactive "p")
3415 (org-timestamp-change (prefix-numeric-value arg) 'day))
3416
3417 (defun org-timestamp-down-day (&optional arg)
3418 "Decrease the date in the time stamp by one day.
3419 With prefix ARG, change that many days."
3420 (interactive "p")
3421 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3422
3423 (defsubst org-pos-in-match-range (pos n)
3424 (and (match-beginning n)
3425 (<= (match-beginning n) pos)
3426 (>= (match-end n) pos)))
3427
3428 (defun org-at-timestamp-p ()
3429 "Determine if the cursor is or at a timestamp."
3430 (interactive)
3431 (let* ((tsr org-ts-regexp2)
3432 (pos (point))
3433 (ans (or (looking-at tsr)
3434 (save-excursion
3435 (skip-chars-backward "^<\n\r\t")
3436 (if (> (point) 1) (backward-char 1))
3437 (and (looking-at tsr)
3438 (> (- (match-end 0) pos) -1))))))
3439 (and (boundp 'org-ts-what)
3440 (setq org-ts-what
3441 (cond
3442 ((org-pos-in-match-range pos 2) 'year)
3443 ((org-pos-in-match-range pos 3) 'month)
3444 ((org-pos-in-match-range pos 7) 'hour)
3445 ((org-pos-in-match-range pos 8) 'minute)
3446 ((or (org-pos-in-match-range pos 4)
3447 (org-pos-in-match-range pos 5)) 'day)
3448 (t 'day))))
3449 ans))
3450
3451 (defun org-timestamp-change (n &optional what)
3452 "Change the date in the time stamp at point.
3453 The date will be changed by N times WHAT. WHAT can be `day', `month',
3454 `year', `minute', `second'. If WHAT is not given, the cursor position
3455 in the timestamp determines what will be changed."
3456 (let ((fmt (car org-time-stamp-formats))
3457 org-ts-what
3458 (pos (point))
3459 ts time time0)
3460 (if (not (org-at-timestamp-p))
3461 (error "Not at a timestamp"))
3462 (setq org-ts-what (or what org-ts-what))
3463 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3464 (- (match-end 0) (match-beginning 0))))
3465 1)
3466 (cdr org-time-stamp-formats)
3467 (car org-time-stamp-formats)))
3468 (setq ts (match-string 0))
3469 (replace-match "")
3470 (setq time0 (org-parse-time-string ts))
3471 (setq time
3472 (apply 'encode-time
3473 (append
3474 (list (or (car time0) 0))
3475 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3476 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3477 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3478 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3479 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3480 (nthcdr 6 time0))))
3481 (if (eq what 'calendar)
3482 (let ((cal-date
3483 (save-excursion
3484 (save-match-data
3485 (set-buffer "*Calendar*")
3486 (calendar-cursor-to-date)))))
3487 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3488 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3489 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3490 (setcar time0 (or (car time0) 0))
3491 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3492 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3493 (setq time (apply 'encode-time time0))))
3494 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3495 (goto-char pos)
3496 ;; Try to recenter the calendar window, if any
3497 (if (and org-calendar-follow-timestamp-change
3498 (get-buffer-window "*Calendar*" t)
3499 (memq org-ts-what '(day month year)))
3500 (org-recenter-calendar (time-to-days time)))))
3501
3502 (defun org-recenter-calendar (date)
3503 "If the calendar is visible, recenter it to DATE."
3504 (let* ((win (selected-window))
3505 (cwin (get-buffer-window "*Calendar*" t)))
3506 (when cwin
3507 (select-window cwin)
3508 (calendar-goto-date (if (listp date) date
3509 (calendar-gregorian-from-absolute date)))
3510 (select-window win))))
3511
3512 (defun org-goto-calendar (&optional arg)
3513 "Go to the Emacs calendar at the current date.
3514 If there is a time stamp in the current line, go to that date.
3515 A prefix ARG can be used force the current date."
3516 (interactive "P")
3517 (let ((tsr org-ts-regexp) diff)
3518 (if (or (org-at-timestamp-p)
3519 (save-excursion
3520 (beginning-of-line 1)
3521 (looking-at (concat ".*" tsr))))
3522 (let ((d1 (time-to-days (current-time)))
3523 (d2 (time-to-days
3524 (org-time-string-to-time (match-string 1)))))
3525 (setq diff (- d2 d1))))
3526 (calendar)
3527 (calendar-goto-today)
3528 (if (and diff (not arg)) (calendar-forward-day diff))))
3529
3530 (defun org-date-from-calendar ()
3531 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3532 If there is already a time stamp at the cursor position, update it."
3533 (interactive)
3534 (org-timestamp-change 0 'calendar))
3535
3536 ;;; Agenda, and Diary Integration
3537
3538 ;;; Define the mode
3539
3540 (defvar org-agenda-mode-map (make-sparse-keymap)
3541 "Keymap for `org-agenda-mode'.")
3542
3543 (defvar org-agenda-menu)
3544 (defvar org-agenda-follow-mode nil)
3545 (defvar org-agenda-buffer-name "*Org Agenda*")
3546 (defvar org-agenda-redo-command nil)
3547 (defvar org-agenda-mode-hook nil)
3548
3549 ;;;###autoload
3550 (defun org-agenda-mode ()
3551 "Mode for time-sorted view on action items in Org-mode files.
3552
3553 The following commands are available:
3554
3555 \\{org-agenda-mode-map}"
3556 (interactive)
3557 (kill-all-local-variables)
3558 (setq major-mode 'org-agenda-mode)
3559 (setq mode-name "Org-Agenda")
3560 (use-local-map org-agenda-mode-map)
3561 (easy-menu-add org-agenda-menu)
3562 (if org-startup-truncated (setq truncate-lines t))
3563 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3564 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3565 (setq org-agenda-follow-mode nil)
3566 (easy-menu-change
3567 '("Agenda") "Agenda Files"
3568 (append
3569 (list
3570 ["Edit File List" (customize-variable 'org-agenda-files) t]
3571 "--")
3572 (mapcar 'org-file-menu-entry org-agenda-files)))
3573 (org-agenda-set-mode-name)
3574 (apply
3575 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3576 org-agenda-mode-hook))
3577
3578 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3579 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3580 (define-key org-agenda-mode-map " " 'org-agenda-show)
3581 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3582 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3583 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3584 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3585 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3586 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3587 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3588 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3589 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3590 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
3591 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
3592
3593 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3594 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3595 (while l (define-key org-agenda-mode-map
3596 (int-to-string (pop l)) 'digit-argument)))
3597
3598 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3599 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3600 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3601 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3602 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3603 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3604 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3605 (define-key org-agenda-mode-map "n" 'next-line)
3606 (define-key org-agenda-mode-map "p" 'previous-line)
3607 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3608 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3609 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3610 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3611 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3612 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3613 (eval-after-load "calendar"
3614 '(define-key calendar-mode-map org-calendar-to-agenda-key
3615 'org-calendar-goto-agenda))
3616 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3617 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3618 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3619 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3620 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3621 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3622 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3623 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3624 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3625 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3626 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3627 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
3628 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
3629 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3630 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3631
3632 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3633 "Local keymap for agenda entries from Org-mode.")
3634
3635 (define-key org-agenda-keymap
3636 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3637 (define-key org-agenda-keymap
3638 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3639
3640 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3641 '("Agenda"
3642 ("Agenda Files")
3643 "--"
3644 ["Show" org-agenda-show t]
3645 ["Go To (other window)" org-agenda-goto t]
3646 ["Go To (one window)" org-agenda-switch-to t]
3647 ["Follow Mode" org-agenda-follow-mode
3648 :style toggle :selected org-agenda-follow-mode :active t]
3649 "--"
3650 ["Cycle TODO" org-agenda-todo t]
3651 ("Reschedule"
3652 ["Reschedule +1 day" org-agenda-date-later t]
3653 ["Reschedule -1 day" org-agenda-date-earlier t]
3654 "--"
3655 ["Reschedule to ..." org-agenda-date-prompt t])
3656 ("Priority"
3657 ["Set Priority" org-agenda-priority t]
3658 ["Increase Priority" org-agenda-priority-up t]
3659 ["Decrease Priority" org-agenda-priority-down t]
3660 ["Show Priority" org-agenda-show-priority t])
3661 "--"
3662 ["Rebuild buffer" org-agenda-redo t]
3663 ["Goto Today" org-agenda-goto-today t]
3664 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3665 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3666 "--"
3667 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3668 :style radio :selected (equal org-agenda-ndays 1)]
3669 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3670 :style radio :selected (equal org-agenda-ndays 7)]
3671 "--"
3672 ["Include Diary" org-agenda-toggle-diary
3673 :style toggle :selected org-agenda-include-diary :active t]
3674 ["Use Time Grid" org-agenda-toggle-time-grid
3675 :style toggle :selected org-agenda-use-time-grid :active t]
3676 "--"
3677 ["New Diary Entry" org-agenda-diary-entry t]
3678 ("Calendar Commands"
3679 ["Goto Calendar" org-agenda-goto-calendar t]
3680 ["Phases of the Moon" org-agenda-phases-of-moon t]
3681 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3682 ["Holidays" org-agenda-holidays t]
3683 ["Convert" org-agenda-convert-date t])
3684 "--"
3685 ["Quit" org-agenda-quit t]
3686 ["Exit and Release Buffers" org-agenda-exit t]
3687 ))
3688
3689 (defvar org-agenda-markers nil
3690 "List of all currently active markers created by `org-agenda'.")
3691 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3692 "Creation time of the last agenda marker.")
3693
3694 (defun org-agenda-new-marker (&optional pos)
3695 "Return a new agenda marker.
3696 Org-mode keeps a list of these markers and resets them when they are
3697 no longer in use."
3698 (let ((m (copy-marker (or pos (point)))))
3699 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3700 (push m org-agenda-markers)
3701 m))
3702
3703 (defun org-agenda-maybe-reset-markers (&optional force)
3704 "Reset markers created by `org-agenda'. But only if they are old enough."
3705 (if (or force
3706 (> (- (time-to-seconds (current-time))
3707 org-agenda-last-marker-time)
3708 5))
3709 (while org-agenda-markers
3710 (move-marker (pop org-agenda-markers) nil))))
3711
3712 (defvar org-agenda-new-buffers nil
3713 "Buffers created to visit agenda files.")
3714
3715 (defun org-get-agenda-file-buffer (file)
3716 "Get a buffer visiting FILE. If the buffer needs to be created, add
3717 it to the list of buffers which might be released later."
3718 (let ((buf (find-buffer-visiting file)))
3719 (if buf
3720 buf ; just return it
3721 ;; Make a new buffer and remember it
3722 (setq buf (find-file-noselect file))
3723 (if buf (push buf org-agenda-new-buffers))
3724 buf)))
3725
3726 (defun org-release-buffers (blist)
3727 "Release all buffers in list, asking the user for confirmation when needed.
3728 When a buffer is unmodified, it is just killed. When modified, it is saved
3729 \(if the user agrees) and then killed."
3730 (let (buf file)
3731 (while (setq buf (pop blist))
3732 (setq file (buffer-file-name buf))
3733 (when (and (buffer-modified-p buf)
3734 file
3735 (y-or-n-p (format "Save file %s? " file)))
3736 (with-current-buffer buf (save-buffer)))
3737 (kill-buffer buf))))
3738
3739 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3740
3741 (defun org-timeline (&optional include-all)
3742 "Show a time-sorted view of the entries in the current org file.
3743 Only entries with a time stamp of today or later will be listed. With
3744 one \\[universal-argument] prefix argument, past entries will also be listed.
3745 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3746 under the current date.
3747 If the buffer contains an active region, only check the region for
3748 dates."
3749 (interactive "P")
3750 (require 'calendar)
3751 (org-agenda-maybe-reset-markers 'force)
3752 (org-compile-prefix-format org-timeline-prefix-format)
3753 (let* ((dopast include-all)
3754 (dotodo (equal include-all '(16)))
3755 (entry (buffer-file-name))
3756 (org-agenda-files (list (buffer-file-name)))
3757 (date (calendar-current-date))
3758 (win (selected-window))
3759 (pos1 (point))
3760 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3761 (end (if (org-region-active-p) (region-end) (point-max)))
3762 (day-numbers (org-get-all-dates beg end 'no-ranges
3763 t)) ; always include today
3764 (today (time-to-days (current-time)))
3765 (org-respect-restriction t)
3766 (past t)
3767 s e rtn d)
3768 (setq org-agenda-redo-command
3769 (list 'progn
3770 (list 'switch-to-buffer-other-window (current-buffer))
3771 (list 'org-timeline (list 'quote include-all))))
3772 (if (not dopast)
3773 ;; Remove past dates from the list of dates.
3774 (setq day-numbers (delq nil (mapcar (lambda(x)
3775 (if (>= x today) x nil))
3776 day-numbers))))
3777 (switch-to-buffer-other-window
3778 (get-buffer-create org-agenda-buffer-name))
3779 (setq buffer-read-only nil)
3780 (erase-buffer)
3781 (org-agenda-mode) (setq buffer-read-only nil)
3782 (while (setq d (pop day-numbers))
3783 (if (and (>= d today)
3784 dopast
3785 past)
3786 (progn
3787 (setq past nil)
3788 (insert (make-string 79 ?-) "\n")))
3789 (setq date (calendar-gregorian-from-absolute d))
3790 (setq s (point))
3791 (if dotodo
3792 (setq rtn (org-agenda-get-day-entries
3793 entry date :todo :timestamp))
3794 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3795 (if (or rtn (equal d today))
3796 (progn
3797 (insert (calendar-day-name date) " "
3798 (number-to-string (extract-calendar-day date)) " "
3799 (calendar-month-name (extract-calendar-month date)) " "
3800 (number-to-string (extract-calendar-year date)) "\n")
3801 (put-text-property s (1- (point)) 'face
3802 'org-link)
3803 (if (equal d today)
3804 (put-text-property s (1- (point)) 'org-today t))
3805 (insert (org-finalize-agenda-entries rtn) "\n")
3806 (put-text-property s (1- (point)) 'day d))))
3807 (goto-char (point-min))
3808 (setq buffer-read-only t)
3809 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3810 (point-min)))
3811 (when (not org-select-timeline-window)
3812 (select-window win)
3813 (goto-char pos1))))
3814
3815 ;;;###autoload
3816 (defun org-agenda (&optional include-all start-day ndays)
3817 "Produce a weekly view from all files in variable `org-agenda-files'.
3818 The view will be for the current week, but from the overview buffer you
3819 will be able to go to other weeks.
3820 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3821 also be shown, under the current date.
3822 START-DAY defaults to TODAY, or to the most recent match for the weekday
3823 given in `org-agenda-start-on-weekday'.
3824 NDAYS defaults to `org-agenda-ndays'."
3825 (interactive "P")
3826 (org-agenda-maybe-reset-markers 'force)
3827 (org-compile-prefix-format org-agenda-prefix-format)
3828 (require 'calendar)
3829 (let* ((org-agenda-start-on-weekday
3830 (if (or (equal ndays 1)
3831 (and (null ndays) (equal 1 org-agenda-ndays)))
3832 nil org-agenda-start-on-weekday))
3833 (files (copy-sequence org-agenda-files))
3834 (win (selected-window))
3835 (today (time-to-days (current-time)))
3836 (sd (or start-day today))
3837 (start (if (or (null org-agenda-start-on-weekday)
3838 (< org-agenda-ndays 7))
3839 sd
3840 (let* ((nt (calendar-day-of-week
3841 (calendar-gregorian-from-absolute sd)))
3842 (n1 org-agenda-start-on-weekday)
3843 (d (- nt n1)))
3844 (- sd (+ (if (< d 0) 7 0) d)))))
3845 (day-numbers (list start))
3846 (inhibit-redisplay t)
3847 s e rtn rtnall file date d start-pos end-pos todayp nd)
3848 (setq org-agenda-redo-command
3849 (list 'org-agenda (list 'quote include-all) start-day ndays))
3850 ;; Make the list of days
3851 (setq ndays (or ndays org-agenda-ndays)
3852 nd ndays)
3853 (while (> ndays 1)
3854 (push (1+ (car day-numbers)) day-numbers)
3855 (setq ndays (1- ndays)))
3856 (setq day-numbers (nreverse day-numbers))
3857 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3858 (progn
3859 (delete-other-windows)
3860 (switch-to-buffer-other-window
3861 (get-buffer-create org-agenda-buffer-name))))
3862 (setq buffer-read-only nil)
3863 (erase-buffer)
3864 (org-agenda-mode) (setq buffer-read-only nil)
3865 (set (make-local-variable 'starting-day) (car day-numbers))
3866 (set (make-local-variable 'include-all-loc) include-all)
3867 (when (and (or include-all org-agenda-include-all-todo)
3868 (member today day-numbers))
3869 (setq files org-agenda-files
3870 rtnall nil)
3871 (while (setq file (pop files))
3872 (catch 'nextfile
3873 (org-check-agenda-file file)
3874 (setq date (calendar-gregorian-from-absolute today)
3875 rtn (org-agenda-get-day-entries
3876 file date :todo))
3877 (setq rtnall (append rtnall rtn))))
3878 (when rtnall
3879 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3880 (add-text-properties (point-min) (1- (point))
3881 (list 'face 'org-link))
3882 (insert (org-finalize-agenda-entries rtnall) "\n")))
3883 (while (setq d (pop day-numbers))
3884 (setq date (calendar-gregorian-from-absolute d)
3885 s (point))
3886 (if (or (setq todayp (= d today))
3887 (and (not start-pos) (= d sd)))
3888 (setq start-pos (point))
3889 (if (and start-pos (not end-pos))
3890 (setq end-pos (point))))
3891 (setq files org-agenda-files
3892 rtnall nil)
3893 (while (setq file (pop files))
3894 (catch 'nextfile
3895 (org-check-agenda-file file)
3896 (setq rtn (org-agenda-get-day-entries file date))
3897 (setq rtnall (append rtnall rtn))))
3898 (if org-agenda-include-diary
3899 (progn
3900 (require 'diary-lib)
3901 (setq rtn (org-get-entries-from-diary date))
3902 (setq rtnall (append rtnall rtn))))
3903 (if (or rtnall org-agenda-show-all-dates)
3904 (progn
3905 (insert (format "%-9s %2d %s %4d\n"
3906 (calendar-day-name date)
3907 (extract-calendar-day date)
3908 (calendar-month-name (extract-calendar-month date))
3909 (extract-calendar-year date)))
3910 (put-text-property s (1- (point)) 'face
3911 'org-link)
3912 (if rtnall (insert
3913 (org-finalize-agenda-entries ;; FIXME: condition needed
3914 (org-agenda-add-time-grid-maybe
3915 rtnall nd todayp))
3916 "\n"))
3917 (put-text-property s (1- (point)) 'day d))))
3918 (goto-char (point-min))
3919 (setq buffer-read-only t)
3920 (if org-fit-agenda-window
3921 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3922 (/ (frame-height) 2)))
3923 (unless (and (pos-visible-in-window-p (point-min))
3924 (pos-visible-in-window-p (point-max)))
3925 (goto-char (1- (point-max)))
3926 (recenter -1)
3927 (if (not (pos-visible-in-window-p (or start-pos 1)))
3928 (progn
3929 (goto-char (or start-pos 1))
3930 (recenter 1))))
3931 (goto-char (or start-pos 1))
3932 (if (not org-select-agenda-window) (select-window win))
3933 (message "")))
3934
3935 (defun org-check-agenda-file (file)
3936 "Make sure FILE exists. If not, ask user what to do."
3937 ;; FIXME: this does not correctly change the menus
3938 ;; Could probably be fixed by explicitly going to the buffer.
3939 (when (not (file-exists-p file))
3940 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3941 file)
3942 (let ((r (downcase (read-char-exclusive))))
3943 (cond
3944 ((equal r ?r)
3945 (org-remove-file file)
3946 (throw 'nextfile t))
3947 (t (error "Abort"))))))
3948
3949 (defun org-agenda-quit ()
3950 "Exit agenda by removing the window or the buffer."
3951 (interactive)
3952 (let ((buf (current-buffer)))
3953 (if (not (one-window-p)) (delete-window))
3954 (kill-buffer buf)
3955 (org-agenda-maybe-reset-markers 'force)))
3956
3957 (defun org-agenda-exit ()
3958 "Exit agenda by removing the window or the buffer.
3959 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3960 Org-mode buffers visited directly by the user will not be touched."
3961 (interactive)
3962 (org-release-buffers org-agenda-new-buffers)
3963 (setq org-agenda-new-buffers nil)
3964 (org-agenda-quit))
3965
3966 (defun org-agenda-redo ()
3967 "Rebuild Agenda."
3968 (interactive)
3969 (eval org-agenda-redo-command))
3970
3971 (defun org-agenda-goto-today ()
3972 "Go to today."
3973 (interactive)
3974 (if (boundp 'starting-day)
3975 (let ((cmd (car org-agenda-redo-command))
3976 (iall (nth 1 org-agenda-redo-command))
3977 (nday (nth 3 org-agenda-redo-command)))
3978 (eval (list cmd iall nil nday)))
3979 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3980 (point-min)))))
3981
3982 (defun org-agenda-later (arg)
3983 "Go forward in time by `org-agenda-ndays' days.
3984 With prefix ARG, go forward that many times `org-agenda-ndays'."
3985 (interactive "p")
3986 (unless (boundp 'starting-day)
3987 (error "Not allowed"))
3988 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3989 (+ starting-day (* arg org-agenda-ndays))))
3990
3991 (defun org-agenda-earlier (arg)
3992 "Go back in time by `org-agenda-ndays' days.
3993 With prefix ARG, go back that many times `org-agenda-ndays'."
3994 (interactive "p")
3995 (unless (boundp 'starting-day)
3996 (error "Not allowed"))
3997 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3998 (- starting-day (* arg org-agenda-ndays))))
3999
4000 (defun org-agenda-week-view ()
4001 "Switch to weekly view for agenda."
4002 (interactive)
4003 (unless (boundp 'starting-day)
4004 (error "Not allowed"))
4005 (setq org-agenda-ndays 7)
4006 (org-agenda include-all-loc
4007 (or (get-text-property (point) 'day)
4008 starting-day))
4009 (org-agenda-set-mode-name)
4010 (message "Switched to week view"))
4011
4012 (defun org-agenda-day-view ()
4013 "Switch to weekly view for agenda."
4014 (interactive)
4015 (unless (boundp 'starting-day)
4016 (error "Not allowed"))
4017 (setq org-agenda-ndays 1)
4018 (org-agenda include-all-loc
4019 (or (get-text-property (point) 'day)
4020 starting-day))
4021 (org-agenda-set-mode-name)
4022 (message "Switched to day view"))
4023
4024 (defun org-agenda-next-date-line (&optional arg)
4025 "Jump to the next line indicating a date in agenda buffer."
4026 (interactive "p")
4027 (beginning-of-line 1)
4028 (if (looking-at "^\\S-") (forward-char 1))
4029 (if (not (re-search-forward "^\\S-" nil t arg))
4030 (progn
4031 (backward-char 1)
4032 (error "No next date after this line in this buffer")))
4033 (goto-char (match-beginning 0)))
4034
4035 (defun org-agenda-previous-date-line (&optional arg)
4036 "Jump to the next line indicating a date in agenda buffer."
4037 (interactive "p")
4038 (beginning-of-line 1)
4039 (if (not (re-search-backward "^\\S-" nil t arg))
4040 (error "No previous date before this line in this buffer")))
4041
4042 ;; Initialize the highlight
4043 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4044 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4045 'face 'highlight)
4046
4047 (defun org-highlight (begin end &optional buffer)
4048 "Highlight a region with overlay."
4049 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4050 org-hl begin end (or buffer (current-buffer))))
4051
4052 (defun org-unhighlight ()
4053 "Detach overlay INDEX."
4054 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4055
4056
4057 (defun org-agenda-follow-mode ()
4058 "Toggle follow mode in an agenda buffer."
4059 (interactive)
4060 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4061 (org-agenda-set-mode-name)
4062 (message "Follow mode is %s"
4063 (if org-agenda-follow-mode "on" "off")))
4064
4065 (defun org-agenda-toggle-diary ()
4066 "Toggle follow mode in an agenda buffer."
4067 (interactive)
4068 (setq org-agenda-include-diary (not org-agenda-include-diary))
4069 (org-agenda-redo)
4070 (org-agenda-set-mode-name)
4071 (message "Diary inclusion turned %s"
4072 (if org-agenda-include-diary "on" "off")))
4073
4074 (defun org-agenda-toggle-time-grid ()
4075 "Toggle follow mode in an agenda buffer."
4076 (interactive)
4077 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4078 (org-agenda-redo)
4079 (org-agenda-set-mode-name)
4080 (message "Time-grid turned %s"
4081 (if org-agenda-use-time-grid "on" "off")))
4082
4083 (defun org-agenda-set-mode-name ()
4084 "Set the mode name to indicate all the small mode settings."
4085 (setq mode-name
4086 (concat "Org-Agenda"
4087 (if (equal org-agenda-ndays 1) " Day" "")
4088 (if (equal org-agenda-ndays 7) " Week" "")
4089 (if org-agenda-follow-mode " Follow" "")
4090 (if org-agenda-include-diary " Diary" "")
4091 (if org-agenda-use-time-grid " Grid" "")))
4092 (force-mode-line-update))
4093
4094 (defun org-agenda-post-command-hook ()
4095 (and (eolp) (not (bolp)) (backward-char 1))
4096 (if (and org-agenda-follow-mode
4097 (get-text-property (point) 'org-marker))
4098 (org-agenda-show)))
4099
4100 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4101
4102 (defun org-get-entries-from-diary (date)
4103 "Get the (Emacs Calendar) diary entries for DATE."
4104 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4105 (diary-display-hook '(fancy-diary-display))
4106 (list-diary-entries-hook
4107 (cons 'org-diary-default-entry list-diary-entries-hook))
4108 (diary-file-name-prefix-function nil) ; turn this feature off
4109 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4110 entries
4111 (org-disable-agenda-to-diary t))
4112 (save-excursion
4113 (save-window-excursion
4114 (list-diary-entries date 1)))
4115 (if (not (get-buffer fancy-diary-buffer))
4116 (setq entries nil)
4117 (with-current-buffer fancy-diary-buffer
4118 (setq buffer-read-only nil)
4119 (if (= (point-max) 1)
4120 ;; No entries
4121 (setq entries nil)
4122 ;; Omit the date and other unnecessary stuff
4123 (org-agenda-cleanup-fancy-diary)
4124 ;; Add prefix to each line and extend the text properties
4125 (if (= (point-max) 1)
4126 (setq entries nil)
4127 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4128 (set-buffer-modified-p nil)
4129 (kill-buffer fancy-diary-buffer)))
4130 (when entries
4131 (setq entries (org-split-string entries "\n"))
4132 (setq entries
4133 (mapcar
4134 (lambda (x)
4135 (setq x (org-format-agenda-item "" x "Diary" 'time))
4136 ;; Extend the text properties to the beginning of the line
4137 (add-text-properties
4138 0 (length x)
4139 (text-properties-at (1- (length x)) x)
4140 x)
4141 x)
4142 entries)))))
4143
4144 (defun org-agenda-cleanup-fancy-diary ()
4145 "Remove unwanted stuff in buffer created by fancy-diary-display.
4146 This gets rid of the date, the underline under the date, and
4147 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4148 date. Itt also removes lines that contain only whitespace."
4149 (goto-char (point-min))
4150 (if (looking-at ".*?:[ \t]*")
4151 (progn
4152 (replace-match "")
4153 (re-search-forward "\n=+$" nil t)
4154 (replace-match "")
4155 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4156 (re-search-forward "\n=+$" nil t)
4157 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4158 (goto-char (point-min))
4159 (while (re-search-forward "^ +\n" nil t)
4160 (replace-match ""))
4161 (goto-char (point-min))
4162 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4163 (replace-match "")))
4164
4165 ;; Make sure entries from the diary have the right text properties.
4166 (eval-after-load "diary-lib"
4167 '(if (boundp 'diary-modify-entry-list-string-function)
4168 ;; We can rely on the hook, nothing to do
4169 nil
4170 ;; Hook not avaiable, must use advice to make this work
4171 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4172 "Make the position visible."
4173 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4174 (stringp string)
4175 (buffer-file-name))
4176 (setq string (org-modify-diary-entry-string string))))))
4177
4178 (defun org-modify-diary-entry-string (string)
4179 "Add text properties to string, allowing org-mode to act on it."
4180 (add-text-properties
4181 0 (length string)
4182 (list 'mouse-face 'highlight
4183 'keymap org-agenda-keymap
4184 'help-echo
4185 (format
4186 "mouse-2 or RET jump to diary file %s"
4187 (abbreviate-file-name (buffer-file-name)))
4188 'org-agenda-diary-link t
4189 'org-marker (org-agenda-new-marker (point-at-bol)))
4190 string)
4191 string)
4192
4193 (defun org-diary-default-entry ()
4194 "Add a dummy entry to the diary.
4195 Needed to avoid empty dates which mess up holiday display."
4196 ;; Catch the error if dealing with the new add-to-diary-alist
4197 (when org-disable-agenda-to-diary
4198 (condition-case nil
4199 (add-to-diary-list original-date "Org-mode dummy" "")
4200 (error
4201 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4202
4203 (defun org-add-file (&optional file)
4204 "Add current file to the list of files in variable `org-agenda-files'.
4205 These are the files which are being checked for agenda entries.
4206 Optional argument FILE means, use this file instead of the current.
4207 It is possible (but not recommended) to add this function to the
4208 `org-mode-hook'."
4209 (interactive)
4210 (catch 'exit
4211 (let* ((file (or file (buffer-file-name)
4212 (if (interactive-p)
4213 (error "Buffer is not visiting a file")
4214 (throw 'exit nil))))
4215 (true-file (file-truename file))
4216 (afile (abbreviate-file-name file))
4217 (present (delq nil (mapcar
4218 (lambda (x)
4219 (equal true-file (file-truename x)))
4220 org-agenda-files))))
4221 (if (not present)
4222 (progn
4223 (setq org-agenda-files
4224 (cons afile org-agenda-files))
4225 ;; Make sure custom.el does not end up with Org-mode
4226 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4227 (customize-save-variable 'org-agenda-files org-agenda-files))
4228 (org-install-agenda-files-menu)
4229 (message "Added file: %s" afile))
4230 (message "File was already in list: %s" afile)))))
4231
4232 (defun org-remove-file (&optional file)
4233 "Remove current file from the list of files in variable `org-agenda-files'.
4234 These are the files which are being checked for agenda entries.
4235 Optional argument FILE means, use this file instead of the current."
4236 (interactive)
4237 (let* ((file (or file (buffer-file-name)))
4238 (true-file (file-truename file))
4239 (afile (abbreviate-file-name file))
4240 (files (delq nil (mapcar
4241 (lambda (x)
4242 (if (equal true-file
4243 (file-truename x))
4244 nil x))
4245 org-agenda-files))))
4246 (if (not (= (length files) (length org-agenda-files)))
4247 (progn
4248 (setq org-agenda-files files)
4249 (customize-save-variable 'org-agenda-files org-agenda-files)
4250 (org-install-agenda-files-menu)
4251 (message "Removed file: %s" afile))
4252 (message "File was not in list: %s" afile))))
4253
4254 (defun org-file-menu-entry (file)
4255 (vector file (list 'find-file file) t))
4256
4257 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4258 "Return a list of all relevant day numbers from BEG to END buffer positions.
4259 If NO-RANGES is non-nil, include only the start and end dates of a range,
4260 not every single day in the range. If FORCE-TODAY is non-nil, make
4261 sure that TODAY is included in the list."
4262 (let (dates date day day1 day2 ts1 ts2)
4263 (if force-today
4264 (setq dates (list (time-to-days (current-time)))))
4265 (save-excursion
4266 (goto-char beg)
4267 (while (re-search-forward org-ts-regexp end t)
4268 (setq day (time-to-days (org-time-string-to-time
4269 (substring (match-string 1) 0 10))))
4270 (or (memq day dates) (push day dates)))
4271 (unless no-ranges
4272 (goto-char beg)
4273 (while (re-search-forward org-tr-regexp end t)
4274 (setq ts1 (substring (match-string 1) 0 10)
4275 ts2 (substring (match-string 2) 0 10)
4276 day1 (time-to-days (org-time-string-to-time ts1))
4277 day2 (time-to-days (org-time-string-to-time ts2)))
4278 (while (< (setq day1 (1+ day1)) day2)
4279 (or (memq day1 dates) (push day1 dates)))))
4280 (sort dates '<))))
4281
4282 ;;;###autoload
4283 (defun org-diary (&rest args)
4284 "Return diary information from org-files.
4285 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4286 It accesses org files and extracts information from those files to be
4287 listed in the diary. The function accepts arguments specifying what
4288 items should be listed. The following arguments are allowed:
4289
4290 :timestamp List the headlines of items containing a date stamp or
4291 date range matching the selected date. Deadlines will
4292 also be listed, on the expiration day.
4293
4294 :deadline List any deadlines past due, or due within
4295 `org-deadline-warning-days'. The listing occurs only
4296 in the diary for *today*, not at any other date. If
4297 an entry is marked DONE, it is no longer listed.
4298
4299 :scheduled List all items which are scheduled for the given date.
4300 The diary for *today* also contains items which were
4301 scheduled earlier and are not yet marked DONE.
4302
4303 :todo List all TODO items from the org-file. This may be a
4304 long list - so this is not turned on by default.
4305 Like deadlines, these entries only show up in the
4306 diary for *today*, not at any other date.
4307
4308 The call in the diary file should look like this:
4309
4310 &%%(org-diary) ~/path/to/some/orgfile.org
4311
4312 Use a separate line for each org file to check. Or, if you omit the file name,
4313 all files listed in `org-agenda-files' will be checked automatically:
4314
4315 &%%(org-diary)
4316
4317 If you don't give any arguments (as in the example above), the default
4318 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4319 also be written as
4320
4321 &%%(org-diary :deadline :timestamp :scheduled)
4322
4323 The function expects the lisp variables `entry' and `date' to be provided
4324 by the caller, because this is how the calendar works. Don't use this
4325 function from a program - use `org-agenda-get-day-entries' instead."
4326 (org-agenda-maybe-reset-markers)
4327 (org-compile-prefix-format org-agenda-prefix-format)
4328 (setq args (or args '(:deadline :scheduled :timestamp)))
4329 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4330 (list entry)
4331 org-agenda-files))
4332 file rtn results)
4333 ;; If this is called during org-agenda, don't return any entries to
4334 ;; the calendar. Org Agenda will list these entries itself.
4335 (if org-disable-agenda-to-diary (setq files nil))
4336 (while (setq file (pop files))
4337 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4338 (setq results (append results rtn)))
4339 (if results
4340 (concat (org-finalize-agenda-entries results) "\n"))))
4341
4342 (defun org-agenda-get-day-entries (file date &rest args)
4343 "Does the work for `org-diary' and `org-agenda'.
4344 FILE is the path to a file to be checked for entries. DATE is date like
4345 the one returned by `calendar-current-date'. ARGS are symbols indicating
4346 which kind of entries should be extracted. For details about these, see
4347 the documentation of `org-diary'."
4348 (setq args (or args '(:deadline :scheduled :timestamp)))
4349 (let* ((org-startup-with-deadline-check nil)
4350 (org-startup-folded nil)
4351 (buffer (if (file-exists-p file)
4352 (org-get-agenda-file-buffer file)
4353 (error "No such file %s" file)))
4354 arg results rtn)
4355 (if (not buffer)
4356 ;; If file does not exist, make sure an error message ends up in diary
4357 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4358 (with-current-buffer buffer
4359 (unless (eq major-mode 'org-mode)
4360 (error "Agenda file %s is not in `org-mode'" file))
4361 (let ((case-fold-search nil))
4362 (save-excursion
4363 (save-restriction
4364 (if org-respect-restriction
4365 (if (org-region-active-p)
4366 ;; Respect a region to restrict search
4367 (narrow-to-region (region-beginning) (region-end)))
4368 ;; If we work for the calendar or many files,
4369 ;; get rid of any restriction
4370 (widen))
4371 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4372 (while (setq arg (pop args))
4373 (cond
4374 ((and (eq arg :todo)
4375 (equal date (calendar-current-date)))
4376 (setq rtn (org-agenda-get-todos))
4377 (setq results (append results rtn)))
4378 ((eq arg :timestamp)
4379 (setq rtn (org-agenda-get-blocks))
4380 (setq results (append results rtn))
4381 (setq rtn (org-agenda-get-timestamps))
4382 (setq results (append results rtn)))
4383 ((eq arg :scheduled)
4384 (setq rtn (org-agenda-get-scheduled))
4385 (setq results (append results rtn)))
4386 ((and (eq arg :deadline)
4387 (equal date (calendar-current-date)))
4388 (setq rtn (org-agenda-get-deadlines))
4389 (setq results (append results rtn))))))))
4390 results))))
4391
4392 (defun org-entry-is-done-p ()
4393 "Is the current entry marked DONE?"
4394 (save-excursion
4395 (and (re-search-backward "[\r\n]\\*" nil t)
4396 (looking-at org-nl-done-regexp))))
4397
4398 (defun org-at-date-range-p ()
4399 "Is the cursor inside a date range?"
4400 (interactive)
4401 (save-excursion
4402 (catch 'exit
4403 (let ((pos (point)))
4404 (skip-chars-backward "^<\r\n")
4405 (skip-chars-backward "<")
4406 (and (looking-at org-tr-regexp)
4407 (>= (match-end 0) pos)
4408 (throw 'exit t))
4409 (skip-chars-backward "^<\r\n")
4410 (skip-chars-backward "<")
4411 (and (looking-at org-tr-regexp)
4412 (>= (match-end 0) pos)
4413 (throw 'exit t)))
4414 nil)))
4415
4416 (defun org-agenda-get-todos ()
4417 "Return the TODO information for agenda display."
4418 (let* ((props (list 'face nil
4419 'done-face 'org-done
4420 'mouse-face 'highlight
4421 'keymap org-agenda-keymap
4422 'help-echo
4423 (format "mouse-2 or RET jump to org file %s"
4424 (abbreviate-file-name (buffer-file-name)))))
4425 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4426 "[^\n\r]*\\)"))
4427 marker priority
4428 ee txt)
4429 (goto-char (point-min))
4430 (while (re-search-forward regexp nil t)
4431 (goto-char (match-beginning 1))
4432 (setq marker (org-agenda-new-marker (point-at-bol))
4433 txt (org-format-agenda-item "" (match-string 1))
4434 priority
4435 (+ (org-get-priority txt)
4436 (if org-todo-kwd-priority-p
4437 (- org-todo-kwd-max-priority -2
4438 (length
4439 (member (match-string 2) org-todo-keywords)))
4440 1)))
4441 (add-text-properties
4442 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4443 'priority priority)
4444 props)
4445 txt)
4446 (push txt ee)
4447 (goto-char (match-end 1)))
4448 (nreverse ee)))
4449
4450 (defconst org-agenda-no-heading-message
4451 "No heading for this item in buffer or region")
4452
4453 (defun org-agenda-get-timestamps ()
4454 "Return the date stamp information for agenda display."
4455 (let* ((props (list 'face nil
4456 'mouse-face 'highlight
4457 'keymap org-agenda-keymap
4458 'help-echo
4459 (format "mouse-2 or RET jump to org file %s"
4460 (abbreviate-file-name (buffer-file-name)))))
4461 (regexp (regexp-quote
4462 (substring
4463 (format-time-string
4464 (car org-time-stamp-formats)
4465 (apply 'encode-time ; DATE bound by calendar
4466 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4467 0 11)))
4468 marker hdmarker deadlinep scheduledp donep tmp priority
4469 ee txt timestr)
4470 (goto-char (point-min))
4471 (while (re-search-forward regexp nil t)
4472 (if (not (save-match-data (org-at-date-range-p)))
4473 (progn
4474 (setq marker (org-agenda-new-marker (match-beginning 0))
4475 tmp (buffer-substring (max (point-min)
4476 (- (match-beginning 0)
4477 org-ds-keyword-length))
4478 (match-beginning 0))
4479 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4480 deadlinep (string-match org-deadline-regexp tmp)
4481 scheduledp (string-match org-scheduled-regexp tmp)
4482 donep (org-entry-is-done-p))
4483 (if (string-match ">" timestr)
4484 ;; substring should only run to end of time stamp
4485 (setq timestr (substring timestr 0 (match-end 0))))
4486 (save-excursion
4487 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4488 (progn
4489 (goto-char (match-end 1))
4490 (setq hdmarker (org-agenda-new-marker))
4491 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4492 (setq txt (org-format-agenda-item
4493 (format "%s%s"
4494 (if deadlinep "Deadline: " "")
4495 (if scheduledp "Scheduled: " ""))
4496 (match-string 1) nil timestr)))
4497 (setq txt org-agenda-no-heading-message))
4498 (setq priority (org-get-priority txt))
4499 (add-text-properties
4500 0 (length txt) (append (list 'org-marker marker
4501 'org-hd-marker hdmarker) props)
4502 txt)
4503 (if deadlinep
4504 (add-text-properties
4505 0 (length txt)
4506 (list 'face
4507 (if donep 'org-done 'org-warning)
4508 'undone-face 'org-warning
4509 'done-face 'org-done
4510 'priority (+ 100 priority))
4511 txt)
4512 (if scheduledp
4513 (add-text-properties
4514 0 (length txt)
4515 (list 'face 'org-scheduled-today
4516 'undone-face 'org-scheduled-today
4517 'done-face 'org-done
4518 priority (+ 99 priority))
4519 txt)
4520 (add-text-properties
4521 0 (length txt)
4522 (list 'priority priority) txt)))
4523 (push txt ee))
4524 (outline-next-heading))))
4525 (nreverse ee)))
4526
4527 (defun org-agenda-get-deadlines ()
4528 "Return the deadline information for agenda display."
4529 (let* ((wdays org-deadline-warning-days)
4530 (props (list 'mouse-face 'highlight
4531 'keymap org-agenda-keymap
4532 'help-echo
4533 (format "mouse-2 or RET jump to org file %s"
4534 (abbreviate-file-name (buffer-file-name)))))
4535 (regexp org-deadline-time-regexp)
4536 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4537 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4538 d2 diff pos pos1
4539 ee txt head)
4540 (goto-char (point-min))
4541 (while (re-search-forward regexp nil t)
4542 (setq pos (1- (match-beginning 1))
4543 d2 (time-to-days
4544 (org-time-string-to-time (match-string 1)))
4545 diff (- d2 d1))
4546 ;; When to show a deadline in the calendar:
4547 ;; If the expiration is within wdays warning time.
4548 ;; Past-due deadlines are only shown on the current date
4549 (if (and (< diff wdays) todayp (not (= diff 0)))
4550 (save-excursion
4551 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4552 (progn
4553 (goto-char (match-end 0))
4554 (setq pos1 (match-end 1))
4555 (setq head (buffer-substring-no-properties
4556 (point)
4557 (progn (skip-chars-forward "^\r\n")
4558 (point))))
4559 (if (string-match org-looking-at-done-regexp head)
4560 (setq txt nil)
4561 (setq txt (org-format-agenda-item
4562 (format "In %3d d.: " diff) head))))
4563 (setq txt org-agenda-no-heading-message))
4564 (when txt
4565 (add-text-properties
4566 0 (length txt)
4567 (append
4568 (list 'org-marker (org-agenda-new-marker pos)
4569 'org-hd-marker (org-agenda-new-marker pos1)
4570 'priority (+ (- 10 diff) (org-get-priority txt))
4571 'face (cond ((<= diff 0) 'org-warning)
4572 ((<= diff 5) 'org-scheduled-previously)
4573 (t nil))
4574 'undone-face (cond
4575 ((<= diff 0) 'org-warning)
4576 ((<= diff 5) 'org-scheduled-previously)
4577 (t nil))
4578 'done-face 'org-done)
4579 props)
4580 txt)
4581 (push txt ee)))))
4582 ee))
4583
4584 (defun org-agenda-get-scheduled ()
4585 "Return the scheduled information for agenda display."
4586 (let* ((props (list 'face 'org-scheduled-previously
4587 'undone-face 'org-scheduled-previously
4588 'done-face 'org-done
4589 'mouse-face 'highlight
4590 'keymap org-agenda-keymap
4591 'help-echo
4592 (format "mouse-2 or RET jump to org file %s"
4593 (abbreviate-file-name (buffer-file-name)))))
4594 (regexp org-scheduled-time-regexp)
4595 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4596 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4597 d2 diff pos pos1
4598 ee txt head)
4599 (goto-char (point-min))
4600 (while (re-search-forward regexp nil t)
4601 (setq pos (1- (match-beginning 1))
4602 d2 (time-to-days
4603 (org-time-string-to-time (match-string 1)))
4604 diff (- d2 d1))
4605 ;; When to show a scheduled item in the calendar:
4606 ;; If it is on or past the date.
4607 (if (and (< diff 0) todayp)
4608 (save-excursion
4609 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4610 (progn
4611 (goto-char (match-end 0))
4612 (setq pos1 (match-end 1))
4613 (setq head (buffer-substring-no-properties
4614 (point)
4615 (progn (skip-chars-forward "^\r\n") (point))))
4616 (if (string-match org-looking-at-done-regexp head)
4617 (setq txt nil)
4618 (setq txt (org-format-agenda-item
4619 (format "Sched.%2dx: " (- 1 diff)) head))))
4620 (setq txt org-agenda-no-heading-message))
4621 (when txt
4622 (add-text-properties
4623 0 (length txt)
4624 (append (list 'org-marker (org-agenda-new-marker pos)
4625 'org-hd-marker (org-agenda-new-marker pos1)
4626 'priority (+ (- 5 diff) (org-get-priority txt)))
4627 props) txt)
4628 (push txt ee)))))
4629 ee))
4630
4631 (defun org-agenda-get-blocks ()
4632 "Return the date-range information for agenda display."
4633 (let* ((props (list 'face nil
4634 'mouse-face 'highlight
4635 'keymap org-agenda-keymap
4636 'help-echo
4637 (format "mouse-2 or RET jump to org file %s"
4638 (abbreviate-file-name (buffer-file-name)))))
4639 (regexp org-tr-regexp)
4640 (d0 (calendar-absolute-from-gregorian date))
4641 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4642 (goto-char (point-min))
4643 (while (re-search-forward regexp nil t)
4644 (setq timestr (match-string 0)
4645 s1 (match-string 1)
4646 s2 (match-string 2)
4647 d1 (time-to-days (org-time-string-to-time s1))
4648 d2 (time-to-days (org-time-string-to-time s2)))
4649 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4650 ;; Only allow days between the limits, because the normal
4651 ;; date stamps will catch the limits.
4652 (save-excursion
4653 (setq marker (org-agenda-new-marker (point)))
4654 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4655 (progn
4656 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4657 (goto-char (match-end 1))
4658 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4659 (setq txt (org-format-agenda-item
4660 (format (if (= d1 d2) "" "(%d/%d): ")
4661 (1+ (- d0 d1)) (1+ (- d2 d1)))
4662 (match-string 1) nil (if (= d0 d1) timestr))))
4663 (setq txt org-agenda-no-heading-message))
4664 (add-text-properties
4665 0 (length txt) (append (list 'org-marker marker
4666 'org-hd-marker hdmarker
4667 'priority (org-get-priority txt))
4668 props)
4669 txt)
4670 (push txt ee)))
4671 (outline-next-heading))
4672 ;; Sort the entries by expiration date.
4673 (nreverse ee)))
4674
4675
4676
4677 (defconst org-plain-time-of-day-regexp
4678 (concat
4679 "\\(\\<[012]?[0-9]"
4680 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4681 "\\(--?"
4682 "\\(\\<[012]?[0-9]"
4683 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4684 "\\)?")
4685 "Regular expression to match a plain time or time range.
4686 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4687 groups carry important information:
4688 0 the full match
4689 1 the first time, range or not
4690 8 the second time, if it is a range.")
4691
4692 (defconst org-stamp-time-of-day-regexp
4693 (concat
4694 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4695 "\\([012][0-9]:[0-5][0-9]\\)>"
4696 "\\(--?"
4697 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4698 "Regular expression to match a timestamp time or time range.
4699 After a match, the following groups carry important information:
4700 0 the full match
4701 1 date plus weekday, for backreferencing to make sure both times on same day
4702 2 the first time, range or not
4703 4 the second time, if it is a range.")
4704
4705 (defvar org-prefix-has-time nil
4706 "A flag, set by `org-compile-prefix-format'.
4707 The flag is set if the currently compiled format contains a `%t'.")
4708
4709 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4710 "Format TXT to be inserted into the agenda buffer.
4711 In particular, it adds the prefix and corresponding text properties. EXTRA
4712 must be a string and replaces the `%s' specifier in the prefix format.
4713 CATEGORY (string, symbol or nil) may be used to overule the default
4714 category taken from local variable or file name. It will replace the `%c'
4715 specifier in the format. DOTIME, when non-nil, indicates that a
4716 time-of-day should be extracted from TXT for sorting of this entry, and for
4717 the `%t' specifier in the format. When DOTIME is a string, this string is
4718 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4719 only the correctly processes TXT should be returned - this is used by
4720 `org-agenda-change-all-lines'."
4721 (save-match-data
4722 ;; Diary entries sometimes have extra whitespace at the beginning
4723 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4724 (let* ((category (or category
4725 org-category
4726 (if (buffer-file-name)
4727 (file-name-sans-extension
4728 (file-name-nondirectory (buffer-file-name)))
4729 "")))
4730 time ;; needed for the eval of the prefix format
4731 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4732 (time-of-day (and dotime (org-get-time-of-day ts)))
4733 stamp plain s0 s1 s2 rtn)
4734 (when (and dotime time-of-day org-prefix-has-time)
4735 ;; Extract starting and ending time and move them to prefix
4736 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4737 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4738 (setq s0 (match-string 0 ts)
4739 s1 (match-string (if plain 1 2) ts)
4740 s2 (match-string (if plain 8 4) ts))
4741
4742 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4743 ;; them, we might want to remove them there to avoid duplication.
4744 ;; The user can turn this off with a variable.
4745 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4746 (string-match (concat (regexp-quote s0) " *") txt)
4747 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4748 (= (match-beginning 0) 0)
4749 t))
4750 (setq txt (replace-match "" nil nil txt))))
4751 ;; Normalize the time(s) to 24 hour
4752 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4753 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4754
4755 ;; Create the final string
4756 (if noprefix
4757 (setq rtn txt)
4758 ;; Prepare the variables needed in the eval of the compiled format
4759 (setq time (cond (s2 (concat s1 "-" s2))
4760 (s1 (concat s1 "......"))
4761 (t ""))
4762 extra (or extra "")
4763 category (if (symbolp category) (symbol-name category) category))
4764 ;; Evaluate the compiled format
4765 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4766
4767 ;; And finally add the text properties
4768 (add-text-properties
4769 0 (length rtn) (list 'category (downcase category)
4770 'prefix-length (- (length rtn) (length txt))
4771 'time-of-day time-of-day
4772 'dotime dotime)
4773 rtn)
4774 rtn)))
4775
4776 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4777 (catch 'exit
4778 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4779 ((and todayp (member 'today (car org-agenda-time-grid))))
4780 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4781 ((member 'weekly (car org-agenda-time-grid)))
4782 (t (throw 'exit list)))
4783 (let* ((have (delq nil (mapcar
4784 (lambda (x) (get-text-property 1 'time-of-day x))
4785 list)))
4786 (string (nth 1 org-agenda-time-grid))
4787 (gridtimes (nth 2 org-agenda-time-grid))
4788 (req (car org-agenda-time-grid))
4789 (remove (member 'remove-match req))
4790 new time)
4791 (if (and (member 'require-timed req) (not have))
4792 ;; don't show empty grid
4793 (throw 'exit list))
4794 (while (setq time (pop gridtimes))
4795 (unless (and remove (member time have))
4796 (setq time (int-to-string time))
4797 (push (org-format-agenda-item
4798 nil string "" ;; FIXME: put a category?
4799 (concat (substring time 0 -2) ":" (substring time -2)))
4800 new)
4801 (put-text-property
4802 1 (length (car new)) 'face 'org-time-grid (car new))))
4803 (if (member 'time-up org-agenda-sorting-strategy)
4804 (append new list)
4805 (append list new)))))
4806
4807 (defun org-compile-prefix-format (format)
4808 "Compile the prefix format into a Lisp form that can be evaluated.
4809 The resulting form is returned and stored in the variable
4810 `org-prefix-format-compiled'."
4811 (setq org-prefix-has-time nil)
4812 (let ((start 0) varform vars var (s format) c f opt)
4813 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4814 s start)
4815 (setq var (cdr (assoc (match-string 4 s)
4816 '(("c" . category) ("t" . time) ("s" . extra))))
4817 c (or (match-string 3 s) "")
4818 opt (match-beginning 1)
4819 start (1+ (match-beginning 0)))
4820 (if (equal var 'time) (setq org-prefix-has-time t))
4821 (setq f (concat "%" (match-string 2 s) "s"))
4822 (if opt
4823 (setq varform
4824 `(if (equal "" ,var)
4825 ""
4826 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4827 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4828 (setq s (replace-match "%s" t nil s))
4829 (push varform vars))
4830 (setq vars (nreverse vars))
4831 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4832
4833 (defun org-get-time-of-day (s &optional string)
4834 "Check string S for a time of day.
4835 If found, return it as a military time number between 0 and 2400.
4836 If not found, return nil.
4837 The optional STRING argument forces conversion into a 5 character wide string
4838 HH:MM."
4839 (save-match-data
4840 (when
4841 (or
4842 (string-match
4843 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4844 (string-match
4845 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4846 (let* ((t0 (+ (* 100
4847 (+ (string-to-number (match-string 1 s))
4848 (if (and (match-beginning 4)
4849 (equal (downcase (match-string 4 s)) "pm"))
4850 12 0)))
4851 (if (match-beginning 3)
4852 (string-to-number (match-string 3 s))
4853 0)))
4854 (t1 (concat " " (int-to-string t0))))
4855 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4856
4857 (defun org-finalize-agenda-entries (list)
4858 "Sort and concatenate the agenda items."
4859 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4860
4861 (defsubst org-cmp-priority (a b)
4862 "Compare the priorities of string a and b."
4863 (let ((pa (or (get-text-property 1 'priority a) 0))
4864 (pb (or (get-text-property 1 'priority b) 0)))
4865 (cond ((> pa pb) +1)
4866 ((< pa pb) -1)
4867 (t nil))))
4868
4869 (defsubst org-cmp-category (a b)
4870 "Compare the string values of categories of strings a and b."
4871 (let ((ca (or (get-text-property 1 'category a) ""))
4872 (cb (or (get-text-property 1 'category b) "")))
4873 (cond ((string-lessp ca cb) -1)
4874 ((string-lessp cb ca) +1)
4875 (t nil))))
4876
4877 (defsubst org-cmp-time (a b)
4878 "Compare the time-of-day values of strings a and b."
4879 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4880 (ta (or (get-text-property 1 'time-of-day a) def))
4881 (tb (or (get-text-property 1 'time-of-day b) def)))
4882 (cond ((< ta tb) -1)
4883 ((< tb ta) +1)
4884 (t nil))))
4885
4886 (defun org-entries-lessp (a b)
4887 "Predicate for sorting agenda entries."
4888 ;; The following variables will be used when the form is evaluated.
4889 (let* ((time-up (org-cmp-time a b))
4890 (time-down (if time-up (- time-up) nil))
4891 (priority-up (org-cmp-priority a b))
4892 (priority-down (if priority-up (- priority-up) nil))
4893 (category-up (org-cmp-category a b))
4894 (category-down (if category-up (- category-up) nil))
4895 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4896 (cdr (assoc
4897 (eval (cons 'or org-agenda-sorting-strategy))
4898 '((-1 . t) (1 . nil) (nil . nil))))))
4899
4900 (defun org-agenda-show-priority ()
4901 "Show the priority of the current item.
4902 This priority is composed of the main priority given with the [#A] cookies,
4903 and by additional input from the age of a schedules or deadline entry."
4904 (interactive)
4905 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4906 (message "Priority is %d" (if pri pri -1000))))
4907
4908 (defun org-agenda-goto (&optional highlight)
4909 "Go to the Org-mode file which contains the item at point."
4910 (interactive)
4911 (let* ((marker (or (get-text-property (point) 'org-marker)
4912 (org-agenda-error)))
4913 (buffer (marker-buffer marker))
4914 (pos (marker-position marker)))
4915 (switch-to-buffer-other-window buffer)
4916 (widen)
4917 (goto-char pos)
4918 (when (eq major-mode 'org-mode)
4919 (org-show-hidden-entry)
4920 (save-excursion
4921 (and (outline-next-heading)
4922 (org-flag-heading nil)))) ; show the next heading
4923 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4924
4925 (defun org-agenda-switch-to ()
4926 "Go to the Org-mode file which contains the item at point."
4927 (interactive)
4928 (let* ((marker (or (get-text-property (point) 'org-marker)
4929 (org-agenda-error)))
4930 (buffer (marker-buffer marker))
4931 (pos (marker-position marker)))
4932 (switch-to-buffer buffer)
4933 (delete-other-windows)
4934 (widen)
4935 (goto-char pos)
4936 (when (eq major-mode 'org-mode)
4937 (org-show-hidden-entry)
4938 (save-excursion
4939 (and (outline-next-heading)
4940 (org-flag-heading nil)))))) ; show the next heading
4941
4942 (defun org-agenda-goto-mouse (ev)
4943 "Go to the Org-mode file which contains the item at the mouse click."
4944 (interactive "e")
4945 (mouse-set-point ev)
4946 (org-agenda-goto))
4947
4948 (defun org-agenda-show ()
4949 "Display the Org-mode file which contains the item at point."
4950 (interactive)
4951 (let ((win (selected-window)))
4952 (org-agenda-goto t)
4953 (select-window win)))
4954
4955 (defun org-agenda-recenter (arg)
4956 "Display the Org-mode file which contains the item at point and recenter."
4957 (interactive "P")
4958 (let ((win (selected-window)))
4959 (org-agenda-goto t)
4960 (recenter arg)
4961 (select-window win)))
4962
4963 (defun org-agenda-show-mouse (ev)
4964 "Display the Org-mode file which contains the item at the mouse click."
4965 (interactive "e")
4966 (mouse-set-point ev)
4967 (org-agenda-show))
4968
4969 (defun org-agenda-check-no-diary ()
4970 "Check if the entry is a diary link and abort if yes."
4971 (if (get-text-property (point) 'org-agenda-diary-link)
4972 (org-agenda-error)))
4973
4974 (defun org-agenda-error ()
4975 (error "Command not allowed in this line"))
4976
4977 (defvar org-last-heading-marker (make-marker)
4978 "Marker pointing to the headline that last changed its TODO state
4979 by a remote command from the agenda.")
4980
4981 (defun org-agenda-todo ()
4982 "Cycle TODO state of line at point, also in Org-mode file.
4983 This changes the line at point, all other lines in the agenda referring to
4984 the same tree node, and the headline of the tree node in the Org-mode file."
4985 (interactive)
4986 (org-agenda-check-no-diary)
4987 (let* ((col (current-column))
4988 (marker (or (get-text-property (point) 'org-marker)
4989 (org-agenda-error)))
4990 (buffer (marker-buffer marker))
4991 (pos (marker-position marker))
4992 (hdmarker (get-text-property (point) 'org-hd-marker))
4993 (buffer-read-only nil)
4994 newhead)
4995 (with-current-buffer buffer
4996 (widen)
4997 (goto-char pos)
4998 (org-show-hidden-entry)
4999 (save-excursion
5000 (and (outline-next-heading)
5001 (org-flag-heading nil))) ; show the next heading
5002 (org-todo)
5003 (forward-char 1)
5004 (setq newhead (org-get-heading))
5005 (save-excursion
5006 (org-back-to-heading)
5007 (move-marker org-last-heading-marker (point))))
5008 (beginning-of-line 1)
5009 (save-excursion
5010 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5011 (move-to-column col)))
5012
5013 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5014 "Change all lines in the agenda buffer which match hdmarker.
5015 The new content of the line will be NEWHEAD (as modified by
5016 `org-format-agenda-item'). HDMARKER is checked with
5017 `equal' against all `org-hd-marker' text properties in the file.
5018 If FIXFACE is non-nil, the face of each item is modified acording to
5019 the new TODO state."
5020 (let* (props m pl undone-face done-face finish new dotime)
5021 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5022 (save-excursion
5023 (goto-char (point-max))
5024 (beginning-of-line 1)
5025 (while (not finish)
5026 (setq finish (bobp))
5027 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5028 (equal m hdmarker))
5029 (setq props (text-properties-at (point))
5030 dotime (get-text-property (point) 'dotime)
5031 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
5032 pl (get-text-property (point) 'prefix-length)
5033 undone-face (get-text-property (point) 'undone-face)
5034 done-face (get-text-property (point) 'done-face))
5035 (move-to-column pl)
5036 (if (looking-at ".*")
5037 (progn
5038 (replace-match new t t)
5039 (beginning-of-line 1)
5040 (add-text-properties (point-at-bol) (point-at-eol) props)
5041 (if fixface
5042 (add-text-properties
5043 (point-at-bol) (point-at-eol)
5044 (list 'face
5045 (if org-last-todo-state-is-todo
5046 undone-face done-face))))
5047 (beginning-of-line 1))
5048 (error "Line update did not work")))
5049 (beginning-of-line 0)))))
5050
5051 (defun org-agenda-priority-up ()
5052 "Increase the priority of line at point, also in Org-mode file."
5053 (interactive)
5054 (org-agenda-priority 'up))
5055
5056 (defun org-agenda-priority-down ()
5057 "Decrease the priority of line at point, also in Org-mode file."
5058 (interactive)
5059 (org-agenda-priority 'down))
5060
5061 (defun org-agenda-priority (&optional force-direction)
5062 "Set the priority of line at point, also in Org-mode file.
5063 This changes the line at point, all other lines in the agenda referring to
5064 the same tree node, and the headline of the tree node in the Org-mode file."
5065 (interactive)
5066 (org-agenda-check-no-diary)
5067 (let* ((marker (or (get-text-property (point) 'org-marker)
5068 (org-agenda-error)))
5069 (buffer (marker-buffer marker))
5070 (pos (marker-position marker))
5071 (hdmarker (get-text-property (point) 'org-hd-marker))
5072 (buffer-read-only nil)
5073 newhead)
5074 (with-current-buffer buffer
5075 (widen)
5076 (goto-char pos)
5077 (org-show-hidden-entry)
5078 (save-excursion
5079 (and (outline-next-heading)
5080 (org-flag-heading nil))) ; show the next heading
5081 (funcall 'org-priority force-direction)
5082 (end-of-line 1)
5083 (setq newhead (org-get-heading)))
5084 (org-agenda-change-all-lines newhead hdmarker)
5085 (beginning-of-line 1)))
5086
5087 (defun org-agenda-date-later (arg &optional what)
5088 "Change the date of this item to one day later."
5089 (interactive "p")
5090 (org-agenda-check-no-diary)
5091 (let* ((marker (or (get-text-property (point) 'org-marker)
5092 (org-agenda-error)))
5093 (buffer (marker-buffer marker))
5094 (pos (marker-position marker)))
5095 (with-current-buffer buffer
5096 (widen)
5097 (goto-char pos)
5098 (if (not (org-at-timestamp-p))
5099 (error "Cannot find time stamp"))
5100 (org-timestamp-change arg (or what 'day))
5101 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5102
5103 (defun org-agenda-date-earlier (arg &optional what)
5104 "Change the date of this item to one day earlier."
5105 (interactive "p")
5106 (org-agenda-date-later (- arg) what))
5107
5108 (defun org-agenda-date-prompt (arg)
5109 "Change the date of this item. Date is prompted for, with default today.
5110 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5111 be used to request time specification in the time stamp."
5112 (interactive "P")
5113 (org-agenda-check-no-diary)
5114 (let* ((marker (or (get-text-property (point) 'org-marker)
5115 (org-agenda-error)))
5116 (buffer (marker-buffer marker))
5117 (pos (marker-position marker)))
5118 (with-current-buffer buffer
5119 (widen)
5120 (goto-char pos)
5121 (if (not (org-at-timestamp-p))
5122 (error "Cannot find time stamp"))
5123 (org-time-stamp arg)
5124 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5125
5126 (defun org-get-heading ()
5127 "Return the heading of the current entry, without the stars."
5128 (save-excursion
5129 (if (and (re-search-backward "[\r\n]\\*" nil t)
5130 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5131 (match-string 1)
5132 "")))
5133
5134 (defun org-agenda-diary-entry ()
5135 "Make a diary entry, like the `i' command from the calendar.
5136 All the standard commands work: block, weekly etc"
5137 (interactive)
5138 (require 'diary-lib)
5139 (let* ((char (progn
5140 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5141 (read-char-exclusive)))
5142 (cmd (cdr (assoc char
5143 '((?d . insert-diary-entry)
5144 (?w . insert-weekly-diary-entry)
5145 (?m . insert-monthly-diary-entry)
5146 (?y . insert-yearly-diary-entry)
5147 (?a . insert-anniversary-diary-entry)
5148 (?b . insert-block-diary-entry)
5149 (?c . insert-cyclic-diary-entry)))))
5150 (oldf (symbol-function 'calendar-cursor-to-date))
5151 (point (point))
5152 (mark (or (mark t) (point))))
5153 (unless cmd
5154 (error "No command associated with <%c>" char))
5155 (unless (and (get-text-property point 'day)
5156 (or (not (equal ?b char))
5157 (get-text-property mark 'day)))
5158 (error "Don't know which date to use for diary entry"))
5159 ;; We implement this by hacking the `calendar-cursor-to-date' function
5160 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5161 (let ((calendar-mark-ring
5162 (list (calendar-gregorian-from-absolute
5163 (or (get-text-property mark 'day)
5164 (get-text-property point 'day))))))
5165 (unwind-protect
5166 (progn
5167 (fset 'calendar-cursor-to-date
5168 (lambda (&optional error)
5169 (calendar-gregorian-from-absolute
5170 (get-text-property point 'day))))
5171 (call-interactively cmd))
5172 (fset 'calendar-cursor-to-date oldf)))))
5173
5174
5175 (defun org-agenda-execute-calendar-command (cmd)
5176 "Execute a calendar command from the agenda, with the date associated to
5177 the cursor position."
5178 (require 'diary-lib)
5179 (unless (get-text-property (point) 'day)
5180 (error "Don't know which date to use for calendar command"))
5181 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5182 (point (point))
5183 (date (calendar-gregorian-from-absolute
5184 (get-text-property point 'day)))
5185 (displayed-day (extract-calendar-day date))
5186 (displayed-month (extract-calendar-month date))
5187 (displayed-year (extract-calendar-year date)))
5188 (unwind-protect
5189 (progn
5190 (fset 'calendar-cursor-to-date
5191 (lambda (&optional error)
5192 (calendar-gregorian-from-absolute
5193 (get-text-property point 'day))))
5194 (call-interactively cmd))
5195 (fset 'calendar-cursor-to-date oldf))))
5196
5197 (defun org-agenda-phases-of-moon ()
5198 "Display the phases of the moon for the 3 months around the cursor date."
5199 (interactive)
5200 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5201
5202 (defun org-agenda-holidays ()
5203 "Display the holidays for the 3 months around the cursor date."
5204 (interactive)
5205 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5206
5207 (defun org-agenda-sunrise-sunset (arg)
5208 "Display sunrise and sunset for the cursor date.
5209 Latitude and longitude can be specified with the variables
5210 `calendar-latitude' and `calendar-longitude'. When called with prefix
5211 argument, latitude and longitude will be prompted for."
5212 (interactive "P")
5213 (let ((calendar-longitude (if arg nil calendar-longitude))
5214 (calendar-latitude (if arg nil calendar-latitude))
5215 (calendar-location-name
5216 (if arg "the given coordinates" calendar-location-name)))
5217 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5218
5219 (defun org-agenda-goto-calendar ()
5220 "Open the Emacs calendar with the date at the cursor."
5221 (interactive)
5222 (let* ((day (or (get-text-property (point) 'day)
5223 (error "Don't know which date to open in calendar")))
5224 (date (calendar-gregorian-from-absolute day)))
5225 (calendar)
5226 (calendar-goto-date date)))
5227
5228 (defun org-calendar-goto-agenda ()
5229 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5230 This is a command that has to be installed in `calendar-mode-map'."
5231 (interactive)
5232 (org-agenda nil (calendar-absolute-from-gregorian
5233 (calendar-cursor-to-date))))
5234
5235 (defun org-agenda-convert-date ()
5236 (interactive)
5237 (let ((day (get-text-property (point) 'day))
5238 date s)
5239 (unless day
5240 (error "Don't know which date to convert"))
5241 (setq date (calendar-gregorian-from-absolute day))
5242 (setq s (concat
5243 "Gregorian: " (calendar-date-string date) "\n"
5244 "ISO: " (calendar-iso-date-string date) "\n"
5245 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5246 "Julian: " (calendar-julian-date-string date) "\n"
5247 "Astron. JD: " (calendar-astro-date-string date)
5248 " (Julian date number at noon UTC)\n"
5249 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5250 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5251 "French: " (calendar-french-date-string date) "\n"
5252 "Mayan: " (calendar-mayan-date-string date) "\n"
5253 "Coptic: " (calendar-coptic-date-string date) "\n"
5254 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5255 "Persian: " (calendar-persian-date-string date) "\n"
5256 "Chinese: " (calendar-chinese-date-string date) "\n"))
5257 (with-output-to-temp-buffer "*Dates*"
5258 (princ s))
5259 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5260
5261 ;;; Link Stuff
5262
5263 (defun org-find-file-at-mouse (ev)
5264 "Open file link or URL at mouse."
5265 (interactive "e")
5266 (mouse-set-point ev)
5267 (org-open-at-point 'in-emacs))
5268
5269 (defun org-open-at-mouse (ev)
5270 "Open file link or URL at mouse."
5271 (interactive "e")
5272 (mouse-set-point ev)
5273 (org-open-at-point))
5274
5275 (defun org-open-at-point (&optional in-emacs)
5276 "Open link at or after point.
5277 If there is no link at point, this function will search forward up to
5278 the end of the current subtree.
5279 Normally, files will be opened by an appropriate application. If the
5280 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5281 (interactive "P")
5282 (if (org-at-timestamp-p)
5283 (org-agenda nil (time-to-days (org-time-string-to-time
5284 (substring (match-string 1) 0 10)))
5285 1)
5286 (let (type path line (pos (point)))
5287 (save-excursion
5288 (skip-chars-backward
5289 (concat (if org-allow-space-in-links "^" "^ ")
5290 org-non-link-chars))
5291 (if (re-search-forward
5292 org-link-regexp
5293 (save-excursion
5294 (condition-case nil
5295 (progn (outline-end-of-subtree) (max pos (point)))
5296 (error (end-of-line 1) (point))))
5297 t)
5298 (setq type (match-string 1)
5299 path (match-string 2)))
5300 (unless path
5301 (error "No link found"))
5302 ;; Remove any trailing spaces in path
5303 (if (string-match " +\\'" path)
5304 (setq path (replace-match "" t t path)))
5305
5306 (cond
5307
5308 ((string= type "file")
5309 (if (string-match ":\\([0-9]+\\)\\'" path)
5310 (setq line (string-to-number (match-string 1 path))
5311 path (substring path 0 (match-beginning 0))))
5312 (org-open-file path in-emacs line))
5313
5314 ((string= type "news")
5315 (org-follow-gnus-link path))
5316
5317 ((string= type "bbdb")
5318 (org-follow-bbdb-link path))
5319
5320 ((string= type "gnus")
5321 (let (group article)
5322 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5323 (error "Error in Gnus link"))
5324 (setq group (match-string 1 path)
5325 article (match-string 3 path))
5326 (org-follow-gnus-link group article)))
5327
5328 ((string= type "vm")
5329 (let (folder article)
5330 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5331 (error "Error in VM link"))
5332 (setq folder (match-string 1 path)
5333 article (match-string 3 path))
5334 ;; in-emacs is the prefix arg, will be interpreted as read-only
5335 (org-follow-vm-link folder article in-emacs)))
5336
5337 ((string= type "wl")
5338 (let (folder article)
5339 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5340 (error "Error in Wanderlust link"))
5341 (setq folder (match-string 1 path)
5342 article (match-string 3 path))
5343 (org-follow-wl-link folder article)))
5344
5345 ((string= type "rmail")
5346 (let (folder article)
5347 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5348 (error "Error in RMAIL link"))
5349 (setq folder (match-string 1 path)
5350 article (match-string 3 path))
5351 (org-follow-rmail-link folder article)))
5352
5353 ((string= type "shell")
5354 (let ((cmd path))
5355 (while (string-match "@{" cmd)
5356 (setq cmd (replace-match "<" t t cmd)))
5357 (while (string-match "@}" cmd)
5358 (setq cmd (replace-match ">" t t cmd)))
5359 (if (or (not org-confirm-shell-links)
5360 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5361 (shell-command cmd)
5362 (error "Abort"))))
5363
5364 (t
5365 (browse-url-at-point)))))))
5366
5367 (defun org-follow-bbdb-link (name)
5368 "Follow a BBDB link to NAME."
5369 (require 'bbdb)
5370 (let ((inhibit-redisplay t))
5371 (catch 'exit
5372 ;; Exact match on name
5373 (bbdb-name (concat "\\`" name "\\'") nil)
5374 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5375 ;; Exact match on name
5376 (bbdb-company (concat "\\`" name "\\'") nil)
5377 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5378 ;; Partial match on name
5379 (bbdb-name name nil)
5380 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5381 ;; Partial match on company
5382 (bbdb-company name nil)
5383 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5384 ;; General match including network address and notes
5385 (bbdb name nil)
5386 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5387 (delete-window (get-buffer-window "*BBDB*"))
5388 (error "No matching BBDB record")))))
5389
5390 (defun org-follow-gnus-link (&optional group article)
5391 "Follow a Gnus link to GROUP and ARTICLE."
5392 (require 'gnus)
5393 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5394 (if group (gnus-fetch-group group))
5395 (if article
5396 (or (gnus-summary-goto-article article nil 'force)
5397 (if (fboundp 'gnus-summary-insert-cached-articles)
5398 (progn
5399 (gnus-summary-insert-cached-articles)
5400 (gnus-summary-goto-article article nil 'force))
5401 (message "Message could not be found.")))))
5402
5403 (defun org-follow-vm-link (&optional folder article readonly)
5404 "Follow a VM link to FOLDER and ARTICLE."
5405 (require 'vm)
5406 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5407 ;; ange-ftp or efs or tramp access
5408 (let ((user (or (match-string 1 folder) (user-login-name)))
5409 (host (match-string 2 folder))
5410 (file (match-string 3 folder)))
5411 (cond
5412 ((featurep 'tramp)
5413 ;; use tramp to access the file
5414 (if org-xemacs-p
5415 (setq folder (format "[%s@%s]%s" user host file))
5416 (setq folder (format "/%s@%s:%s" user host file))))
5417 (t
5418 ;; use ange-ftp or efs
5419 (require (if org-xemacs-p 'efs 'ange-ftp))
5420 (setq folder (format "/%s@%s:%s" user host file))))))
5421 (when folder
5422 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5423 (sit-for 0.1)
5424 (when article
5425 (vm-select-folder-buffer)
5426 (widen)
5427 (let ((case-fold-search t))
5428 (goto-char (point-min))
5429 (if (not (re-search-forward
5430 (concat "^" "message-id: *" (regexp-quote article))))
5431 (error "Could not find the specified message in this folder"))
5432 (vm-isearch-update)
5433 (vm-isearch-narrow)
5434 (vm-beginning-of-message)
5435 (vm-summarize)))))
5436
5437 (defun org-follow-wl-link (folder article)
5438 "Follow a Wanderlust link to FOLDER and ARTICLE."
5439 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5440 (if article (wl-summary-jump-to-msg-by-message-id article))
5441 (wl-summary-redisplay))
5442
5443 (defun org-follow-rmail-link (folder article)
5444 "Follow an RMAIL link to FOLDER and ARTICLE."
5445 (let (message-number)
5446 (save-excursion
5447 (save-window-excursion
5448 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5449 (setq message-number
5450 (save-restriction
5451 (widen)
5452 (goto-char (point-max))
5453 (if (re-search-backward
5454 (concat "^Message-ID:\\s-+" (regexp-quote
5455 (or article "")))
5456 nil t)
5457 (rmail-what-message))))))
5458 (if message-number
5459 (progn
5460 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5461 (rmail-show-message message-number)
5462 message-number)
5463 (error "Message not found"))))
5464
5465 (defun org-open-file (path &optional in-emacs line)
5466 "Open the file at PATH.
5467 First, this expands any special file name abbreviations. Then the
5468 configuration variable `org-file-apps' is checked if it contains an
5469 entry for this file type, and if yes, the corresponding command is launched.
5470 If no application is found, Emacs simply visits the file.
5471 With optional argument IN-EMACS, Emacs will visit the file.
5472 If the file does not exist, an error is thrown."
5473 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5474 (dfile (downcase file))
5475 ext cmd apps)
5476 (if (and (not (file-exists-p file))
5477 (not org-open-non-existing-files))
5478 (error "No such file: %s" file))
5479 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5480 (setq ext (match-string 1 dfile))
5481 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5482 (setq ext (match-string 1 dfile))))
5483 (setq apps (append org-file-apps (org-default-apps)))
5484 (if in-emacs
5485 (setq cmd 'emacs)
5486 (setq cmd (or (cdr (assoc ext apps))
5487 (cdr (assoc t apps)))))
5488 (cond
5489 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5490 (setq cmd (format cmd (concat "\"" file "\"")))
5491 (save-window-excursion
5492 (shell-command (concat cmd " & &"))))
5493 ((or (stringp cmd)
5494 (eq cmd 'emacs))
5495 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5496 (if line (goto-line line)))
5497 ((consp cmd)
5498 (eval cmd))
5499 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5500
5501 (defun org-default-apps ()
5502 "Return the default applications for this operating system."
5503 (cond
5504 ((eq system-type 'darwin)
5505 org-file-apps-defaults-macosx)
5506 ((eq system-type 'windows-nt)
5507 org-file-apps-defaults-windowsnt)
5508 (t org-file-apps-defaults-gnu)))
5509
5510 (defun org-expand-file-name (path)
5511 "Replace special path abbreviations and expand the file name."
5512 (expand-file-name path))
5513
5514
5515 (defvar org-insert-link-history nil
5516 "Minibuffer history for links inserted with `org-insert-link'.")
5517
5518 (defvar org-stored-links nil
5519 "Contains the links stored with `org-store-link'.")
5520
5521 ;;;###autoload
5522 (defun org-store-link (arg)
5523 "\\<org-mode-map>Store an org-link to the current location.
5524 This link can later be inserted into an org-buffer with
5525 \\[org-insert-link].
5526 For some link types, a prefix arg is interpreted:
5527 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5528 For file links, arg negates `org-line-numbers-in-file-links'."
5529 (interactive "P")
5530 (let (link cpltxt)
5531 (cond
5532
5533 ((eq major-mode 'bbdb-mode)
5534 (setq cpltxt (concat
5535 "bbdb:"
5536 (or (bbdb-record-name (bbdb-current-record))
5537 (bbdb-record-company (bbdb-current-record))))
5538 link (org-make-link cpltxt)))
5539
5540 ((eq major-mode 'calendar-mode)
5541 (let ((cd (calendar-cursor-to-date)))
5542 (setq link
5543 (format-time-string
5544 (car org-time-stamp-formats)
5545 (apply 'encode-time
5546 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5547 nil nil nil))))))
5548
5549 ((or (eq major-mode 'vm-summary-mode)
5550 (eq major-mode 'vm-presentation-mode))
5551 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5552 (vm-follow-summary-cursor)
5553 (save-excursion
5554 (vm-select-folder-buffer)
5555 (let* ((message (car vm-message-pointer))
5556 (folder (buffer-file-name))
5557 (subject (vm-su-subject message))
5558 (author (vm-su-full-name message))
5559 (message-id (vm-su-message-id message)))
5560 (setq folder (abbreviate-file-name folder))
5561 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5562 folder)
5563 (setq folder (replace-match "" t t folder)))
5564 (setq cpltxt (concat author " on: " subject))
5565 (setq link (concat cpltxt "\n "
5566 (org-make-link
5567 "vm:" folder "#" message-id))))))
5568
5569 ((eq major-mode 'wl-summary-mode)
5570 (let* ((msgnum (wl-summary-message-number))
5571 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5572 msgnum 'message-id))
5573 (wl-message-entity (elmo-msgdb-overview-get-entity
5574 msgnum (wl-summary-buffer-msgdb)))
5575 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5576 (subject "???")) ; FIXME: How to get subject of email?
5577 (setq cpltxt (concat author " on: " subject))
5578 (setq link (concat cpltxt "\n "
5579 (org-make-link
5580 "wl:" wl-summary-buffer-folder-name
5581 "#" message-id)))))
5582
5583 ((eq major-mode 'rmail-mode)
5584 (save-excursion
5585 (save-restriction
5586 (rmail-narrow-to-non-pruned-header)
5587 (let ((folder (buffer-file-name))
5588 (message-id (mail-fetch-field "message-id"))
5589 (author (mail-fetch-field "from"))
5590 (subject (mail-fetch-field "subject")))
5591 (setq cpltxt (concat author " on: " subject))
5592 (setq link (concat cpltxt "\n "
5593 (org-make-link
5594 "rmail:" folder "#" message-id)))))))
5595
5596 ((eq major-mode 'gnus-group-mode)
5597 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5598 (gnus-group-group-name)) ; version
5599 ((fboundp 'gnus-group-name)
5600 (gnus-group-name))
5601 (t "???"))))
5602 (setq cpltxt (concat
5603 (if (org-xor arg org-usenet-links-prefer-google)
5604 "http://groups.google.com/groups?group="
5605 "gnus:")
5606 group)
5607 link (org-make-link cpltxt))))
5608
5609 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5610 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5611 (gnus-summary-beginning-of-article)
5612 (let* ((group (car gnus-article-current))
5613 (article (cdr gnus-article-current))
5614 (header (gnus-summary-article-header article))
5615 (author (mail-header-from header))
5616 (message-id (mail-header-id header))
5617 (date (mail-header-date header))
5618 (subject (gnus-summary-subject-string)))
5619 (setq cpltxt (concat author " on: " subject))
5620 (if (org-xor arg org-usenet-links-prefer-google)
5621 (setq link
5622 (concat
5623 cpltxt "\n "
5624 (format "http://groups.google.com/groups?as_umsgid=%s"
5625 (org-fixup-message-id-for-http message-id))))
5626 (setq link (concat cpltxt "\n"
5627 (org-make-link
5628 "gnus:" group
5629 "#" (number-to-string article)))))))
5630
5631 ((eq major-mode 'w3-mode)
5632 (setq cpltxt (url-view-url t)
5633 link (org-make-link cpltxt)))
5634 ((eq major-mode 'w3m-mode)
5635 (setq cpltxt w3m-current-url
5636 link (org-make-link cpltxt)))
5637
5638 ((buffer-file-name)
5639 ;; Just link to this file here.
5640 (setq cpltxt (concat "file:"
5641 (abbreviate-file-name (buffer-file-name))))
5642 ;; Add the line number?
5643 (if (org-xor org-line-numbers-in-file-links arg)
5644 (setq cpltxt
5645 (concat cpltxt
5646 ":" (int-to-string
5647 (+ (if (bolp) 1 0) (count-lines
5648 (point-min) (point)))))))
5649 (setq link (org-make-link cpltxt)))
5650
5651 ((interactive-p)
5652 (error "Cannot link to a buffer which is not visiting a file"))
5653
5654 (t (setq link nil)))
5655
5656 (if (and (interactive-p) link)
5657 (progn
5658 (setq org-stored-links
5659 (cons (cons (or cpltxt link) link) org-stored-links))
5660 (message "Stored: %s" (or cpltxt link)))
5661 link)))
5662
5663 (defun org-make-link (&rest strings)
5664 "Concatenate STRINGS, format resulting string with `org-link-format'."
5665 (format org-link-format (apply 'concat strings)))
5666
5667 (defun org-xor (a b)
5668 "Exclusive or."
5669 (if a (not b) b))
5670
5671 (defun org-get-header (header)
5672 "Find a header field in the current buffer."
5673 (save-excursion
5674 (goto-char (point-min))
5675 (let ((case-fold-search t) s)
5676 (cond
5677 ((eq header 'from)
5678 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5679 (setq s (match-string 1)))
5680 (while (string-match "\"" s)
5681 (setq s (replace-match "" t t s)))
5682 (if (string-match "[<(].*" s)
5683 (setq s (replace-match "" t t s))))
5684 ((eq header 'message-id)
5685 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5686 (setq s (match-string 1))))
5687 ((eq header 'subject)
5688 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5689 (setq s (match-string 1)))))
5690 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5691 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5692 s)))
5693
5694
5695 (defun org-fixup-message-id-for-http (s)
5696 "Replace special characters in a message id, so it can be used in an http query."
5697 (while (string-match "<" s)
5698 (setq s (replace-match "%3C" t t s)))
5699 (while (string-match ">" s)
5700 (setq s (replace-match "%3E" t t s)))
5701 (while (string-match "@" s)
5702 (setq s (replace-match "%40" t t s)))
5703 s)
5704
5705 (defun org-insert-link (&optional complete-file)
5706 "Insert a link. At the prompt, enter the link.
5707
5708 Completion can be used to select a link previously stored with
5709 `org-store-link'. When the empty string is entered (i.e. if you just
5710 press RET at the prompt), the link defaults to the most recently
5711 stored link. As SPC triggers completion in the minibuffer, you need to
5712 use M-SPC or C-q SPC to force the insertion of a space character.
5713
5714 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5715 selected using completion. The path to the file will be relative to
5716 the current directory if the file is in the current directory or a
5717 subdirectory. Otherwise, the link will be the absolute path as
5718 completed in the minibuffer (i.e. normally ~/path/to/file).
5719
5720 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5721 is in the current directory or below."
5722 (interactive "P")
5723 (let ((link (if complete-file
5724 (read-file-name "File: ")
5725 (completing-read
5726 "Link: " org-stored-links nil nil nil
5727 org-insert-link-history
5728 (or (car (car org-stored-links))))))
5729 linktxt matched)
5730 (if (or (not link) (equal link ""))
5731 (error "No links available"))
5732 (if complete-file
5733 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5734 (cond
5735 ((equal complete-file '(16))
5736 (insert
5737 (org-make-link
5738 "file:" (abbreviate-file-name (expand-file-name link)))))
5739 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5740 (expand-file-name link))
5741 (insert
5742 (org-make-link
5743 "file:" (match-string 1 (expand-file-name link)))))
5744 (t (insert (org-make-link "file:" link)))))
5745 (setq linktxt (cdr (assoc link org-stored-links)))
5746 (if (not org-keep-stored-link-after-insertion)
5747 (setq org-stored-links (delq (assoc link org-stored-links)
5748 org-stored-links)))
5749 (if (not linktxt) (setq link (org-make-link link)))
5750 (let ((lines (org-split-string (or linktxt link) "\n")))
5751 (insert (car lines))
5752 (setq matched (string-match org-link-regexp (car lines)))
5753 (setq lines (cdr lines))
5754 (while lines
5755 (insert "\n")
5756 (if (save-excursion
5757 (beginning-of-line 0)
5758 (looking-at "[ \t]+\\S-"))
5759 (indent-relative))
5760 (setq matched (or matched
5761 (string-match org-link-regexp (car lines))))
5762 (insert (car lines))
5763 (setq lines (cdr lines))))
5764 (unless matched
5765 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5766
5767 ;;; Hooks for remember.el
5768 ;;;###autoload
5769 (defun org-remember-annotation ()
5770 "Return a link to the current location as an annotation for remember.el.
5771 If you are using Org-mode files as target for data storage with
5772 remember.el, then the annotations should include a link compatible with the
5773 conventions in Org-mode. This function returns such a link."
5774 (org-store-link nil))
5775
5776 (defconst org-remember-help
5777 "Select a destination location for the note.
5778 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5779 RET at beg-of-buf -> Append to file as level 2 headline
5780 RET on headline -> Store as sublevel entry to current headline
5781 <left>/<right> -> before/after current headline, same headings level")
5782
5783 ;;;###autoload
5784 (defun org-remember-handler ()
5785 "Store stuff from remember.el into an org file.
5786 First prompts for an org file. If the user just presses return, the value
5787 of `org-default-notes-file' is used.
5788 Then the command offers the headings tree of the selected file in order to
5789 file the text at a specific location.
5790 You can either immediately press RET to get the note appended to the
5791 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5792 find a better place. Then press RET or <left> or <right> in insert the note.
5793
5794 Key Cursor position Note gets inserted
5795 -----------------------------------------------------------------------------
5796 RET buffer-start as level 2 heading at end of file
5797 RET on headline as sublevel of the heading at cursor
5798 RET no heading at cursor position, level taken from context.
5799 Or use prefix arg to specify level manually.
5800 <left> on headline as same level, before current heading
5801 <right> on headline as same level, after current heading
5802
5803 So the fastest way to store the note is to press RET RET to append it to
5804 the default file. This way your current train of thought is not
5805 interrupted, in accordance with the principles of remember.el. But with
5806 little extra effort, you can push it directly to the correct location.
5807
5808 Before being stored away, the function ensures that the text has a
5809 headline, i.e. a first line that starts with a \"*\". If not, a headline
5810 is constructed from the current date and some additional data.
5811
5812 If the variable `org-adapt-indentation' is non-nil, the entire text is
5813 also indented so that it starts in the same column as the headline
5814 \(i.e. after the stars).
5815
5816 See also the variable `org-reverse-note-order'."
5817 (catch 'quit
5818 (let* ((txt (buffer-substring (point-min) (point-max)))
5819 (fastp current-prefix-arg)
5820 (file (if fastp org-default-notes-file (org-get-org-file)))
5821 (visiting (find-buffer-visiting file))
5822 (org-startup-with-deadline-check nil)
5823 (org-startup-folded nil)
5824 spos level indent reversed)
5825 ;; Modify text so that it becomes a nice subtree which can be inserted
5826 ;; into an org tree.
5827 (let* ((lines (split-string txt "\n"))
5828 (first (car lines))
5829 (lines (cdr lines)))
5830 (if (string-match "^\\*+" first)
5831 ;; Is already a headline
5832 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5833 -1) ?\ ))
5834 ;; We need to add a headline: Use time and first buffer line
5835 (setq lines (cons first lines)
5836 first (concat "* " (current-time-string)
5837 " (" (remember-buffer-desc) ")")
5838 indent " "))
5839 (if org-adapt-indentation
5840 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5841 (setq txt (concat first "\n"
5842 (mapconcat 'identity lines "\n"))))
5843 ;; Find the file
5844 (if (not visiting)
5845 (find-file-noselect file))
5846 (with-current-buffer (get-file-buffer file)
5847 (setq reversed (org-notes-order-reversed-p))
5848 (save-excursion
5849 (save-restriction
5850 (widen)
5851 ;; Ask the User for a location
5852 (setq spos (if fastp 1 (org-get-location
5853 (current-buffer)
5854 org-remember-help)))
5855 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5856 ; not handle this note
5857 (goto-char spos)
5858 (cond ((bobp)
5859 ;; Put it at the start or end, as level 2
5860 (save-restriction
5861 (widen)
5862 (goto-char (if reversed (point-min) (point-max)))
5863 (if (not (bolp)) (newline))
5864 (org-paste-subtree (or current-prefix-arg 2) txt)))
5865 ((and (org-on-heading-p nil) (not current-prefix-arg))
5866 ;; Put it below this entry, at the beg/end of the subtree
5867 (org-back-to-heading)
5868 (setq level (outline-level))
5869 (if reversed
5870 (outline-end-of-heading)
5871 (outline-end-of-subtree))
5872 (if (not (bolp)) (newline))
5873 (beginning-of-line 1)
5874 (org-paste-subtree (1+ level) txt))
5875 (t
5876 ;; Put it right there, with automatic level determined by
5877 ;; org-paste-subtree or from prefix arg
5878 (org-paste-subtree current-prefix-arg txt)))
5879 (when remember-save-after-remembering
5880 (save-buffer)
5881 (if (not visiting) (kill-buffer (current-buffer)))))))))
5882 t) ;; return t to indicate that we took care of this note.
5883
5884 (defun org-get-org-file ()
5885 "Read a filename, with default directory `org-directory'."
5886 (let ((default (or org-default-notes-file remember-data-file)))
5887 (read-file-name (format "File name [%s]: " default)
5888 (file-name-as-directory org-directory)
5889 default)))
5890
5891 (defun org-notes-order-reversed-p ()
5892 "Check if the current file should receive notes in reversed order."
5893 (cond
5894 ((not org-reverse-note-order) nil)
5895 ((eq t org-reverse-note-order) t)
5896 ((not (listp org-reverse-note-order)) nil)
5897 (t (catch 'exit
5898 (let ((all org-reverse-note-order)
5899 entry)
5900 (while (setq entry (pop all))
5901 (if (string-match (car entry) (buffer-file-name))
5902 (throw 'exit (cdr entry))))
5903 nil)))))
5904
5905 ;;; Tables
5906
5907 ;; Watch out: Here we are talking about two different kind of tables.
5908 ;; Most of the code is for the tables created with the Org-mode table editor.
5909 ;; Sometimes, we talk about tables created and edited with the table.el
5910 ;; Emacs package. We call the former org-type tables, and the latter
5911 ;; table.el-type tables.
5912
5913
5914 (defun org-before-change-function (beg end)
5915 "Every change indicates that a table might need an update."
5916 (setq org-table-may-need-update t))
5917
5918 (defconst org-table-line-regexp "^[ \t]*|"
5919 "Detects an org-type table line.")
5920 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5921 "Detects an org-type table line.")
5922 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5923 "Detects a table line marked for automatic recalculation.")
5924 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5925 "Detects a table line marked for automatic recalculation.")
5926 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5927 "Detects a table line marked for automatic recalculation.")
5928 (defconst org-table-hline-regexp "^[ \t]*|-"
5929 "Detects an org-type table hline.")
5930 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5931 "Detects a table-type table hline.")
5932 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5933 "Detects an org-type or table-type table.")
5934 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5935 "Searching from within a table (any type) this finds the first line
5936 outside the table.")
5937 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5938 "Searching from within a table (any type) this finds the first line
5939 outside the table.")
5940
5941 (defun org-table-create-with-table.el ()
5942 "Use the table.el package to insert a new table.
5943 If there is already a table at point, convert between Org-mode tables
5944 and table.el tables."
5945 (interactive)
5946 (require 'table)
5947 (cond
5948 ((org-at-table.el-p)
5949 (if (y-or-n-p "Convert table to Org-mode table? ")
5950 (org-table-convert)))
5951 ((org-at-table-p)
5952 (if (y-or-n-p "Convert table to table.el table? ")
5953 (org-table-convert)))
5954 (t (call-interactively 'table-insert))))
5955
5956 (defun org-table-create (&optional size)
5957 "Query for a size and insert a table skeleton.
5958 SIZE is a string Columns x Rows like for example \"3x2\"."
5959 (interactive "P")
5960 (unless size
5961 (setq size (read-string
5962 (concat "Table size Columns x Rows [e.g. "
5963 org-table-default-size "]: ")
5964 "" nil org-table-default-size)))
5965
5966 (let* ((pos (point))
5967 (indent (make-string (current-column) ?\ ))
5968 (split (org-split-string size " *x *"))
5969 (rows (string-to-number (nth 1 split)))
5970 (columns (string-to-number (car split)))
5971 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5972 "\n")))
5973 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5974 (point-at-bol) (point)))
5975 (beginning-of-line 1)
5976 (newline))
5977 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5978 (dotimes (i rows) (insert line))
5979 (goto-char pos)
5980 (if (> rows 1)
5981 ;; Insert a hline after the first row.
5982 (progn
5983 (end-of-line 1)
5984 (insert "\n|-")
5985 (goto-char pos)))
5986 (org-table-align)))
5987
5988 (defun org-table-convert-region (beg0 end0 nspace)
5989 "Convert region to a table.
5990 The region goes from BEG0 to END0, but these borders will be moved
5991 slightly, to make sure a beginning of line in the first line is included.
5992 When NSPACE is non-nil, it indicates the minimum number of spaces that
5993 separate columns (default: just one space)"
5994 (let* ((beg (min beg0 end0))
5995 (end (max beg0 end0))
5996 (tabsep t)
5997 re)
5998 (goto-char beg)
5999 (beginning-of-line 1)
6000 (setq beg (move-marker (make-marker) (point)))
6001 (goto-char end)
6002 (if (bolp) (backward-char 1) (end-of-line 1))
6003 (setq end (move-marker (make-marker) (point)))
6004 ;; Lets see if this is tab-separated material. If every nonempty line
6005 ;; contains a tab, we will assume that it is tab-separated material
6006 (if nspace
6007 (setq tabsep nil)
6008 (goto-char beg)
6009 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6010 (if nspace (setq tabsep nil))
6011 (if tabsep
6012 (setq re "^\\|\t")
6013 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6014 (max 1 (prefix-numeric-value nspace)))))
6015 (goto-char beg)
6016 (while (re-search-forward re end t)
6017 (replace-match "|" t t))
6018 (goto-char beg)
6019 (insert " ")
6020 (org-table-align)))
6021
6022 (defun org-table-import (file arg)
6023 "Import FILE as a table.
6024 The file is assumed to be tab-separated. Such files can be produced by most
6025 spreadsheet and database applications. If no tabs (at least one per line)
6026 are found, lines will be split on whitespace into fields."
6027 (interactive "f\nP")
6028 (or (bolp) (newline))
6029 (let ((beg (point))
6030 (pm (point-max)))
6031 (insert-file-contents file)
6032 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6033
6034 (defun org-table-export ()
6035 "Export table as a tab-separated file.
6036 Such a file can be imported into a spreadsheet program like Excel."
6037 (interactive)
6038 (let* ((beg (org-table-begin))
6039 (end (org-table-end))
6040 (table (buffer-substring beg end))
6041 (file (read-file-name "Export table to: "))
6042 buf)
6043 (unless (or (not (file-exists-p file))
6044 (y-or-n-p (format "Overwrite file %s? " file)))
6045 (error "Abort"))
6046 (with-current-buffer (find-file-noselect file)
6047 (setq buf (current-buffer))
6048 (erase-buffer)
6049 (fundamental-mode)
6050 (insert table)
6051 (goto-char (point-min))
6052 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6053 (replace-match "" t t)
6054 (end-of-line 1))
6055 (goto-char (point-min))
6056 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6057 (replace-match "" t t)
6058 (goto-char (min (1+ (point)) (point-max))))
6059 (goto-char (point-min))
6060 (while (re-search-forward "^-[-+]*$" nil t)
6061 (replace-match "")
6062 (if (looking-at "\n")
6063 (delete-char 1)))
6064 (goto-char (point-min))
6065 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6066 (replace-match "\t" t t))
6067 (save-buffer))
6068 (kill-buffer buf)))
6069
6070 (defvar org-table-aligned-begin-marker (make-marker)
6071 "Marker at the beginning of the table last aligned.
6072 Used to check if cursor still is in that table, to minimize realignment.")
6073 (defvar org-table-aligned-end-marker (make-marker)
6074 "Marker at the end of the table last aligned.
6075 Used to check if cursor still is in that table, to minimize realignment.")
6076 (defvar org-table-last-alignment nil
6077 "List of flags for flushright alignment, from the last re-alignment.
6078 This is being used to correctly align a single field after TAB or RET.")
6079 ;; FIXME: The following is currently not used.
6080 (defvar org-table-last-column-widths nil
6081 "List of max width of fields in each column.
6082 This is being used to correctly align a single field after TAB or RET.")
6083
6084 (defvar org-last-recalc-line nil)
6085
6086 (defun org-table-align ()
6087 "Align the table at point by aligning all vertical bars."
6088 (interactive)
6089 ;; (message "align") (sit-for 2)
6090 (let* (
6091 ;; Limits of table
6092 (beg (org-table-begin))
6093 (end (org-table-end))
6094 ;; Current cursor position
6095 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6096 (colpos (org-table-current-column))
6097 (winstart (window-start))
6098 text lines (new "") lengths l typenums ty fields maxfields i
6099 column
6100 (indent "") cnt frac
6101 rfmt hfmt
6102 (spaces (if (org-in-invisibility-spec-p '(org-table))
6103 org-table-spaces-around-invisible-separators
6104 org-table-spaces-around-separators))
6105 (sp1 (car spaces))
6106 (sp2 (cdr spaces))
6107 (rfmt1 (concat
6108 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6109 (hfmt1 (concat
6110 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6111 emptystrings)
6112 (untabify beg end)
6113 ;; (message "Aligning table...")
6114 ;; Get the rows
6115 (setq lines (org-split-string
6116 (buffer-substring-no-properties beg end) "\n"))
6117 ;; Store the indentation of the first line
6118 (if (string-match "^ *" (car lines))
6119 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6120 ;; Mark the hlines
6121 (setq lines (mapcar (lambda (l)
6122 (if (string-match "^ *|-" l)
6123 nil
6124 (if (string-match "[ \t]+$" l)
6125 (substring l 0 (match-beginning 0))
6126 l)))
6127 lines))
6128 ;; Get the data fields
6129 (setq fields (mapcar
6130 (lambda (l)
6131 (org-split-string l " *| *"))
6132 (delq nil (copy-sequence lines))))
6133 ;; How many fields in the longest line?
6134 (condition-case nil
6135 (setq maxfields (apply 'max (mapcar 'length fields)))
6136 (error
6137 (kill-region beg end)
6138 (org-table-create org-table-default-size)
6139 (error "Empty table - created default table")))
6140 ;; A list of empty string to fill any short rows on output
6141 (setq emptystrings (make-list maxfields ""))
6142 ;; Get the maximum length of a field and the most common datatype
6143 ;; for each column
6144 (setq i -1)
6145 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6146 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6147 ;; maximum length
6148 (push (apply 'max 1 (mapcar 'length column)) lengths)
6149 ;; compute the fraction stepwise, ignoring empty fields
6150 (setq cnt 0 frac 0.0)
6151 (mapcar
6152 (lambda (x)
6153 (if (equal x "")
6154 nil
6155 (setq frac ( / (+ (* frac cnt)
6156 (if (string-match org-table-number-regexp x) 1 0))
6157 (setq cnt (1+ cnt))))))
6158 column)
6159 (push (>= frac org-table-number-fraction) typenums))
6160 (setq lengths (nreverse lengths)
6161 typenums (nreverse typenums))
6162 (setq org-table-last-alignment typenums
6163 org-table-last-column-widths lengths)
6164 ;; Compute the formats needed for output of the table
6165 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6166 (while (setq l (pop lengths))
6167 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6168 (setq rfmt (concat rfmt (format rfmt1 ty l))
6169 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6170 (setq rfmt (concat rfmt "\n")
6171 hfmt (concat (substring hfmt 0 -1) "|\n"))
6172 ;; Produce the new table
6173 ;;(while lines
6174 ;; (setq l (pop lines))
6175 ;; (if l
6176 ;; (setq new (concat new (apply 'format rfmt
6177 ;; (append (pop fields) emptystrings))))
6178 ;; (setq new (concat new hfmt))))
6179 (setq new (mapconcat
6180 (lambda (l)
6181 (if l (apply 'format rfmt
6182 (append (pop fields) emptystrings))
6183 hfmt))
6184 lines ""))
6185 ;; Replace the old one
6186 (delete-region beg end)
6187 (move-marker end nil)
6188 (move-marker org-table-aligned-begin-marker (point))
6189 (insert new)
6190 (move-marker org-table-aligned-end-marker (point))
6191 ;; Try to move to the old location (approximately)
6192 (goto-line linepos)
6193 (set-window-start (selected-window) winstart 'noforce)
6194 (org-table-goto-column colpos)
6195 (setq org-table-may-need-update nil)
6196 (if (org-in-invisibility-spec-p '(org-table))
6197 (org-table-add-invisible-to-vertical-lines))
6198 ))
6199
6200 (defun org-table-begin (&optional table-type)
6201 "Find the beginning of the table and return its position.
6202 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6203 (save-excursion
6204 (if (not (re-search-backward
6205 (if table-type org-table-any-border-regexp
6206 org-table-border-regexp)
6207 nil t))
6208 (error "Can't find beginning of table")
6209 (goto-char (match-beginning 0))
6210 (beginning-of-line 2)
6211 (point))))
6212
6213 (defun org-table-end (&optional table-type)
6214 "Find the end of the table and return its position.
6215 With argument TABLE-TYPE, go to the end of a table.el-type table."
6216 (save-excursion
6217 (if (not (re-search-forward
6218 (if table-type org-table-any-border-regexp
6219 org-table-border-regexp)
6220 nil t))
6221 (goto-char (point-max))
6222 (goto-char (match-beginning 0)))
6223 (point-marker)))
6224
6225 (defun org-table-justify-field-maybe (&optional new)
6226 "Justify the current field, text to left, number to right.
6227 Optional argument NEW may specify text to replace the current field content."
6228 (cond
6229 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6230 ((org-at-table-hline-p)
6231 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6232 ;; (setq org-table-may-need-update t)
6233 )
6234 ((and (not new)
6235 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6236 (current-buffer)))
6237 (< (point) org-table-aligned-begin-marker)
6238 (>= (point) org-table-aligned-end-marker)))
6239 ;; This is not the same table, force a full re-align
6240 (setq org-table-may-need-update t))
6241 (t ;; realign the current field, based on previous full realign
6242 (let* ((pos (point)) s
6243 (col (org-table-current-column))
6244 (num (nth (1- col) org-table-last-alignment))
6245 l f n o e)
6246 (when (> col 0)
6247 (skip-chars-backward "^|\n")
6248 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6249 (progn
6250 (setq s (match-string 1)
6251 o (match-string 0)
6252 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6253 e (not (= (match-beginning 2) (match-end 2))))
6254 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6255 l (if e "|" (setq org-table-may-need-update t) ""))
6256 n (format f s t t))
6257 (if new
6258 (if (<= (length new) l)
6259 (setq n (format f new t t)) ;; FIXME: why t t?????
6260 (setq n (concat new "|") org-table-may-need-update t)))
6261 (or (equal n o)
6262 (let (org-table-may-need-update)
6263 (replace-match n))))
6264 (setq org-table-may-need-update t))
6265 (goto-char pos))))))
6266
6267 (defun org-table-next-field ()
6268 "Go to the next field in the current table.
6269 Before doing so, re-align the table if necessary."
6270 (interactive)
6271 (org-table-maybe-eval-formula)
6272 (org-table-maybe-recalculate-line)
6273 (if (and org-table-automatic-realign
6274 org-table-may-need-update)
6275 (org-table-align))
6276 (if (org-at-table-hline-p)
6277 (end-of-line 1))
6278 (condition-case nil
6279 (progn
6280 (re-search-forward "|" (org-table-end))
6281 (if (looking-at "[ \t]*$")
6282 (re-search-forward "|" (org-table-end)))
6283 (if (looking-at "-")
6284 (progn
6285 (beginning-of-line 0)
6286 (org-table-insert-row 'below))
6287 (if (looking-at " ") (forward-char 1))))
6288 (error
6289 (org-table-insert-row 'below))))
6290
6291 (defun org-table-previous-field ()
6292 "Go to the previous field in the table.
6293 Before doing so, re-align the table if necessary."
6294 (interactive)
6295 (org-table-justify-field-maybe)
6296 (org-table-maybe-recalculate-line)
6297 (if (and org-table-automatic-realign
6298 org-table-may-need-update)
6299 (org-table-align))
6300 (if (org-at-table-hline-p)
6301 (end-of-line 1))
6302 (re-search-backward "|" (org-table-begin))
6303 (re-search-backward "|" (org-table-begin))
6304 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6305 (re-search-backward "|" (org-table-begin)))
6306 (if (looking-at "| ?")
6307 (goto-char (match-end 0))))
6308
6309 (defun org-table-next-row ()
6310 "Go to the next row (same column) in the current table.
6311 Before doing so, re-align the table if necessary."
6312 (interactive)
6313 (org-table-maybe-eval-formula)
6314 (org-table-maybe-recalculate-line)
6315 (if (or (looking-at "[ \t]*$")
6316 (save-excursion (skip-chars-backward " \t") (bolp)))
6317 (newline)
6318 (if (and org-table-automatic-realign
6319 org-table-may-need-update)
6320 (org-table-align))
6321 (let ((col (org-table-current-column)))
6322 (beginning-of-line 2)
6323 (if (or (not (org-at-table-p))
6324 (org-at-table-hline-p))
6325 (progn
6326 (beginning-of-line 0)
6327 (org-table-insert-row 'below)))
6328 (org-table-goto-column col)
6329 (skip-chars-backward "^|\n\r")
6330 (if (looking-at " ") (forward-char 1)))))
6331
6332 (defun org-table-copy-down (n)
6333 "Copy a field down in the current column.
6334 If the field at the cursor is empty, copy into it the content of the nearest
6335 non-empty field above. With argument N, use the Nth non-empty field.
6336 If the current field is not empty, it is copied down to the next row, and
6337 the cursor is moved with it. Therefore, repeating this command causes the
6338 column to be filled row-by-row.
6339 If the variable `org-table-copy-increment' is non-nil and the field is an
6340 integer, it will be incremented while copying."
6341 (interactive "p")
6342 (let* ((colpos (org-table-current-column))
6343 (field (org-table-get-field))
6344 (non-empty (string-match "[^ \t]" field))
6345 (beg (org-table-begin))
6346 txt)
6347 (org-table-check-inside-data-field)
6348 (if non-empty
6349 (progn
6350 (setq txt (org-trim field))
6351 (org-table-next-row)
6352 (org-table-blank-field))
6353 (save-excursion
6354 (setq txt
6355 (catch 'exit
6356 (while (progn (beginning-of-line 1)
6357 (re-search-backward org-table-dataline-regexp
6358 beg t))
6359 (org-table-goto-column colpos t)
6360 (if (and (looking-at
6361 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6362 (= (setq n (1- n)) 0))
6363 (throw 'exit (match-string 1))))))))
6364 (if txt
6365 (progn
6366 (if (and org-table-copy-increment
6367 (string-match "^[0-9]+$" txt))
6368 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6369 (insert txt)
6370 (org-table-maybe-recalculate-line)
6371 (org-table-align))
6372 (error "No non-empty field found"))))
6373
6374 (defun org-table-check-inside-data-field ()
6375 "Is point inside a table data field?
6376 I.e. not on a hline or before the first or after the last column?
6377 This actually throws an error, so it aborts the current command."
6378 (if (or (not (org-at-table-p))
6379 (= (org-table-current-column) 0)
6380 (org-at-table-hline-p)
6381 (looking-at "[ \t]*$"))
6382 (error "Not in table data field")))
6383
6384 (defvar org-table-clip nil
6385 "Clipboard for table regions.")
6386
6387 (defun org-table-blank-field ()
6388 "Blank the current table field or active region."
6389 (interactive)
6390 (org-table-check-inside-data-field)
6391 (if (and (interactive-p) (org-region-active-p))
6392 (let (org-table-clip)
6393 (org-table-cut-region (region-beginning) (region-end)))
6394 (skip-chars-backward "^|")
6395 (backward-char 1)
6396 (if (looking-at "|[^|\n]+")
6397 (let* ((pos (match-beginning 0))
6398 (match (match-string 0))
6399 (len (length match)))
6400 (replace-match (concat "|" (make-string (1- len) ?\ )))
6401 (goto-char (+ 2 pos))
6402 (substring match 1)))))
6403
6404 (defun org-table-get-field (&optional n replace)
6405 "Return the value of the field in column N of current row.
6406 N defaults to current field.
6407 If REPLACE is a string, replace field with this value. The return value
6408 is always the old value."
6409 (and n (org-table-goto-column n))
6410 (skip-chars-backward "^|\n")
6411 (backward-char 1)
6412 (if (looking-at "|[^|\r\n]*")
6413 (let* ((pos (match-beginning 0))
6414 (val (buffer-substring (1+ pos) (match-end 0))))
6415 (if replace
6416 (replace-match (concat "|" replace)))
6417 (goto-char (min (point-at-eol) (+ 2 pos)))
6418 val)
6419 (forward-char 1) ""))
6420
6421 (defun org-table-current-column ()
6422 "Find out which column we are in.
6423 When called interactively, column is also displayed in echo area."
6424 (interactive)
6425 (if (interactive-p) (org-table-check-inside-data-field))
6426 (save-excursion
6427 (let ((cnt 0) (pos (point)))
6428 (beginning-of-line 1)
6429 (while (search-forward "|" pos t)
6430 (setq cnt (1+ cnt)))
6431 (if (interactive-p) (message "This is table column %d" cnt))
6432 cnt)))
6433
6434 (defun org-table-goto-column (n &optional on-delim force)
6435 "Move the cursor to the Nth column in the current table line.
6436 With optional argument ON-DELIM, stop with point before the left delimiter
6437 of the field.
6438 If there are less than N fields, just go to after the last delimiter.
6439 However, when FORCE is non-nil, create new columns if necessary."
6440 (let ((pos (point-at-eol)))
6441 (beginning-of-line 1)
6442 (when (> n 0)
6443 (while (and (> (setq n (1- n)) -1)
6444 (or (search-forward "|" pos t)
6445 (and force
6446 (progn (end-of-line 1)
6447 (skip-chars-backward "^|")
6448 (insert " | "))))))
6449 ; (backward-char 2) t)))))
6450 (when (and force (not (looking-at ".*|")))
6451 (save-excursion (end-of-line 1) (insert " | ")))
6452 (if on-delim
6453 (backward-char 1)
6454 (if (looking-at " ") (forward-char 1))))))
6455
6456 (defun org-at-table-p (&optional table-type)
6457 "Return t if the cursor is inside an org-type table.
6458 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6459 (if org-enable-table-editor
6460 (save-excursion
6461 (beginning-of-line 1)
6462 (looking-at (if table-type org-table-any-line-regexp
6463 org-table-line-regexp)))
6464 nil))
6465
6466 (defun org-table-recognize-table.el ()
6467 "If there is a table.el table nearby, recognize it and move into it."
6468 (if org-table-tab-recognizes-table.el
6469 (if (org-at-table.el-p)
6470 (progn
6471 (beginning-of-line 1)
6472 (if (looking-at org-table-dataline-regexp)
6473 nil
6474 (if (looking-at org-table1-hline-regexp)
6475 (progn
6476 (beginning-of-line 2)
6477 (if (looking-at org-table-any-border-regexp)
6478 (beginning-of-line -1)))))
6479 (if (re-search-forward "|" (org-table-end t) t)
6480 (progn
6481 (require 'table)
6482 (if (table--at-cell-p (point))
6483 t
6484 (message "recognizing table.el table...")
6485 (table-recognize-table)
6486 (message "recognizing table.el table...done")))
6487 (error "This should not happen..."))
6488 t)
6489 nil)
6490 nil))
6491
6492 (defun org-at-table.el-p ()
6493 "Return t if the cursor is inside a table.el-type table."
6494 (save-excursion
6495 (if (org-at-table-p 'any)
6496 (progn
6497 (goto-char (org-table-begin 'any))
6498 (looking-at org-table1-hline-regexp))
6499 nil)))
6500
6501 (defun org-at-table-hline-p ()
6502 "Return t if the cursor is inside a hline in a table."
6503 (if org-enable-table-editor
6504 (save-excursion
6505 (beginning-of-line 1)
6506 (looking-at org-table-hline-regexp))
6507 nil))
6508
6509 (defun org-table-insert-column ()
6510 "Insert a new column into the table."
6511 (interactive)
6512 (if (not (org-at-table-p))
6513 (error "Not at a table"))
6514 (org-table-find-dataline)
6515 (let* ((col (max 1 (org-table-current-column)))
6516 (beg (org-table-begin))
6517 (end (org-table-end))
6518 ;; Current cursor position
6519 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6520 (colpos col))
6521 (goto-char beg)
6522 (while (< (point) end)
6523 (if (org-at-table-hline-p)
6524 nil
6525 (org-table-goto-column col t)
6526 (insert "| "))
6527 (beginning-of-line 2))
6528 (move-marker end nil)
6529 (goto-line linepos)
6530 (org-table-goto-column colpos)
6531 (org-table-align)
6532 (org-table-modify-formulas 'insert col)))
6533
6534 (defun org-table-find-dataline ()
6535 "Find a dataline in the current table, which is needed for column commands."
6536 (if (and (org-at-table-p)
6537 (not (org-at-table-hline-p)))
6538 t
6539 (let ((col (current-column))
6540 (end (org-table-end)))
6541 (move-to-column col)
6542 (while (and (< (point) end)
6543 (or (not (= (current-column) col))
6544 (org-at-table-hline-p)))
6545 (beginning-of-line 2)
6546 (move-to-column col))
6547 (if (and (org-at-table-p)
6548 (not (org-at-table-hline-p)))
6549 t
6550 (error
6551 "Please position cursor in a data line for column operations")))))
6552
6553 (defun org-table-delete-column ()
6554 "Delete a column into the table."
6555 (interactive)
6556 (if (not (org-at-table-p))
6557 (error "Not at a table"))
6558 (org-table-find-dataline)
6559 (org-table-check-inside-data-field)
6560 (let* ((col (org-table-current-column))
6561 (beg (org-table-begin))
6562 (end (org-table-end))
6563 ;; Current cursor position
6564 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6565 (colpos col))
6566 (goto-char beg)
6567 (while (< (point) end)
6568 (if (org-at-table-hline-p)
6569 nil
6570 (org-table-goto-column col t)
6571 (and (looking-at "|[^|\n]+|")
6572 (replace-match "|")))
6573 (beginning-of-line 2))
6574 (move-marker end nil)
6575 (goto-line linepos)
6576 (org-table-goto-column colpos)
6577 (org-table-align)
6578 (org-table-modify-formulas 'remove col)))
6579
6580 (defun org-table-move-column-right ()
6581 "Move column to the right."
6582 (interactive)
6583 (org-table-move-column nil))
6584 (defun org-table-move-column-left ()
6585 "Move column to the left."
6586 (interactive)
6587 (org-table-move-column 'left))
6588
6589 (defun org-table-move-column (&optional left)
6590 "Move the current column to the right. With arg LEFT, move to the left."
6591 (interactive "P")
6592 (if (not (org-at-table-p))
6593 (error "Not at a table"))
6594 (org-table-find-dataline)
6595 (org-table-check-inside-data-field)
6596 (let* ((col (org-table-current-column))
6597 (col1 (if left (1- col) col))
6598 (beg (org-table-begin))
6599 (end (org-table-end))
6600 ;; Current cursor position
6601 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6602 (colpos (if left (1- col) (1+ col))))
6603 (if (and left (= col 1))
6604 (error "Cannot move column further left"))
6605 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6606 (error "Cannot move column further right"))
6607 (goto-char beg)
6608 (while (< (point) end)
6609 (if (org-at-table-hline-p)
6610 nil
6611 (org-table-goto-column col1 t)
6612 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6613 (replace-match "|\\2|\\1|")))
6614 (beginning-of-line 2))
6615 (move-marker end nil)
6616 (goto-line linepos)
6617 (org-table-goto-column colpos)
6618 (org-table-align)
6619 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6620
6621 (defun org-table-move-row-down ()
6622 "move table row down."
6623 (interactive)
6624 (org-table-move-row nil))
6625 (defun org-table-move-row-up ()
6626 "move table row up."
6627 (interactive)
6628 (org-table-move-row 'up))
6629
6630 (defun org-table-move-row (&optional up)
6631 "Move the current table line down. With arg UP, move it up."
6632 (interactive "P")
6633 (let ((col (current-column))
6634 (pos (point))
6635 (tonew (if up 0 2))
6636 txt)
6637 (beginning-of-line tonew)
6638 (if (not (org-at-table-p))
6639 (progn
6640 (goto-char pos)
6641 (error "Cannot move row further")))
6642 (goto-char pos)
6643 (beginning-of-line 1)
6644 (setq pos (point))
6645 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6646 (delete-region (point) (1+ (point-at-eol)))
6647 (beginning-of-line tonew)
6648 (insert txt)
6649 (beginning-of-line 0)
6650 (move-to-column col)))
6651
6652 (defun org-table-insert-row (&optional arg)
6653 "Insert a new row above the current line into the table.
6654 With prefix ARG, insert below the current line."
6655 (interactive "P")
6656 (if (not (org-at-table-p))
6657 (error "Not at a table"))
6658 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6659 new)
6660 (if (string-match "^[ \t]*|-" line)
6661 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6662 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6663 ;; Fix the first field if necessary
6664 (setq new (concat new))
6665 (if (string-match "^[ \t]*| *[#$] *|" line)
6666 (setq new (replace-match (match-string 0 line) t t new)))
6667 (beginning-of-line (if arg 2 1))
6668 (let (org-table-may-need-update)
6669 (insert-before-markers new)
6670 (insert-before-markers "\n"))
6671 (beginning-of-line 0)
6672 (re-search-forward "| ?" (point-at-eol) t)
6673 (and org-table-may-need-update (org-table-align))))
6674
6675 (defun org-table-insert-hline (&optional arg)
6676 "Insert a horizontal-line below the current line into the table.
6677 With prefix ARG, insert above the current line."
6678 (interactive "P")
6679 (if (not (org-at-table-p))
6680 (error "Not at a table"))
6681 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6682 (col (current-column))
6683 start)
6684 (if (string-match "^[ \t]*|-" line)
6685 (setq line
6686 (mapcar (lambda (x) (if (member x '(?| ?+))
6687 (prog1 (if start ?+ ?|) (setq start t))
6688 (if start ?- ?\ )))
6689 line))
6690 (setq line
6691 (mapcar (lambda (x) (if (equal x ?|)
6692 (prog1 (if start ?+ ?|) (setq start t))
6693 (if start ?- ?\ )))
6694 line)))
6695 (beginning-of-line (if arg 1 2))
6696 (apply 'insert line)
6697 (if (equal (char-before (point)) ?+)
6698 (progn (backward-delete-char 1) (insert "|")))
6699 (insert "\n")
6700 (beginning-of-line 0)
6701 (move-to-column col)))
6702
6703 (defun org-table-kill-row ()
6704 "Delete the current row or horizontal line from the table."
6705 (interactive)
6706 (if (not (org-at-table-p))
6707 (error "Not at a table"))
6708 (let ((col (current-column)))
6709 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6710 (if (not (org-at-table-p)) (beginning-of-line 0))
6711 (move-to-column col)))
6712
6713
6714 (defun org-table-cut-region (beg end)
6715 "Copy region in table to the clipboard and blank all relevant fields."
6716 (interactive "r")
6717 (org-table-copy-region beg end 'cut))
6718
6719 (defun org-table-copy-region (beg end &optional cut)
6720 "Copy rectangular region in table to clipboard.
6721 A special clipboard is used which can only be accessed
6722 with `org-table-paste-rectangle'"
6723 (interactive "rP")
6724 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6725 region cols
6726 (rpl (if cut " " nil)))
6727 (goto-char beg)
6728 (org-table-check-inside-data-field)
6729 (setq l01 (count-lines (point-min) (point))
6730 c01 (org-table-current-column))
6731 (goto-char end)
6732 (org-table-check-inside-data-field)
6733 (setq l02 (count-lines (point-min) (point))
6734 c02 (org-table-current-column))
6735 (setq l1 (min l01 l02) l2 (max l01 l02)
6736 c1 (min c01 c02) c2 (max c01 c02))
6737 (catch 'exit
6738 (while t
6739 (catch 'nextline
6740 (if (> l1 l2) (throw 'exit t))
6741 (goto-line l1)
6742 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6743 (setq cols nil ic1 c1 ic2 c2)
6744 (while (< ic1 (1+ ic2))
6745 (push (org-table-get-field ic1 rpl) cols)
6746 (setq ic1 (1+ ic1)))
6747 (push (nreverse cols) region)
6748 (setq l1 (1+ l1)))))
6749 (setq org-table-clip (nreverse region))
6750 (if cut (org-table-align))
6751 org-table-clip))
6752
6753 (defun org-table-paste-rectangle ()
6754 "Paste a rectangular region into a table.
6755 The upper right corner ends up in the current field. All involved fields
6756 will be overwritten. If the rectangle does not fit into the present table,
6757 the table is enlarged as needed. The process ignores horizontal separator
6758 lines."
6759 (interactive)
6760 (unless (and org-table-clip (listp org-table-clip))
6761 (error "First cut/copy a region to paste!"))
6762 (org-table-check-inside-data-field)
6763 (let* ((clip org-table-clip)
6764 (line (count-lines (point-min) (point)))
6765 (col (org-table-current-column))
6766 (org-enable-table-editor t)
6767 (org-table-automatic-realign nil)
6768 c cols field)
6769 (while (setq cols (pop clip))
6770 (while (org-at-table-hline-p) (beginning-of-line 2))
6771 (if (not (org-at-table-p))
6772 (progn (end-of-line 0) (org-table-next-field)))
6773 (setq c col)
6774 (while (setq field (pop cols))
6775 (org-table-goto-column c nil 'force)
6776 (org-table-get-field nil field)
6777 (setq c (1+ c)))
6778 (beginning-of-line 2))
6779 (goto-line line)
6780 (org-table-goto-column col)
6781 (org-table-align)))
6782
6783 (defun org-table-convert ()
6784 "Convert from `org-mode' table to table.el and back.
6785 Obviously, this only works within limits. When an Org-mode table is
6786 converted to table.el, all horizontal separator lines get lost, because
6787 table.el uses these as cell boundaries and has no notion of horizontal lines.
6788 A table.el table can be converted to an Org-mode table only if it does not
6789 do row or column spanning. Multiline cells will become multiple cells.
6790 Beware, Org-mode does not test if the table can be successfully converted - it
6791 blindly applies a recipe that works for simple tables."
6792 (interactive)
6793 (require 'table)
6794 (if (org-at-table.el-p)
6795 ;; convert to Org-mode table
6796 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6797 (end (move-marker (make-marker) (org-table-end t))))
6798 (table-unrecognize-region beg end)
6799 (goto-char beg)
6800 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6801 (replace-match ""))
6802 (goto-char beg))
6803 (if (org-at-table-p)
6804 ;; convert to table.el table
6805 (let ((beg (move-marker (make-marker) (org-table-begin)))
6806 (end (move-marker (make-marker) (org-table-end))))
6807 ;; first, get rid of all horizontal lines
6808 (goto-char beg)
6809 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6810 (replace-match ""))
6811 ;; insert a hline before first
6812 (goto-char beg)
6813 (org-table-insert-hline 'above)
6814 ;; insert a hline after each line
6815 (while (progn (beginning-of-line 2) (< (point) end))
6816 (org-table-insert-hline))
6817 (goto-char beg)
6818 (setq end (move-marker end (org-table-end)))
6819 ;; replace "+" at beginning and ending of hlines
6820 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6821 (replace-match "\\1+-"))
6822 (goto-char beg)
6823 (while (re-search-forward "-|[ \t]*$" end t)
6824 (replace-match "-+"))
6825 (goto-char beg)))))
6826
6827 (defun org-table-wrap-region (arg)
6828 "Wrap several fields in a column like a paragraph.
6829 This is useful if you'd like to spread the contents of a field over several
6830 lines, in order to keep the table compact.
6831
6832 If there is an active region, and both point and mark are in the same column,
6833 the text in the column is wrapped to minimum width for the given number of
6834 lines. Generally, this makes the table more compact. A prefix ARG may be
6835 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6836 formats the selected text to two lines. If the region was longer than 2
6837 lines, the remaining lines remain empty. A negative prefix argument reduces
6838 the current number of lines by that amount. The wrapped text is pasted back
6839 into the table. If you formatted it to more lines than it was before, fields
6840 further down in the table get overwritten - so you might need to make space in
6841 the table first.
6842
6843 If there is no region, the current field is split at the cursor position and
6844 the text fragment to the right of the cursor is prepended to the field one
6845 line down.
6846
6847 If there is no region, but you specify a prefix ARG, the current field gets
6848 blank, and the content is appended to the field above."
6849 (interactive "P")
6850 (org-table-check-inside-data-field)
6851 (if (org-region-active-p)
6852 ;; There is a region: fill as a paragraph
6853 (let ((beg (region-beginning))
6854 nlines)
6855 (org-table-cut-region (region-beginning) (region-end))
6856 (if (> (length (car org-table-clip)) 1)
6857 (error "Region must be limited to single column"))
6858 (setq nlines (if arg
6859 (if (< arg 1)
6860 (+ (length org-table-clip) arg)
6861 arg)
6862 (length org-table-clip)))
6863 (setq org-table-clip
6864 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6865 nil nlines)))
6866 (goto-char beg)
6867 (org-table-paste-rectangle))
6868 ;; No region, split the current field at point
6869 (if arg
6870 ;; combine with field above
6871 (let ((s (org-table-blank-field))
6872 (col (org-table-current-column)))
6873 (beginning-of-line 0)
6874 (while (org-at-table-hline-p) (beginning-of-line 0))
6875 (org-table-goto-column col)
6876 (skip-chars-forward "^|")
6877 (skip-chars-backward " ")
6878 (insert " " (org-trim s))
6879 (org-table-align))
6880 ;; split field
6881 (when (looking-at "\\([^|]+\\)+|")
6882 (let ((s (match-string 1)))
6883 (replace-match " |")
6884 (goto-char (match-beginning 0))
6885 (org-table-next-row)
6886 (insert (org-trim s) " ")
6887 (org-table-align))))))
6888
6889 (defun org-trim (s)
6890 "Remove whitespace at beginning and end of string."
6891 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6892 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6893 s)
6894
6895 (defun org-wrap (string &optional width lines)
6896 "Wrap string to either a number of lines, or a width in characters.
6897 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6898 that costs. If there is a word longer than WIDTH, the text is actually
6899 wrapped to the length of that word.
6900 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6901 many lines, whatever width that takes.
6902 The return value is a list of lines, without newlines at the end."
6903 (let* ((words (org-split-string string "[ \t\n]+"))
6904 (maxword (apply 'max (mapcar 'length words)))
6905 w ll)
6906 (cond (width
6907 (org-do-wrap words (max maxword width)))
6908 (lines
6909 (setq w maxword)
6910 (setq ll (org-do-wrap words maxword))
6911 (if (<= (length ll) lines)
6912 ll
6913 (setq ll words)
6914 (while (> (length ll) lines)
6915 (setq w (1+ w))
6916 (setq ll (org-do-wrap words w)))
6917 ll))
6918 (t (error "Cannot wrap this")))))
6919
6920
6921 (defun org-do-wrap (words width)
6922 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6923 (let (lines line)
6924 (while words
6925 (setq line (pop words))
6926 (while (and words (< (+ (length line) (length (car words))) width))
6927 (setq line (concat line " " (pop words))))
6928 (setq lines (push line lines)))
6929 (nreverse lines)))
6930
6931 ;; FIXME: I think I can make this more efficient
6932 (defun org-split-string (string &optional separators)
6933 "Splits STRING into substrings at SEPARATORS.
6934 No empty strings are returned if there are matches at the beginning
6935 and end of string."
6936 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6937 (start 0)
6938 notfirst
6939 (list nil))
6940 (while (and (string-match rexp string
6941 (if (and notfirst
6942 (= start (match-beginning 0))
6943 (< start (length string)))
6944 (1+ start) start))
6945 (< (match-beginning 0) (length string)))
6946 (setq notfirst t)
6947 (or (eq (match-beginning 0) 0)
6948 (and (eq (match-beginning 0) (match-end 0))
6949 (eq (match-beginning 0) start))
6950 (setq list
6951 (cons (substring string start (match-beginning 0))
6952 list)))
6953 (setq start (match-end 0)))
6954 (or (eq start (length string))
6955 (setq list
6956 (cons (substring string start)
6957 list)))
6958 (nreverse list)))
6959
6960 (defun org-table-add-invisible-to-vertical-lines ()
6961 "Add an `invisible' property to vertical lines of current table."
6962 (interactive)
6963 (let* ((beg (org-table-begin))
6964 (end (org-table-end))
6965 (end1))
6966 (save-excursion
6967 (goto-char beg)
6968 (while (< (point) end)
6969 (setq end1 (point-at-eol))
6970 (if (looking-at org-table-dataline-regexp)
6971 (while (re-search-forward "|" end1 t)
6972 (add-text-properties (1- (point)) (point)
6973 '(invisible org-table)))
6974 (while (re-search-forward "[+|]" end1 t)
6975 (add-text-properties (1- (point)) (point)
6976 '(invisible org-table))))
6977 (beginning-of-line 2)))))
6978
6979 (defun org-table-toggle-vline-visibility (&optional arg)
6980 "Toggle the visibility of table vertical lines.
6981 The effect is immediate and on all tables in the file.
6982 With prefix ARG, make lines invisible when ARG is positive, make lines
6983 visible when ARG is not positive"
6984 (interactive "P")
6985 (let ((action (cond
6986 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6987 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6988 (t (if (org-in-invisibility-spec-p '(org-table))
6989 'off
6990 'on)))))
6991 (if (eq action 'off)
6992 (progn
6993 (org-remove-from-invisibility-spec '(org-table))
6994 (org-table-map-tables 'org-table-align)
6995 (message "Vertical table lines visible")
6996 (if (org-at-table-p)
6997 (org-table-align)))
6998 (org-add-to-invisibility-spec '(org-table))
6999 (org-table-map-tables 'org-table-align)
7000 (message "Vertical table lines invisible"))
7001 (redraw-frame (selected-frame))))
7002
7003 (defun org-table-map-tables (function)
7004 "Apply FUNCTION to the start of all tables in the buffer."
7005 (save-excursion
7006 (save-restriction
7007 (widen)
7008 (goto-char (point-min))
7009 (while (re-search-forward org-table-any-line-regexp nil t)
7010 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7011 (beginning-of-line 1)
7012 (if (looking-at org-table-line-regexp)
7013 (save-excursion (funcall function)))
7014 (re-search-forward org-table-any-border-regexp nil 1)))))
7015
7016 (defun org-table-sum (&optional beg end nlast)
7017 "Sum numbers in region of current table column.
7018 The result will be displayed in the echo area, and will be available
7019 as kill to be inserted with \\[yank].
7020
7021 If there is an active region, it is interpreted as a rectangle and all
7022 numbers in that rectangle will be summed. If there is no active
7023 region and point is located in a table column, sum all numbers in that
7024 column.
7025
7026 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7027 numbers are assumed to be times as well (in decimal hours) and the
7028 numbers are added as such.
7029
7030 If NLAST is a number, only the NLAST fields will actually be summed."
7031 (interactive)
7032 (save-excursion
7033 (let (col (timecnt 0) diff h m s org-table-clip)
7034 (cond
7035 ((and beg end)) ; beg and end given explicitly
7036 ((org-region-active-p)
7037 (setq beg (region-beginning) end (region-end)))
7038 (t
7039 (setq col (org-table-current-column))
7040 (goto-char (org-table-begin))
7041 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7042 (error "No table data"))
7043 (org-table-goto-column col)
7044 ;not needed? (skip-chars-backward "^|")
7045 (setq beg (point))
7046 (goto-char (org-table-end))
7047 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7048 (error "No table data"))
7049 (org-table-goto-column col)
7050 ;not needed? (skip-chars-forward "^|")
7051 (setq end (point))))
7052 (let* ((items (apply 'append (org-table-copy-region beg end)))
7053 (items1 (cond ((not nlast) items)
7054 ((>= nlast (length items)) items)
7055 (t (setq items (reverse items))
7056 (setcdr (nthcdr (1- nlast) items) nil)
7057 (nreverse items))))
7058 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7059 items1)))
7060 (res (apply '+ numbers))
7061 (sres (if (= timecnt 0)
7062 (format "%g" res)
7063 (setq diff (* 3600 res)
7064 h (floor (/ diff 3600)) diff (mod diff 3600)
7065 m (floor (/ diff 60)) diff (mod diff 60)
7066 s diff)
7067 (format "%d:%02d:%02d" h m s))))
7068 (kill-new sres)
7069 (if (interactive-p)
7070 (message "%s"
7071 (substitute-command-keys
7072 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7073 (length numbers) sres))))
7074 sres))))
7075
7076 (defun org-table-get-number-for-summing (s)
7077 (let (n)
7078 (if (string-match "^ *|? *" s)
7079 (setq s (replace-match "" nil nil s)))
7080 (if (string-match " *|? *$" s)
7081 (setq s (replace-match "" nil nil s)))
7082 (setq n (string-to-number s))
7083 (cond
7084 ((and (string-match "0" s)
7085 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7086 ((string-match "\\`[ \t]+\\'" s) nil)
7087 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7088 (let ((h (string-to-number (or (match-string 1 s) "0")))
7089 (m (string-to-number (or (match-string 2 s) "0")))
7090 (s (string-to-number (or (match-string 4 s) "0"))))
7091 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7092 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7093 ((equal n 0) nil)
7094 (t n))))
7095
7096 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7097 "Get a calc vector from a column, accorting to desctiptor DESC.
7098 Optional arguments TBEG and COL can give the beginning of the table and
7099 the current column, to avoid unnecessary parsing."
7100 (save-excursion
7101 (or tbeg (setq tbeg (org-table-begin)))
7102 (or col (setq col (org-table-current-column)))
7103 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7104 (cond
7105 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7106 (setq n1 (- (match-end 1) (match-beginning 1)))
7107 (if (match-beginning 3)
7108 (setq n2 (- (match-end 2) (match-beginning 3))))
7109 (setq n (if n2 (max n1 n2) n1))
7110 (setq n1 (if n2 (min n1 n2)))
7111 (setq nn n)
7112 (while (and (> nn 0)
7113 (re-search-backward org-table-hline-regexp tbeg t))
7114 (push (org-current-line) hline-list)
7115 (setq nn (1- nn)))
7116 (setq hline-list (nreverse hline-list))
7117 (goto-line (nth (1- n) hline-list))
7118 (when (re-search-forward org-table-dataline-regexp)
7119 (org-table-goto-column col)
7120 (setq beg (point)))
7121 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7122 (when (re-search-backward org-table-dataline-regexp)
7123 (org-table-goto-column col)
7124 (setq end (point)))
7125 (setq l (apply 'append (org-table-copy-region beg end)))
7126 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7127 (if (equal x "") "0" x))
7128 l ",") "]"))
7129 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7130 (setq n1 (string-to-number (match-string 1 desc))
7131 n2 (string-to-number (match-string 2 desc)))
7132 (beginning-of-line 1)
7133 (save-excursion
7134 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7135 (org-table-goto-column col)
7136 (setq beg (point))))
7137 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7138 (org-table-goto-column col)
7139 (setq end (point)))
7140 (setq l (apply 'append (org-table-copy-region beg end)))
7141 (concat "[" (mapconcat
7142 (lambda (x) (setq x (org-trim x))
7143 (if (equal x "") "0" x))
7144 l ",") "]"))
7145 ((string-match "\\([0-9]+\\)" desc)
7146 (beginning-of-line 1)
7147 (when (re-search-backward org-table-dataline-regexp tbeg t
7148 (string-to-number (match-string 0 desc)))
7149 (org-table-goto-column col)
7150 (org-trim (org-table-get-field))))))))
7151
7152 (defvar org-table-formula-history nil)
7153
7154 (defvar org-table-column-names nil
7155 "Alist with column names, derived from the `!' line.")
7156 (defvar org-table-column-name-regexp nil
7157 "Regular expression matching the current column names.")
7158 (defvar org-table-local-parameters nil
7159 "Alist with parameter names, derived from the `$' line.")
7160 (defvar org-table-named-field-locations nil
7161 "Alist with locations of named fields.")
7162
7163 (defun org-table-get-formula (&optional equation named)
7164 "Read a formula from the minibuffer, offer stored formula as default."
7165 (let* ((name (car (rassoc (list (org-current-line)
7166 (org-table-current-column))
7167 org-table-named-field-locations)))
7168 (scol (if named
7169 (if name name
7170 (error "Not in a named field"))
7171 (int-to-string (org-table-current-column))))
7172 (dummy (and name (not named)
7173 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7174 (error "Abort")))
7175 (org-table-may-need-update nil)
7176 (stored-list (org-table-get-stored-formulas))
7177 (stored (cdr (assoc scol stored-list)))
7178 (eq (cond
7179 ((and stored equation (string-match "^ *=? *$" equation))
7180 stored)
7181 ((stringp equation)
7182 equation)
7183 (t (read-string
7184 (format "%s formula $%s=" (if named "Field" "Column") scol)
7185 (or stored "") 'org-table-formula-history
7186 ;stored
7187 ))))
7188 mustsave)
7189 (when (not (string-match "\\S-" eq))
7190 ;; remove formula
7191 (setq stored-list (delq (assoc scol stored-list) stored-list))
7192 (org-table-store-formulas stored-list)
7193 (error "Formula removed"))
7194 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7195 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7196 (if (and name (not named))
7197 ;; We set the column equation, delete the named one.
7198 (setq stored-list (delq (assoc name stored-list) stored-list)
7199 mustsave t))
7200 (if stored
7201 (setcdr (assoc scol stored-list) eq)
7202 (setq stored-list (cons (cons scol eq) stored-list)))
7203 (if (or mustsave (not (equal stored eq)))
7204 (org-table-store-formulas stored-list))
7205 eq))
7206
7207 (defun org-table-store-formulas (alist)
7208 "Store the list of formulas below the current table."
7209 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7210 (save-excursion
7211 (goto-char (org-table-end))
7212 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7213 (delete-region (point) (match-end 0)))
7214 (insert "#+TBLFM: "
7215 (mapconcat (lambda (x)
7216 (concat "$" (car x) "=" (cdr x)))
7217 alist "::")
7218 "\n")))
7219
7220 (defun org-table-get-stored-formulas ()
7221 "Return an alist with the t=stored formulas directly after current table."
7222 (interactive)
7223 (let (scol eq eq-alist strings string seen)
7224 (save-excursion
7225 (goto-char (org-table-end))
7226 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7227 (setq strings (org-split-string (match-string 2) " *:: *"))
7228 (while (setq string (pop strings))
7229 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7230 (setq scol (match-string 1 string)
7231 eq (match-string 2 string)
7232 eq-alist (cons (cons scol eq) eq-alist))
7233 (if (member scol seen)
7234 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7235 (push scol seen))))))
7236 (nreverse eq-alist)))
7237
7238 (defun org-table-modify-formulas (action &rest columns)
7239 "Modify the formulas stored below the current table.
7240 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7241 expected, for the other action only a single column number is needed."
7242 (let ((list (org-table-get-stored-formulas))
7243 (nmax (length (org-split-string
7244 (buffer-substring (point-at-bol) (point-at-eol))
7245 "|")))
7246 col col1 col2 scol si sc1 sc2)
7247 (cond
7248 ((null list)) ; No action needed if there are no stored formulas
7249 ((eq action 'remove)
7250 (setq col (car columns)
7251 scol (int-to-string col))
7252 (org-table-replace-in-formulas list scol "INVALID")
7253 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7254 (loop for i from (1+ col) upto nmax by 1 do
7255 (setq si (int-to-string i))
7256 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7257 (if (assoc si list) (setcar (assoc si list)
7258 (int-to-string (1- i))))))
7259 ((eq action 'insert)
7260 (setq col (car columns))
7261 (loop for i from nmax downto col by 1 do
7262 (setq si (int-to-string i))
7263 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7264 (if (assoc si list) (setcar (assoc si list)
7265 (int-to-string (1+ i))))))
7266 ((eq action 'swap)
7267 (setq col1 (car columns) col2 (nth 1 columns)
7268 sc1 (int-to-string col1) sc2 (int-to-string col2))
7269 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7270 (org-table-replace-in-formulas list sc1 "ZqZ")
7271 (org-table-replace-in-formulas list sc2 sc1)
7272 (org-table-replace-in-formulas list "ZqZ" sc2)
7273 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7274 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7275 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7276 (t (error "Invalid action in `org-table-modify-formulas'")))
7277 (if list (org-table-store-formulas list))))
7278
7279 (defun org-table-replace-in-formulas (list s1 s2)
7280 (let (elt re s)
7281 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7282 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7283 re (concat (regexp-quote s1) "\\>"))
7284 (while (setq elt (pop list))
7285 (setq s (cdr elt))
7286 (while (string-match re s)
7287 (setq s (replace-match s2 t t s)))
7288 (setcdr elt s))))
7289
7290 (defun org-table-get-specials ()
7291 "Get the column nmaes and local parameters for this table."
7292 (save-excursion
7293 (let ((beg (org-table-begin)) (end (org-table-end))
7294 names name fields fields1 field cnt c v line col)
7295 (setq org-table-column-names nil
7296 org-table-local-parameters nil
7297 org-table-named-field-locations nil)
7298 (goto-char beg)
7299 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7300 (setq names (org-split-string (match-string 1) " *| *")
7301 cnt 1)
7302 (while (setq name (pop names))
7303 (setq cnt (1+ cnt))
7304 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7305 (push (cons name (int-to-string cnt)) org-table-column-names))))
7306 (setq org-table-column-names (nreverse org-table-column-names))
7307 (setq org-table-column-name-regexp
7308 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7309 (goto-char beg)
7310 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7311 (setq fields (org-split-string (match-string 1) " *| *"))
7312 (while (setq field (pop fields))
7313 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7314 (push (cons (match-string 1 field) (match-string 2 field))
7315 org-table-local-parameters))))
7316 (goto-char beg)
7317 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7318 (setq c (match-string 1)
7319 fields (org-split-string (match-string 2) " *| *"))
7320 (save-excursion
7321 (beginning-of-line (if (equal c "_") 2 0))
7322 (setq line (org-current-line) col 1)
7323 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7324 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7325 (while (and fields1 (setq field (pop fields)))
7326 (setq v (pop fields1) col (1+ col))
7327 (when (and (stringp field) (stringp v)
7328 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7329 (push (cons field v) org-table-local-parameters)
7330 (push (list field line col) org-table-named-field-locations)))))))
7331
7332 (defun org-this-word ()
7333 ;; Get the current word
7334 (save-excursion
7335 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7336 (end (progn (skip-chars-forward "^ \t\n") (point))))
7337 (buffer-substring-no-properties beg end))))
7338
7339 (defun org-table-maybe-eval-formula ()
7340 "Check if the current field starts with \"=\" or \":=\".
7341 If yes, store the formula and apply it."
7342 ;; We already know we are in a table. Get field will only return a formula
7343 ;; when appropriate. It might return a separator line, but no problem.
7344 (when org-table-formula-evaluate-inline
7345 (let* ((field (org-trim (or (org-table-get-field) "")))
7346 named eq)
7347 (when (string-match "^:?=\\(.*\\)" field)
7348 (setq named (equal (string-to-char field) ?:)
7349 eq (match-string 1 field))
7350 (if (fboundp 'calc-eval)
7351 (org-table-eval-formula (if named '(4) nil) eq))))))
7352
7353 (defvar org-recalc-commands nil
7354 "List of commands triggering the reccalculation of a line.
7355 Will be filled automatically during use.")
7356
7357 (defvar org-recalc-marks
7358 '((" " . "Unmarked: no special line, no automatic recalculation")
7359 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7360 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7361 ("!" . "Column name definition line. Reference in formula as $name.")
7362 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7363 ("_" . "Names for values in row below this one.")
7364 ("^" . "Names for values in row above this one.")))
7365
7366 (defun org-table-rotate-recalc-marks (&optional newchar)
7367 "Rotate the recalculation mark in the first column.
7368 If in any row, the first field is not consistent with a mark,
7369 insert a new column for the makers.
7370 When there is an active region, change all the lines in the region,
7371 after prompting for the marking character.
7372 After each change, a message will be displayed indication the meaning
7373 of the new mark."
7374 (interactive)
7375 (unless (org-at-table-p) (error "Not at a table"))
7376 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7377 (beg (org-table-begin))
7378 (end (org-table-end))
7379 (l (org-current-line))
7380 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7381 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7382 (have-col
7383 (save-excursion
7384 (goto-char beg)
7385 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7386 (col (org-table-current-column))
7387 (forcenew (car (assoc newchar org-recalc-marks)))
7388 epos new)
7389 (when l1
7390 (message "Change region to what mark? Type # * ! $ or SPC: ")
7391 (setq newchar (char-to-string (read-char-exclusive))
7392 forcenew (car (assoc newchar org-recalc-marks))))
7393 (if (and newchar (not forcenew))
7394 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7395 newchar))
7396 (if l1 (goto-line l1))
7397 (save-excursion
7398 (beginning-of-line 1)
7399 (unless (looking-at org-table-dataline-regexp)
7400 (error "Not at a table data line")))
7401 (unless have-col
7402 (org-table-goto-column 1)
7403 (org-table-insert-column)
7404 (org-table-goto-column (1+ col)))
7405 (setq epos (point-at-eol))
7406 (save-excursion
7407 (beginning-of-line 1)
7408 (org-table-get-field
7409 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7410 (concat " "
7411 (setq new (or forcenew
7412 (cadr (member (match-string 1) marks))))
7413 " ")
7414 " # ")))
7415 (if (and l1 l2)
7416 (progn
7417 (goto-line l1)
7418 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7419 (and (looking-at org-table-dataline-regexp)
7420 (org-table-get-field 1 (concat " " new " "))))
7421 (goto-line l1)))
7422 (if (not (= epos (point-at-eol))) (org-table-align))
7423 (goto-line l)
7424 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7425
7426 (defun org-table-maybe-recalculate-line ()
7427 "Recompute the current line if marked for it, and if we haven't just done it."
7428 (interactive)
7429 (and org-table-allow-automatic-line-recalculation
7430 (not (and (memq last-command org-recalc-commands)
7431 (equal org-last-recalc-line (org-current-line))))
7432 (save-excursion (beginning-of-line 1)
7433 (looking-at org-table-auto-recalculate-regexp))
7434 (fboundp 'calc-eval)
7435 (org-table-recalculate) t))
7436
7437 (defvar org-table-formula-debug nil
7438 "Non-nil means, debug table formulas.
7439 When nil, simply write \"#ERROR\" in corrupted fields.")
7440
7441 (defvar modes)
7442 (defsubst org-set-calc-mode (var &optional value)
7443 (if (stringp var)
7444 (setq var (assoc var '(("D" calc-angle-mode deg)
7445 ("R" calc-angle-mode rad)
7446 ("F" calc-prefer-frac t)
7447 ("S" calc-symbolic-mode t)))
7448 value (nth 2 var) var (nth 1 var)))
7449 (if (memq var modes)
7450 (setcar (cdr (memq var modes)) value)
7451 (cons var (cons value modes)))
7452 modes)
7453
7454 (defun org-table-eval-formula (&optional arg equation
7455 suppress-align suppress-const
7456 suppress-store)
7457 "Replace the table field value at the cursor by the result of a calculation.
7458
7459 This function makes use of Dave Gillespie's calc package, in my view the
7460 most exciting program ever written for GNU Emacs. So you need to have calc
7461 installed in order to use this function.
7462
7463 In a table, this command replaces the value in the current field with the
7464 result of a formula. It also installes the formula as the \"current\" column
7465 formula, by storing it in a special line below the table. When called
7466 with a `C-u' prefix, the current field must ba a named field, and the
7467 formula is installed as valid in only this specific field.
7468
7469 When called, the command first prompts for a formula, which is read in
7470 the minibuffer. Previously entered formulas are available through the
7471 history list, and the last used formula is offered as a default.
7472 These stored formulas are adapted correctly when moving, inserting, or
7473 deleting columns with the corresponding commands.
7474
7475 The formula can be any algebraic expression understood by the calc package.
7476 For details, see the Org-mode manual.
7477
7478 This function can also be called from Lisp programs and offers
7479 additional Arguments: EQUATION can be the formula to apply. If this
7480 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7481 used to speed-up recursive calls by by-passing unnecessary aligns.
7482 SUPPRESS-CONST suppresses the interpretation of constants in the
7483 formula, assuming that this has been done already outside the fuction.
7484 SUPPRESS-STORE means the formula should not be stored, either because
7485 it is already stored, or because it is a modified equation that should
7486 not overwrite the stored one."
7487 (interactive "P")
7488 (require 'calc)
7489 (org-table-check-inside-data-field)
7490 (org-table-get-specials)
7491 (let* (fields
7492 (ndown (if (integerp arg) arg 1))
7493 (org-table-automatic-realign nil)
7494 (case-fold-search nil)
7495 (down (> ndown 1))
7496 (formula (if (and equation suppress-store)
7497 equation
7498 (org-table-get-formula equation (equal arg '(4)))))
7499 (n0 (org-table-current-column))
7500 (modes (copy-sequence org-calc-default-modes))
7501 n form fmt x ev orig c)
7502 ;; Parse the format string. Since we have a lot of modes, this is
7503 ;; a lot of work. However, I think calc still uses most of the time.
7504 (if (string-match ";" formula)
7505 (let ((tmp (org-split-string formula ";")))
7506 (setq formula (car tmp)
7507 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7508 (nth 1 tmp)))
7509 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7510 (setq c (string-to-char (match-string 1 fmt))
7511 n (string-to-number (or (match-string 1 fmt) "")))
7512 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7513 (setq modes (org-set-calc-mode
7514 'calc-float-format
7515 (list (cdr (assoc c '((?n. float) (?f. fix)
7516 (?s. sci) (?e. eng))))
7517 n))))
7518 (setq fmt (replace-match "" t t fmt)))
7519 (while (string-match "[DRFS]" fmt)
7520 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7521 (setq fmt (replace-match "" t t fmt)))
7522 (unless (string-match "\\S-" fmt)
7523 (setq fmt nil))))
7524 (if (and (not suppress-const) org-table-formula-use-constants)
7525 (setq formula (org-table-formula-substitute-names formula)))
7526 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7527 (while (> ndown 0)
7528 (setq fields (org-split-string
7529 (buffer-substring
7530 (point-at-bol) (point-at-eol)) " *| *"))
7531 (if org-table-formula-numbers-only
7532 (setq fields (mapcar
7533 (lambda (x) (number-to-string (string-to-number x)))
7534 fields)))
7535 (setq ndown (1- ndown))
7536 (setq form (copy-sequence formula))
7537 ;; Insert the references to fields in same row
7538 (while (string-match "\\$\\([0-9]+\\)?" form)
7539 (setq n (if (match-beginning 1)
7540 (string-to-number (match-string 1 form))
7541 n0)
7542 x (nth (1- n) fields))
7543 (unless x (error "Invalid field specifier \"%s\""
7544 (match-string 0 form)))
7545 (if (equal x "") (setq x "0"))
7546 (setq form (replace-match (concat "(" x ")") t t form)))
7547 ;; Insert ranges in current column
7548 (while (string-match "\\&[-I0-9]+" form)
7549 (setq form (replace-match
7550 (save-match-data
7551 (org-table-get-vertical-vector (match-string 0 form)
7552 nil n0))
7553 t t form)))
7554 (setq ev (calc-eval (cons form modes)
7555 (if org-table-formula-numbers-only 'num)))
7556
7557 (when org-table-formula-debug
7558 (with-output-to-temp-buffer "*Help*"
7559 (princ (format "Substitution history of formula
7560 Orig: %s
7561 $xyz-> %s
7562 $1-> %s\n" orig formula form))
7563 (if (listp ev)
7564 (princ (format " %s^\nError: %s"
7565 (make-string (car ev) ?\-) (nth 1 ev)))
7566 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7567 ev (or fmt "NONE")
7568 (if fmt (format fmt (string-to-number ev)) ev)))))
7569 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7570 (unless (and (interactive-p) (not ndown))
7571 (unless (let (inhibit-redisplay)
7572 (y-or-n-p "Debugging Formula. Continue to next? "))
7573 (org-table-align)
7574 (error "Abort"))
7575 (delete-window (get-buffer-window "*Help*"))
7576 (message "")))
7577 (if (listp ev) (setq fmt nil ev "#ERROR"))
7578 (org-table-justify-field-maybe
7579 (if fmt (format fmt (string-to-number ev)) ev))
7580 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7581 (call-interactively 'org-return)
7582 (setq ndown 0)))
7583 (and down (org-table-maybe-recalculate-line))
7584 (or suppress-align (and org-table-may-need-update
7585 (org-table-align)))))
7586
7587 (defun org-table-recalculate (&optional all noalign)
7588 "Recalculate the current table line by applying all stored formulas."
7589 (interactive "P")
7590 (or (memq this-command org-recalc-commands)
7591 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7592 (unless (org-at-table-p) (error "Not at a table"))
7593 (org-table-get-specials)
7594 (let* ((eqlist (sort (org-table-get-stored-formulas)
7595 (lambda (a b) (string< (car a) (car b)))))
7596 (inhibit-redisplay t)
7597 (line-re org-table-dataline-regexp)
7598 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7599 (thiscol (org-table-current-column))
7600 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7601 ;; Insert constants in all formulas
7602 (setq eqlist
7603 (mapcar (lambda (x)
7604 (setcdr x (org-table-formula-substitute-names (cdr x)))
7605 x)
7606 eqlist))
7607 ;; Split the equation list
7608 (while (setq eq (pop eqlist))
7609 (if (<= (string-to-char (car eq)) ?9)
7610 (push eq eqlnum)
7611 (push eq eqlname)))
7612 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7613 (if all
7614 (progn
7615 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7616 (goto-char (setq beg (org-table-begin)))
7617 (if (re-search-forward org-table-calculate-mark-regexp end t)
7618 ;; This is a table with marked lines, only compute selected lines
7619 (setq line-re org-table-recalculate-regexp)
7620 ;; Move forward to the first non-header line
7621 (if (and (re-search-forward org-table-dataline-regexp end t)
7622 (re-search-forward org-table-hline-regexp end t)
7623 (re-search-forward org-table-dataline-regexp end t))
7624 (setq beg (match-beginning 0))
7625 nil))) ;; just leave beg where it is
7626 (setq beg (point-at-bol)
7627 end (move-marker (make-marker) (1+ (point-at-eol)))))
7628 (goto-char beg)
7629 (and all (message "Re-applying formulas to full table..."))
7630 (while (re-search-forward line-re end t)
7631 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7632 ;; Unprotected line, recalculate
7633 (and all (message "Re-applying formulas to full table...(line %d)"
7634 (setq cnt (1+ cnt))))
7635 (setq org-last-recalc-line (org-current-line))
7636 (setq eql eqlnum)
7637 (while (setq entry (pop eql))
7638 (goto-line org-last-recalc-line)
7639 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7640 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7641 (goto-line thisline)
7642 (org-table-goto-column thiscol)
7643 (or noalign (and org-table-may-need-update (org-table-align))
7644 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7645 ;; Now do the names fields
7646 (while (setq eq (pop eqlname))
7647 (setq name (car eq)
7648 a (assoc name org-table-named-field-locations))
7649 (when a
7650 (message "Re-applying formula to named field: %s" name)
7651 (goto-line (nth 1 a))
7652 (org-table-goto-column (nth 2 a))
7653 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7654 ;; back to initial position
7655 (goto-line thisline)
7656 (org-table-goto-column thiscol)
7657 (or noalign (and org-table-may-need-update (org-table-align))
7658 (and all (message "Re-applying formulas...done")))))
7659
7660 (defun org-table-formula-substitute-names (f)
7661 "Replace $const with values in string F."
7662 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7663 ;; First, check for column names
7664 (while (setq start (string-match org-table-column-name-regexp f start))
7665 (setq start (1+ start))
7666 (setq a (assoc (match-string 1 f) org-table-column-names))
7667 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7668 ;; Expand ranges to vectors
7669 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7670 (setq n1 (string-to-number (match-string 1 f))
7671 n2 (string-to-number (match-string 2 f))
7672 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7673 s (concat "[($" (number-to-string (1- nn1)) ")"))
7674 (loop for i from nn1 upto nn2 do
7675 (setq s (concat s ",($" (int-to-string i) ")")))
7676 (setq s (concat s "]"))
7677 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7678 (setq f (replace-match s t t f)))
7679 ;; Parameters and constants
7680 (setq start 0)
7681 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7682 (setq start (1+ start))
7683 (if (setq a (save-match-data
7684 (org-table-get-constant (match-string 1 f))))
7685 (setq f (replace-match (concat "(" a ")") t t f))))
7686 (if org-table-formula-debug
7687 (put-text-property 0 (length f) :orig-formula f1 f))
7688 f))
7689
7690 (defun org-table-get-constant (const)
7691 "Find the value for a parameter or constant in a formula.
7692 Parameters get priority."
7693 (or (cdr (assoc const org-table-local-parameters))
7694 (cdr (assoc const org-table-formula-constants))
7695 (and (fboundp 'constants-get) (constants-get const))
7696 "#UNDEFINED_NAME"))
7697
7698 (defvar org-edit-formulas-map (make-sparse-keymap))
7699 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7700 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7701 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7702
7703 (defvar org-pos)
7704 (defvar org-window-configuration)
7705
7706 (defun org-table-edit-formulas ()
7707 "Edit the formulas of the current table in a separate buffer."
7708 (interactive)
7709 (unless (org-at-table-p)
7710 (error "Not at a table"))
7711 (org-table-get-specials)
7712 (let ((eql (org-table-get-stored-formulas))
7713 (pos (move-marker (make-marker) (point)))
7714 (wc (current-window-configuration))
7715 entry loc s)
7716 (switch-to-buffer-other-window "*Edit Formulas*")
7717 (erase-buffer)
7718 (fundamental-mode)
7719 (set (make-local-variable 'org-pos) pos)
7720 (set (make-local-variable 'org-window-configuration) wc)
7721 (use-local-map org-edit-formulas-map)
7722 (setq s "# Edit formulas and finish with `C-c C-c'.
7723 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7724 # Use `C-c ?' to get information about $name at point.
7725 # To cancel editing, press `C-c C-q'.\n")
7726 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7727 (insert s)
7728 (while (setq entry (pop eql))
7729 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7730 (setq s (format "# Named formula, referring to column %d in line %d\n"
7731 (nth 2 loc) (nth 1 loc)))
7732 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7733 (insert s))
7734 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7735 (remove-text-properties 0 (length s) '(face nil) s)
7736 (insert s))
7737 (goto-char (point-min))
7738 (message "Edit formulas and finish with `C-c C-c'.")))
7739
7740 (defun org-show-variable ()
7741 "Show the location/value of the $ expression at point."
7742 (interactive)
7743 (let (var (pos org-pos) (win (selected-window)) e)
7744 (save-excursion
7745 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7746 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7747 (setq var (match-string 1))
7748 (error "No variable at point")))
7749 (cond
7750 ((setq e (assoc var org-table-named-field-locations))
7751 (switch-to-buffer-other-window (marker-buffer pos))
7752 (goto-line (nth 1 e))
7753 (org-table-goto-column (nth 2 e))
7754 (select-window win)
7755 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7756 ((setq e (assoc var org-table-column-names))
7757 (switch-to-buffer-other-window (marker-buffer pos))
7758 (goto-char pos)
7759 (goto-char (org-table-begin))
7760 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7761 (org-table-end) t)
7762 (progn
7763 (goto-char (match-beginning 1))
7764 (message "Named column (column %s)" (cdr e)))
7765 (error "Column name not found"))
7766 (select-window win))
7767 ((string-match "^[0-9]$" var)
7768 ;; column number
7769 (switch-to-buffer-other-window (marker-buffer pos))
7770 (goto-char pos)
7771 (goto-char (org-table-begin))
7772 (recenter 1)
7773 (if (re-search-forward org-table-dataline-regexp
7774 (org-table-end) t)
7775 (progn
7776 (goto-char (match-beginning 0))
7777 (org-table-goto-column (string-to-number var))
7778 (message "Column %s" var))
7779 (error "Column name not found"))
7780 (select-window win))
7781 ((setq e (assoc var org-table-local-parameters))
7782 (switch-to-buffer-other-window (marker-buffer pos))
7783 (goto-char pos)
7784 (goto-char (org-table-begin))
7785 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7786 (progn
7787 (goto-char (match-beginning 1))
7788 (message "Local parameter."))
7789 (error "Parameter not found"))
7790 (select-window win))
7791 (t
7792 (cond
7793 ((setq e (assoc var org-table-formula-constants))
7794 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7795 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7796 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7797 (t (error "Undefined name $%s" var)))))))
7798
7799 (defun org-finish-edit-formulas (&optional arg)
7800 "Parse the buffer for formula definitions and install them.
7801 With prefix ARG, apply the new formulas to the table."
7802 (interactive "P")
7803 (let ((pos org-pos) eql)
7804 (goto-char (point-min))
7805 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7806 (push (cons (match-string 1) (match-string 2)) eql))
7807 (set-window-configuration org-window-configuration)
7808 (select-window (get-buffer-window (marker-buffer pos)))
7809 (goto-char pos)
7810 (unless (org-at-table-p)
7811 (error "Lost table position - cannot install formulae"))
7812 (org-table-store-formulas eql)
7813 (move-marker pos nil)
7814 (kill-buffer "*Edit Formulas*")
7815 (if arg
7816 (org-table-recalculate 'all)
7817 (message "New formulas installed - press C-u C-c C-c to apply."))))
7818
7819 (defun org-abort-edit-formulas ()
7820 "Abort editing formulas, without installing the changes."
7821 (interactive)
7822 (let ((pos org-pos))
7823 (set-window-configuration org-window-configuration)
7824 (select-window (get-buffer-window (marker-buffer pos)))
7825 (goto-char pos)
7826 (message "Formula editing aborted without installing changes")))
7827
7828 ;;; The orgtbl minor mode
7829
7830 ;; Define a minor mode which can be used in other modes in order to
7831 ;; integrate the org-mode table editor.
7832
7833 ;; This is really a hack, because the org-mode table editor uses several
7834 ;; keys which normally belong to the major mode, for example the TAB and
7835 ;; RET keys. Here is how it works: The minor mode defines all the keys
7836 ;; necessary to operate the table editor, but wraps the commands into a
7837 ;; function which tests if the cursor is currently inside a table. If that
7838 ;; is the case, the table editor command is executed. However, when any of
7839 ;; those keys is used outside a table, the function uses `key-binding' to
7840 ;; look up if the key has an associated command in another currently active
7841 ;; keymap (minor modes, major mode, global), and executes that command.
7842 ;; There might be problems if any of the keys used by the table editor is
7843 ;; otherwise used as a prefix key.
7844
7845 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7846 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7847 ;; addresses this by checking explicitly for both bindings.
7848
7849 ;; The optimized version (see variable `orgtbl-optimized') takes over
7850 ;; all keys which are bound to `self-insert-command' in the *global map*.
7851 ;; Some modes bind other commands to simple characters, for example
7852 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7853 ;; active, this binding is ignored inside tables and replaced with a
7854 ;; modified self-insert.
7855
7856 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7857 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7858 In the optimized version, the table editor takes over all simple keys that
7859 normally just insert a character. In tables, the characters are inserted
7860 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7861 for empty fields). Outside tables, the correct binding of the keys is
7862 restored.
7863
7864 The default for this option is t if the optimized version is also used in
7865 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7866 this variable requires a restart of Emacs to become effective."
7867 :group 'org-table
7868 :type 'boolean)
7869
7870 (defvar orgtbl-mode nil
7871 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7872 table editor in arbitrary modes.")
7873 (make-variable-buffer-local 'orgtbl-mode)
7874
7875 (defvar orgtbl-mode-map (make-keymap)
7876 "Keymap for `orgtbl-mode'.")
7877
7878 ;;;###autoload
7879 (defun turn-on-orgtbl ()
7880 "Unconditionally turn on `orgtbl-mode'."
7881 (orgtbl-mode 1))
7882
7883 ;;;###autoload
7884 (defun orgtbl-mode (&optional arg)
7885 "The `org-mode' table editor as a minor mode for use in other modes."
7886 (interactive)
7887 (if (eq major-mode 'org-mode)
7888 ;; Exit without error, in case some hook functions calls this
7889 ;; by accident in org-mode.
7890 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7891 (setq orgtbl-mode
7892 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7893 (if orgtbl-mode
7894 (progn
7895 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7896 ;; Make sure we are first in minor-mode-map-alist
7897 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7898 (and c (setq minor-mode-map-alist
7899 (cons c (delq c minor-mode-map-alist)))))
7900 (set (make-local-variable (quote org-table-may-need-update)) t)
7901 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
7902 (add-hook 'before-change-functions 'org-before-change-function
7903 nil 'local)
7904 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7905 auto-fill-inhibit-regexp)
7906 (set (make-local-variable 'auto-fill-inhibit-regexp)
7907 (if auto-fill-inhibit-regexp
7908 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7909 "[ \t]*|"))
7910 (easy-menu-add orgtbl-mode-menu)
7911 (run-hooks 'orgtbl-mode-hook))
7912 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7913 (remove-hook 'before-change-functions 'org-before-change-function t)
7914 (easy-menu-remove orgtbl-mode-menu)
7915 (force-mode-line-update 'all))))
7916
7917 ;; Install it as a minor mode.
7918 (put 'orgtbl-mode :included t)
7919 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7920 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7921
7922 (defun orgtbl-make-binding (fun n &rest keys)
7923 "Create a function for binding in the table minor mode.
7924 FUN is the command to call inside a table. N is used to create a unique
7925 command name. KEYS are keys that should be checked in for a command
7926 to execute outside of tables."
7927 (eval
7928 (list 'defun
7929 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7930 '(arg)
7931 (concat "In tables, run `" (symbol-name fun) "'.\n"
7932 "Outside of tables, run the binding of `"
7933 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7934 "'.")
7935 '(interactive "p")
7936 (list 'if
7937 '(org-at-table-p)
7938 (list 'call-interactively (list 'quote fun))
7939 (list 'let '(orgtbl-mode)
7940 (list 'call-interactively
7941 (append '(or)
7942 (mapcar (lambda (k)
7943 (list 'key-binding k))
7944 keys)
7945 '('orgtbl-error))))))))
7946
7947 (defun orgtbl-error ()
7948 "Error when there is no default binding for a table key."
7949 (interactive)
7950 (error "This key is has no function outside tables"))
7951
7952 (defun orgtbl-setup ()
7953 "Setup orgtbl keymaps."
7954 (let ((nfunc 0)
7955 (bindings
7956 (list
7957 '([(meta shift left)] org-table-delete-column)
7958 '([(meta left)] org-table-move-column-left)
7959 '([(meta right)] org-table-move-column-right)
7960 '([(meta shift right)] org-table-insert-column)
7961 '([(meta shift up)] org-table-kill-row)
7962 '([(meta shift down)] org-table-insert-row)
7963 '([(meta up)] org-table-move-row-up)
7964 '([(meta down)] org-table-move-row-down)
7965 '("\C-c\C-w" org-table-cut-region)
7966 '("\C-c\M-w" org-table-copy-region)
7967 '("\C-c\C-y" org-table-paste-rectangle)
7968 '("\C-c-" org-table-insert-hline)
7969 ; '([(shift tab)] org-table-previous-field)
7970 '("\C-m" org-table-next-row)
7971 (list (org-key 'S-return) 'org-table-copy-down)
7972 '([(meta return)] org-table-wrap-region)
7973 '("\C-c\C-q" org-table-wrap-region)
7974 '("\C-c?" org-table-current-column)
7975 '("\C-c " org-table-blank-field)
7976 '("\C-c+" org-table-sum)
7977 '("\C-c|" org-table-toggle-vline-visibility)
7978 '("\C-c=" org-table-eval-formula)
7979 '("\C-c'" org-table-edit-formulas)
7980 '("\C-c*" org-table-recalculate)
7981 '([(control ?#)] org-table-rotate-recalc-marks)))
7982 elt key fun cmd)
7983 (while (setq elt (pop bindings))
7984 (setq nfunc (1+ nfunc))
7985 (setq key (car elt)
7986 fun (nth 1 elt)
7987 cmd (orgtbl-make-binding fun nfunc key))
7988 (define-key orgtbl-mode-map key cmd))
7989 ;; Special treatment needed for TAB and RET
7990 (define-key orgtbl-mode-map [(return)]
7991 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7992 (define-key orgtbl-mode-map "\C-m"
7993 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7994 (define-key orgtbl-mode-map [(tab)]
7995 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7996 (define-key orgtbl-mode-map "\C-i"
7997 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7998 (define-key orgtbl-mode-map "\C-i"
7999 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8000 (define-key orgtbl-mode-map "\C-c\C-c"
8001 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8002 (when orgtbl-optimized
8003 ;; If the user wants maximum table support, we need to hijack
8004 ;; some standard editing functions
8005 (org-remap orgtbl-mode-map
8006 'self-insert-command 'orgtbl-self-insert-command
8007 'delete-char 'orgtbl-delete-char
8008 'delete-backward-char 'orgtbl-delete-backward-char)
8009 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8010 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8011 '("OrgTbl"
8012 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8013 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8014 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8015 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8016 "--"
8017 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8018 ["Copy Field from Above"
8019 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8020 "--"
8021 ("Column"
8022 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8023 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8024 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8025 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8026 ("Row"
8027 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8028 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8029 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8030 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8031 "--"
8032 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8033 ("Rectangle"
8034 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c C-x M-w"]
8035 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-x C-w"]
8036 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-x C-y"]
8037 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
8038 "--"
8039 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8040 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8041 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8042 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8043 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8044 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8045 ["Sum Column/Rectangle" org-table-sum
8046 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8047 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8048 ["Debug Formulas"
8049 (setq org-table-formula-debug (not org-table-formula-debug))
8050 :style toggle :selected org-table-formula-debug]
8051 ))
8052 t)
8053
8054 (defun orgtbl-tab ()
8055 "Justification and field motion for `orgtbl-mode'."
8056 (interactive)
8057 (org-table-justify-field-maybe)
8058 (org-table-next-field))
8059
8060 (defun orgtbl-ret ()
8061 "Justification and field motion for `orgtbl-mode'."
8062 (interactive)
8063 (org-table-justify-field-maybe)
8064 (org-table-next-row))
8065
8066 (defun orgtbl-self-insert-command (N)
8067 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8068 If the cursor is in a table looking at whitespace, the whitespace is
8069 overwritten, and the table is not marked as requiring realignment."
8070 (interactive "p")
8071 (if (and (org-at-table-p)
8072 (or
8073 (and org-table-auto-blank-field
8074 (member last-command
8075 '(orgtbl-hijacker-command-100
8076 orgtbl-hijacker-command-101
8077 orgtbl-hijacker-command-102
8078 orgtbl-hijacker-command-103
8079 orgtbl-hijacker-command-104
8080 orgtbl-hijacker-command-105))
8081 (org-table-blank-field))
8082 t)
8083 (eq N 1)
8084 (looking-at "[^|\n]* +|"))
8085 (let (org-table-may-need-update)
8086 (goto-char (1- (match-end 0)))
8087 (delete-backward-char 1)
8088 (goto-char (match-beginning 0))
8089 (self-insert-command N))
8090 (setq org-table-may-need-update t)
8091 (let (orgtbl-mode)
8092 (call-interactively (key-binding (vector last-input-event))))))
8093
8094 (defun org-force-self-insert (N)
8095 "Needed to enforce self-insert under remapping."
8096 (interactive "p")
8097 (self-insert-command N))
8098
8099 (defun orgtbl-delete-backward-char (N)
8100 "Like `delete-backward-char', insert whitespace at field end in tables.
8101 When deleting backwards, in tables this function will insert whitespace in
8102 front of the next \"|\" separator, to keep the table aligned. The table will
8103 still be marked for re-alignment, because a narrow field may lead to a
8104 reduced column width."
8105 (interactive "p")
8106 (if (and (org-at-table-p)
8107 (eq N 1)
8108 (string-match "|" (buffer-substring (point-at-bol) (point)))
8109 (looking-at ".*?|"))
8110 (let ((pos (point)))
8111 (backward-delete-char N)
8112 (skip-chars-forward "^|")
8113 (insert " ")
8114 (goto-char (1- pos)))
8115 (delete-backward-char N)))
8116
8117 (defun orgtbl-delete-char (N)
8118 "Like `delete-char', but insert whitespace at field end in tables.
8119 When deleting characters, in tables this function will insert whitespace in
8120 front of the next \"|\" separator, to keep the table aligned. The table
8121 will still be marked for re-alignment, because a narrow field may lead to
8122 a reduced column width."
8123 (interactive "p")
8124 (if (and (org-at-table-p)
8125 (not (bolp))
8126 (not (= (char-after) ?|))
8127 (eq N 1))
8128 (if (looking-at ".*?|")
8129 (let ((pos (point)))
8130 (replace-match (concat
8131 (substring (match-string 0) 1 -1)
8132 " |"))
8133 (goto-char pos)))
8134 (delete-char N)))
8135
8136 ;;; Exporting
8137
8138 (defconst org-level-max 20)
8139
8140 (defun org-export-find-first-heading-line (list)
8141 "Remove all lines from LIST which are before the first headline."
8142 (let ((orig-list list)
8143 (re (concat "^" outline-regexp)))
8144 (while (and list
8145 (not (string-match re (car list))))
8146 (pop list))
8147 (or list orig-list)))
8148
8149 (defun org-skip-comments (lines)
8150 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8151 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8152 (re2 "^\\(\\*+\\)[ \t\n\r]")
8153 rtn line level)
8154 (while (setq line (pop lines))
8155 (cond
8156 ((and (string-match re1 line)
8157 (setq level (- (match-end 1) (match-beginning 1))))
8158 ;; Beginning of a COMMENT subtree. Skip it.
8159 (while (and (setq line (pop lines))
8160 (or (not (string-match re2 line))
8161 (> (- (match-end 1) (match-beginning 1)) level))))
8162 (setq lines (cons line lines)))
8163 ((string-match "^#" line)
8164 ;; an ordinary comment line
8165 )
8166 (t (setq rtn (cons line rtn)))))
8167 (nreverse rtn)))
8168
8169 ;; ASCII
8170
8171 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8172 "Characters for underlining headings in ASCII export.")
8173
8174 (defconst org-html-entities
8175 '(("nbsp")
8176 ("iexcl")
8177 ("cent")
8178 ("pound")
8179 ("curren")
8180 ("yen")
8181 ("brvbar")
8182 ("sect")
8183 ("uml")
8184 ("copy")
8185 ("ordf")
8186 ("laquo")
8187 ("not")
8188 ("shy")
8189 ("reg")
8190 ("macr")
8191 ("deg")
8192 ("plusmn")
8193 ("sup2")
8194 ("sup3")
8195 ("acute")
8196 ("micro")
8197 ("para")
8198 ("middot")
8199 ("odot"."o")
8200 ("star"."*")
8201 ("cedil")
8202 ("sup1")
8203 ("ordm")
8204 ("raquo")
8205 ("frac14")
8206 ("frac12")
8207 ("frac34")
8208 ("iquest")
8209 ("Agrave")
8210 ("Aacute")
8211 ("Acirc")
8212 ("Atilde")
8213 ("Auml")
8214 ("Aring") ("AA"."&Aring;")
8215 ("AElig")
8216 ("Ccedil")
8217 ("Egrave")
8218 ("Eacute")
8219 ("Ecirc")
8220 ("Euml")
8221 ("Igrave")
8222 ("Iacute")
8223 ("Icirc")
8224 ("Iuml")
8225 ("ETH")
8226 ("Ntilde")
8227 ("Ograve")
8228 ("Oacute")
8229 ("Ocirc")
8230 ("Otilde")
8231 ("Ouml")
8232 ("times")
8233 ("Oslash")
8234 ("Ugrave")
8235 ("Uacute")
8236 ("Ucirc")
8237 ("Uuml")
8238 ("Yacute")
8239 ("THORN")
8240 ("szlig")
8241 ("agrave")
8242 ("aacute")
8243 ("acirc")
8244 ("atilde")
8245 ("auml")
8246 ("aring")
8247 ("aelig")
8248 ("ccedil")
8249 ("egrave")
8250 ("eacute")
8251 ("ecirc")
8252 ("euml")
8253 ("igrave")
8254 ("iacute")
8255 ("icirc")
8256 ("iuml")
8257 ("eth")
8258 ("ntilde")
8259 ("ograve")
8260 ("oacute")
8261 ("ocirc")
8262 ("otilde")
8263 ("ouml")
8264 ("divide")
8265 ("oslash")
8266 ("ugrave")
8267 ("uacute")
8268 ("ucirc")
8269 ("uuml")
8270 ("yacute")
8271 ("thorn")
8272 ("yuml")
8273 ("fnof")
8274 ("Alpha")
8275 ("Beta")
8276 ("Gamma")
8277 ("Delta")
8278 ("Epsilon")
8279 ("Zeta")
8280 ("Eta")
8281 ("Theta")
8282 ("Iota")
8283 ("Kappa")
8284 ("Lambda")
8285 ("Mu")
8286 ("Nu")
8287 ("Xi")
8288 ("Omicron")
8289 ("Pi")
8290 ("Rho")
8291 ("Sigma")
8292 ("Tau")
8293 ("Upsilon")
8294 ("Phi")
8295 ("Chi")
8296 ("Psi")
8297 ("Omega")
8298 ("alpha")
8299 ("beta")
8300 ("gamma")
8301 ("delta")
8302 ("epsilon")
8303 ("varepsilon"."&epsilon;")
8304 ("zeta")
8305 ("eta")
8306 ("theta")
8307 ("iota")
8308 ("kappa")
8309 ("lambda")
8310 ("mu")
8311 ("nu")
8312 ("xi")
8313 ("omicron")
8314 ("pi")
8315 ("rho")
8316 ("sigmaf") ("varsigma"."&sigmaf;")
8317 ("sigma")
8318 ("tau")
8319 ("upsilon")
8320 ("phi")
8321 ("chi")
8322 ("psi")
8323 ("omega")
8324 ("thetasym") ("vartheta"."&thetasym;")
8325 ("upsih")
8326 ("piv")
8327 ("bull") ("bullet"."&bull;")
8328 ("hellip") ("dots"."&hellip;")
8329 ("prime")
8330 ("Prime")
8331 ("oline")
8332 ("frasl")
8333 ("weierp")
8334 ("image")
8335 ("real")
8336 ("trade")
8337 ("alefsym")
8338 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8339 ("uarr") ("uparrow"."&uarr;")
8340 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8341 ("darr")("downarrow"."&darr;")
8342 ("harr") ("leftrightarrow"."&harr;")
8343 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8344 ("lArr") ("Leftarrow"."&lArr;")
8345 ("uArr") ("Uparrow"."&uArr;")
8346 ("rArr") ("Rightarrow"."&rArr;")
8347 ("dArr") ("Downarrow"."&dArr;")
8348 ("hArr") ("Leftrightarrow"."&hArr;")
8349 ("forall")
8350 ("part") ("partial"."&part;")
8351 ("exist") ("exists"."&exist;")
8352 ("empty") ("emptyset"."&empty;")
8353 ("nabla")
8354 ("isin") ("in"."&isin;")
8355 ("notin")
8356 ("ni")
8357 ("prod")
8358 ("sum")
8359 ("minus")
8360 ("lowast") ("ast"."&lowast;")
8361 ("radic")
8362 ("prop") ("proptp"."&prop;")
8363 ("infin") ("infty"."&infin;")
8364 ("ang") ("angle"."&ang;")
8365 ("and") ("vee"."&and;")
8366 ("or") ("wedge"."&or;")
8367 ("cap")
8368 ("cup")
8369 ("int")
8370 ("there4")
8371 ("sim")
8372 ("cong") ("simeq"."&cong;")
8373 ("asymp")("approx"."&asymp;")
8374 ("ne") ("neq"."&ne;")
8375 ("equiv")
8376 ("le")
8377 ("ge")
8378 ("sub") ("subset"."&sub;")
8379 ("sup") ("supset"."&sup;")
8380 ("nsub")
8381 ("sube")
8382 ("supe")
8383 ("oplus")
8384 ("otimes")
8385 ("perp")
8386 ("sdot") ("cdot"."&sdot;")
8387 ("lceil")
8388 ("rceil")
8389 ("lfloor")
8390 ("rfloor")
8391 ("lang")
8392 ("rang")
8393 ("loz") ("Diamond"."&loz;")
8394 ("spades") ("spadesuit"."&spades;")
8395 ("clubs") ("clubsuit"."&clubs;")
8396 ("hearts") ("diamondsuit"."&hearts;")
8397 ("diams") ("diamondsuit"."&diams;")
8398 ("quot")
8399 ("amp")
8400 ("lt")
8401 ("gt")
8402 ("OElig")
8403 ("oelig")
8404 ("Scaron")
8405 ("scaron")
8406 ("Yuml")
8407 ("circ")
8408 ("tilde")
8409 ("ensp")
8410 ("emsp")
8411 ("thinsp")
8412 ("zwnj")
8413 ("zwj")
8414 ("lrm")
8415 ("rlm")
8416 ("ndash")
8417 ("mdash")
8418 ("lsquo")
8419 ("rsquo")
8420 ("sbquo")
8421 ("ldquo")
8422 ("rdquo")
8423 ("bdquo")
8424 ("dagger")
8425 ("Dagger")
8426 ("permil")
8427 ("lsaquo")
8428 ("rsaquo")
8429 ("euro")
8430
8431 ("arccos"."arccos")
8432 ("arcsin"."arcsin")
8433 ("arctan"."arctan")
8434 ("arg"."arg")
8435 ("cos"."cos")
8436 ("cosh"."cosh")
8437 ("cot"."cot")
8438 ("coth"."coth")
8439 ("csc"."csc")
8440 ("deg"."deg")
8441 ("det"."det")
8442 ("dim"."dim")
8443 ("exp"."exp")
8444 ("gcd"."gcd")
8445 ("hom"."hom")
8446 ("inf"."inf")
8447 ("ker"."ker")
8448 ("lg"."lg")
8449 ("lim"."lim")
8450 ("liminf"."liminf")
8451 ("limsup"."limsup")
8452 ("ln"."ln")
8453 ("log"."log")
8454 ("max"."max")
8455 ("min"."min")
8456 ("Pr"."Pr")
8457 ("sec"."sec")
8458 ("sin"."sin")
8459 ("sinh"."sinh")
8460 ("sup"."sup")
8461 ("tan"."tan")
8462 ("tanh"."tanh")
8463 )
8464 "Entities for TeX->HTML translation.
8465 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8466 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8467 In that case, \"\\ent\" will be translated to \"&other;\".
8468 The list contains HTML entities for Latin-1, Greek and other symbols.
8469 It is supplemented by a number of commonly used TeX macros with appropriate
8470 translations. There is currently no way for users to extend this.")
8471
8472 (defvar org-last-level nil) ; dynamically scoped variable
8473
8474 (defun org-export-as-ascii (arg)
8475 "Export the outline as a pretty ASCII file.
8476 If there is an active region, export only the region.
8477 The prefix ARG specifies how many levels of the outline should become
8478 underlined headlines. The default is 3."
8479 (interactive "P")
8480 (setq-default org-todo-line-regexp org-todo-line-regexp)
8481 (let* ((region
8482 (buffer-substring
8483 (if (org-region-active-p) (region-beginning) (point-min))
8484 (if (org-region-active-p) (region-end) (point-max))))
8485 (lines (org-export-find-first-heading-line
8486 (org-skip-comments (org-split-string region "[\r\n]"))))
8487 (org-startup-with-deadline-check nil)
8488 (level 0) line txt
8489 (umax nil)
8490 (case-fold-search nil)
8491 (filename (concat (file-name-sans-extension (buffer-file-name))
8492 ".txt"))
8493 (buffer (find-file-noselect filename))
8494 (levels-open (make-vector org-level-max nil))
8495 (date (format-time-string "%Y/%m/%d" (current-time)))
8496 (time (format-time-string "%X" (current-time)))
8497 (author user-full-name)
8498 (title (buffer-name))
8499 (options nil)
8500 (email user-mail-address)
8501 (language org-export-default-language)
8502 (text nil)
8503 (todo nil)
8504 (lang-words nil))
8505
8506 (setq org-last-level 1)
8507 (org-init-section-numbers)
8508
8509 (find-file-noselect filename)
8510
8511 ;; Search for the export key lines
8512 (org-parse-key-lines)
8513
8514 (setq lang-words (or (assoc language org-export-language-setup)
8515 (assoc "en" org-export-language-setup)))
8516 (if org-export-ascii-show-new-buffer
8517 (switch-to-buffer-other-window buffer)
8518 (set-buffer buffer))
8519 (erase-buffer)
8520 (fundamental-mode)
8521 (if options (org-parse-export-options options))
8522 (setq umax (if arg (prefix-numeric-value arg)
8523 org-export-headline-levels))
8524
8525 ;; File header
8526 (if title (org-insert-centered title ?=))
8527 (insert "\n")
8528 (if (or author email)
8529 (insert (concat (nth 1 lang-words) ": " (or author "")
8530 (if email (concat " <" email ">") "")
8531 "\n")))
8532 (if (and date time)
8533 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8534 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8535
8536 (insert "\n\n")
8537
8538 (if org-export-with-toc
8539 (progn
8540 (insert (nth 3 lang-words) "\n"
8541 (make-string (length (nth 3 lang-words)) ?=) "\n")
8542 (mapcar '(lambda (line)
8543 (if (string-match org-todo-line-regexp
8544 line)
8545 ;; This is a headline
8546 (progn
8547 (setq level (- (match-end 1) (match-beginning 1))
8548 txt (match-string 3 line)
8549 todo
8550 (or (and (match-beginning 2)
8551 (not (equal (match-string 2 line)
8552 org-done-string)))
8553 ; TODO, not DONE
8554 (and (= level umax)
8555 (org-search-todo-below
8556 line lines level))))
8557 (setq txt (org-html-expand-for-ascii txt))
8558
8559 (if org-export-with-section-numbers
8560 (setq txt (concat (org-section-number level)
8561 " " txt)))
8562 (if (<= level umax)
8563 (progn
8564 (insert
8565 (make-string (* (1- level) 4) ?\ )
8566 (format (if todo "%s (*)\n" "%s\n") txt))
8567 (setq org-last-level level))
8568 ))))
8569 lines)))
8570
8571 (org-init-section-numbers)
8572 (while (setq line (pop lines))
8573 ;; Remove the quoted HTML tags.
8574 (setq line (org-html-expand-for-ascii line))
8575 (cond
8576 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8577 ;; a Headline
8578 (setq level (- (match-end 1) (match-beginning 1))
8579 txt (match-string 2 line))
8580 (org-ascii-level-start level txt umax))
8581 (t (insert line "\n"))))
8582 (normal-mode)
8583 (save-buffer)
8584 (goto-char (point-min))))
8585
8586 (defun org-search-todo-below (line lines level)
8587 "Search the subtree below LINE for any TODO entries."
8588 (let ((rest (cdr (memq line lines)))
8589 (re org-todo-line-regexp)
8590 line lv todo)
8591 (catch 'exit
8592 (while (setq line (pop rest))
8593 (if (string-match re line)
8594 (progn
8595 (setq lv (- (match-end 1) (match-beginning 1))
8596 todo (and (match-beginning 2)
8597 (not (equal (match-string 2 line)
8598 org-done-string))))
8599 ; TODO, not DONE
8600 (if (<= lv level) (throw 'exit nil))
8601 (if todo (throw 'exit t))))))))
8602
8603 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8604 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8605 (defun org-html-expand-for-ascii (line)
8606 "Handle quoted HTML for ASCII export."
8607 (if org-export-html-expand
8608 (while (string-match "@<[^<>\n]*>" line)
8609 ;; We just remove the tags for now.
8610 (setq line (replace-match "" nil nil line))))
8611 line)
8612
8613 (defun org-insert-centered (s &optional underline)
8614 "Insert the string S centered and underline it with character UNDERLINE."
8615 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8616 (insert (make-string ind ?\ ) s "\n")
8617 (if underline
8618 (insert (make-string ind ?\ )
8619 (make-string (length s) underline)
8620 "\n"))))
8621
8622 (defun org-ascii-level-start (level title umax)
8623 "Insert a new level in ASCII export."
8624 (let (char)
8625 (if (> level umax)
8626 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8627 (if (or (not (equal (char-before) ?\n))
8628 (not (equal (char-before (1- (point))) ?\n)))
8629 (insert "\n"))
8630 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8631 (if org-export-with-section-numbers
8632 (setq title (concat (org-section-number level) " " title)))
8633 (insert title "\n" (make-string (string-width title) char) "\n"))))
8634
8635 (defun org-export-copy-visible ()
8636 "Copy the visible part of the buffer to another buffer, for printing.
8637 Also removes the first line of the buffer if it specifies a mode,
8638 and all options lines."
8639 (interactive)
8640 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8641 ".txt"))
8642 (buffer (find-file-noselect filename))
8643 (ore (concat
8644 (org-make-options-regexp
8645 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8646 "STARTUP" "ARCHIVE"
8647 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8648 (if org-noutline-p "\\(\n\\|$\\)" "")))
8649 s e)
8650 (with-current-buffer buffer
8651 (erase-buffer)
8652 (text-mode))
8653 (save-excursion
8654 (setq s (goto-char (point-min)))
8655 (while (not (= (point) (point-max)))
8656 (goto-char (org-find-invisible))
8657 (append-to-buffer buffer s (point))
8658 (setq s (goto-char (org-find-visible)))))
8659 (switch-to-buffer-other-window buffer)
8660 (newline)
8661 (goto-char (point-min))
8662 (if (looking-at ".*-\\*- mode:.*\n")
8663 (replace-match ""))
8664 (while (re-search-forward ore nil t)
8665 (replace-match ""))
8666 (goto-char (point-min))))
8667
8668 (defun org-find-visible ()
8669 (if (featurep 'noutline)
8670 (let ((s (point)))
8671 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8672 (get-char-property s 'invisible)))
8673 s)
8674 (skip-chars-forward "^\n")
8675 (point)))
8676 (defun org-find-invisible ()
8677 (if (featurep 'noutline)
8678 (let ((s (point)))
8679 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8680 (not (get-char-property s 'invisible))))
8681 s)
8682 (skip-chars-forward "^\r")
8683 (point)))
8684
8685 ;; HTML
8686
8687 (defun org-get-current-options ()
8688 "Return a string with current options as keyword options.
8689 Does include HTML export options as well as TODO and CATEGORY stuff."
8690 (format
8691 "#+TITLE: %s
8692 #+AUTHOR: %s
8693 #+EMAIL: %s
8694 #+LANGUAGE: %s
8695 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8696 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8697 #+CATEGORY: %s
8698 #+SEQ_TODO: %s
8699 #+TYP_TODO: %s
8700 #+STARTUP: %s %s
8701 #+ARCHIVE: %s
8702 "
8703 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8704 org-export-headline-levels
8705 org-export-with-section-numbers
8706 org-export-with-toc
8707 org-export-preserve-breaks
8708 org-export-html-expand
8709 org-export-with-fixed-width
8710 org-export-with-tables
8711 org-export-with-sub-superscripts
8712 org-export-with-emphasize
8713 org-export-with-TeX-macros
8714 (file-name-nondirectory (buffer-file-name))
8715 (if (equal org-todo-interpretation 'sequence)
8716 (mapconcat 'identity org-todo-keywords " ")
8717 "TODO FEEDBACK VERIFY DONE")
8718 (if (equal org-todo-interpretation 'type)
8719 (mapconcat 'identity org-todo-keywords " ")
8720 "Me Jason Marie DONE")
8721 (cdr (assoc org-startup-folded
8722 '((nil . "nofold")(t . "fold")(content . "content"))))
8723 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8724 org-archive-location
8725 ))
8726
8727 (defun org-insert-export-options-template ()
8728 "Insert into the buffer a template with information for exporting."
8729 (interactive)
8730 (if (not (bolp)) (newline))
8731 (let ((s (org-get-current-options)))
8732 (and (string-match "#\\+CATEGORY" s)
8733 (setq s (substring s 0 (match-beginning 0))))
8734 (insert s)))
8735
8736 (defun org-toggle-fixed-width-section (arg)
8737 "Toggle the fixed-width export.
8738 If there is no active region, the QUOTE keyword at the current headline is
8739 inserted or removed. When present, it causes the text between this headline
8740 and the next to be exported as fixed-width text, and unmodified.
8741 If there is an active region, this command adds or removes a colon as the
8742 first character of this line. If the first character of a line is a colon,
8743 this line is also exported in fixed-width font."
8744 (interactive "P")
8745 (let* ((cc 0)
8746 (regionp (org-region-active-p))
8747 (beg (if regionp (region-beginning) (point)))
8748 (end (if regionp (region-end)))
8749 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8750 (re "[ \t]*\\(:\\)")
8751 off)
8752 (if regionp
8753 (save-excursion
8754 (goto-char beg)
8755 (setq cc (current-column))
8756 (beginning-of-line 1)
8757 (setq off (looking-at re))
8758 (while (> nlines 0)
8759 (setq nlines (1- nlines))
8760 (beginning-of-line 1)
8761 (cond
8762 (arg
8763 (move-to-column cc t)
8764 (insert ":\n")
8765 (forward-line -1))
8766 ((and off (looking-at re))
8767 (replace-match "" t t nil 1))
8768 ((not off) (move-to-column cc t) (insert ":")))
8769 (forward-line 1)))
8770 (save-excursion
8771 (org-back-to-heading)
8772 (if (looking-at (concat outline-regexp
8773 "\\( +\\<" org-quote-string "\\>\\)"))
8774 (replace-match "" t t nil 1)
8775 (if (looking-at outline-regexp)
8776 (progn
8777 (goto-char (match-end 0))
8778 (insert " " org-quote-string))))))))
8779
8780 (defun org-export-as-html-and-open (arg)
8781 "Export the outline as HTML and immediately open it with a browser.
8782 If there is an active region, export only the region.
8783 The prefix ARG specifies how many levels of the outline should become
8784 headlines. The default is 3. Lower levels will become bulleted lists."
8785 (interactive "P")
8786 (org-export-as-html arg 'hidden)
8787 (org-open-file (buffer-file-name)))
8788
8789 (defun org-export-as-html-batch ()
8790 "Call `org-export-as-html', may be used in batch processing as
8791 emacs --batch
8792 --load=$HOME/lib/emacs/org.el
8793 --eval \"(setq org-export-headline-levels 2)\"
8794 --visit=MyFile --funcall org-export-as-html-batch"
8795 (org-export-as-html org-export-headline-levels 'hidden))
8796
8797 (defun org-export-as-html (arg &optional hidden)
8798 "Export the outline as a pretty HTML file.
8799 If there is an active region, export only the region.
8800 The prefix ARG specifies how many levels of the outline should become
8801 headlines. The default is 3. Lower levels will become bulleted lists."
8802 (interactive "P")
8803 (setq-default org-todo-line-regexp org-todo-line-regexp)
8804 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8805 (setq-default org-done-string org-done-string)
8806 (let* ((region-p (org-region-active-p))
8807 (region
8808 (buffer-substring
8809 (if region-p (region-beginning) (point-min))
8810 (if region-p (region-end) (point-max))))
8811 (all_lines
8812 (org-skip-comments (org-split-string region "[\r\n]")))
8813 (lines (org-export-find-first-heading-line all_lines))
8814 (level 0) (line "") (origline "") txt todo
8815 (umax nil)
8816 (filename (concat (file-name-sans-extension (buffer-file-name))
8817 ".html"))
8818 (buffer (find-file-noselect filename))
8819 (levels-open (make-vector org-level-max nil))
8820 (date (format-time-string "%Y/%m/%d" (current-time)))
8821 (time (format-time-string "%X" (current-time)))
8822 (author user-full-name)
8823 (title (buffer-name))
8824 (options nil)
8825 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
8826 (inquote nil)
8827 (email user-mail-address)
8828 (language org-export-default-language)
8829 (text nil)
8830 (lang-words nil)
8831 (head-count 0) cnt
8832 (start 0)
8833 ;; FIXME: The following returns always nil under XEmacs
8834 (coding-system (and (fboundp 'coding-system-get)
8835 (boundp 'buffer-file-coding-system)
8836 buffer-file-coding-system))
8837 (charset (and coding-system
8838 (coding-system-get coding-system 'mime-charset)))
8839 table-open type
8840 table-buffer table-orig-buffer
8841 )
8842 (message "Exporting...")
8843
8844 (setq org-last-level 1)
8845 (org-init-section-numbers)
8846
8847 ;; Search for the export key lines
8848 (org-parse-key-lines)
8849 (setq lang-words (or (assoc language org-export-language-setup)
8850 (assoc "en" org-export-language-setup)))
8851
8852 ;; Switch to the output buffer
8853 (if (or hidden (not org-export-html-show-new-buffer))
8854 (set-buffer buffer)
8855 (switch-to-buffer-other-window buffer))
8856 (erase-buffer)
8857 (fundamental-mode)
8858 (let ((case-fold-search nil))
8859 (if options (org-parse-export-options options))
8860 (setq umax (if arg (prefix-numeric-value arg)
8861 org-export-headline-levels))
8862
8863 ;; File header
8864 (insert (format
8865 "<html lang=\"%s\"><head>
8866 <title>%s</title>
8867 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
8868 <meta name=generator content=\"Org-mode\">
8869 <meta name=generated content=\"%s %s\">
8870 <meta name=author content=\"%s\">
8871 </head><body>
8872 "
8873 language (org-html-expand title) (or charset "iso-8859-1")
8874 date time author))
8875 (if title (insert (concat "<H1 align=\"center\">"
8876 (org-html-expand title) "</H1>\n")))
8877 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8878 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8879 email "&gt;</a>\n")))
8880 (if (or author email) (insert "<br>\n"))
8881 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8882 date " " time "<br>\n")))
8883 (if text (insert (concat "<p>\n" (org-html-expand text))))
8884 (if org-export-with-toc
8885 (progn
8886 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8887 (insert "<ul>\n")
8888 (mapcar '(lambda (line)
8889 (if (string-match org-todo-line-regexp line)
8890 ;; This is a headline
8891 (progn
8892 (setq level (- (match-end 1) (match-beginning 1))
8893 txt (save-match-data
8894 (org-html-expand
8895 (match-string 3 line)))
8896 todo
8897 (or (and (match-beginning 2)
8898 (not (equal (match-string 2 line)
8899 org-done-string)))
8900 ; TODO, not DONE
8901 (and (= level umax)
8902 (org-search-todo-below
8903 line lines level))))
8904 (if org-export-with-section-numbers
8905 (setq txt (concat (org-section-number level)
8906 " " txt)))
8907 (if (<= level umax)
8908 (progn
8909 (setq head-count (+ head-count 1))
8910 (if (> level org-last-level)
8911 (progn
8912 (setq cnt (- level org-last-level))
8913 (while (>= (setq cnt (1- cnt)) 0)
8914 (insert "<ul>"))
8915 (insert "\n")))
8916 (if (< level org-last-level)
8917 (progn
8918 (setq cnt (- org-last-level level))
8919 (while (>= (setq cnt (1- cnt)) 0)
8920 (insert "</ul>"))
8921 (insert "\n")))
8922 (insert
8923 (format
8924 (if todo
8925 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8926 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8927 head-count txt))
8928 (setq org-last-level level))
8929 ))))
8930 lines)
8931 (while (> org-last-level 0)
8932 (setq org-last-level (1- org-last-level))
8933 (insert "</ul>\n"))
8934 ))
8935 (setq head-count 0)
8936 (org-init-section-numbers)
8937
8938 (while (setq line (pop lines) origline line)
8939 ;; end of quote?
8940 (when (and inquote (string-match "^\\*+" line))
8941 (insert "</pre>\n")
8942 (setq inquote nil))
8943 ;; inquote
8944 (if inquote
8945 (progn
8946 (insert line "\n")
8947 (setq line (org-html-expand line))) ;;????? FIXME: not needed?
8948
8949 ;; Protect the links
8950 (setq start 0)
8951 (while (string-match org-link-maybe-angles-regexp line start)
8952 (setq start (match-end 0))
8953 (setq line (replace-match
8954 (concat "\000" (match-string 1 line) "\000")
8955 t t line)))
8956
8957 ;; replace "<" and ">" by "&lt;" and "&gt;"
8958 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8959 (setq line (org-html-expand line))
8960
8961 ;; Verbatim lines
8962 (if (and org-export-with-fixed-width
8963 (string-match "^[ \t]*:\\(.*\\)" line))
8964 (progn
8965 (let ((l (match-string 1 line)))
8966 (while (string-match " " l)
8967 (setq l (replace-match "&nbsp;" t t l)))
8968 (insert "\n<span style='font-family:Courier'>"
8969 l "</span>"
8970 (if (and lines
8971 (not (string-match "^[ \t]+\\(:.*\\)"
8972 (car lines))))
8973 "<br>\n" "\n"))))
8974
8975 (setq start 0)
8976 (while (string-match org-protected-link-regexp line start)
8977 (setq start (- (match-end 0) 2))
8978 (setq type (match-string 1 line))
8979 (cond
8980 ((member type '("http" "https" "ftp" "mailto" "news"))
8981 ;; standard URL
8982 (setq line (replace-match
8983 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8984 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8985 nil nil line)))
8986 ((string= type "file")
8987 ;; FILE link
8988 (let* ((filename (match-string 2 line))
8989 (abs-p (file-name-absolute-p filename))
8990 (thefile (if abs-p (expand-file-name filename) filename))
8991 (thefile (save-match-data
8992 (if (string-match ":[0-9]+$" thefile)
8993 (replace-match "" t t thefile)
8994 thefile)))
8995 (file-is-image-p
8996 (save-match-data
8997 (string-match (org-image-file-name-regexp) thefile))))
8998 (setq line (replace-match
8999 (if (and org-export-html-inline-images
9000 file-is-image-p)
9001 (concat "<img src=\"" thefile "\"/>")
9002 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
9003 nil nil line))))
9004
9005 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
9006 (setq line (replace-match
9007 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
9008
9009 ;; TODO items
9010 (if (and (string-match org-todo-line-regexp line)
9011 (match-beginning 2))
9012 (if (equal (match-string 2 line) org-done-string)
9013 (setq line (replace-match
9014 "<span style='color:green'>\\2</span>"
9015 nil nil line 2))
9016 (setq line (replace-match "<span style='color:red'>\\2</span>"
9017 nil nil line 2))))
9018
9019 ;; DEADLINES
9020 (if (string-match org-deadline-line-regexp line)
9021 (progn
9022 (if (save-match-data
9023 (string-match "<a href"
9024 (substring line 0 (match-beginning 0))))
9025 nil ; Don't do the replacement - it is inside a link
9026 (setq line (replace-match "<span style='color:red'>\\&</span>"
9027 nil nil line 1)))))
9028
9029
9030 (cond
9031 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9032 ;; This is a headline
9033 (setq level (- (match-end 1) (match-beginning 1))
9034 txt (match-string 2 line))
9035 (if (<= level umax) (setq head-count (+ head-count 1)))
9036 (org-html-level-start level txt umax
9037 (and org-export-with-toc (<= level umax))
9038 head-count)
9039 ;; QUOTES
9040 (when (string-match quote-re line)
9041 (insert "<pre>")
9042 (setq inquote t)))
9043
9044 ((and org-export-with-tables
9045 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9046 (if (not table-open)
9047 ;; New table starts
9048 (setq table-open t table-buffer nil table-orig-buffer nil))
9049 ;; Accumulate lines
9050 (setq table-buffer (cons line table-buffer)
9051 table-orig-buffer (cons origline table-orig-buffer))
9052 (when (or (not lines)
9053 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9054 (car lines))))
9055 (setq table-open nil
9056 table-buffer (nreverse table-buffer)
9057 table-orig-buffer (nreverse table-orig-buffer))
9058 (insert (org-format-table-html table-buffer table-orig-buffer))))
9059 (t
9060 ;; Normal lines
9061 ;; Lines starting with "-", and empty lines make new paragraph.
9062 ;; FIXME: Should we add + and *?
9063 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
9064 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9065 )))
9066 (if org-export-html-with-timestamp
9067 (insert org-export-html-html-helper-timestamp))
9068 (insert "</body>\n</html>\n")
9069 (normal-mode)
9070 (save-buffer)
9071 (goto-char (point-min)))))
9072
9073 (defun org-format-table-html (lines olines)
9074 "Find out which HTML converter to use and return the HTML code."
9075 (if (string-match "^[ \t]*|" (car lines))
9076 ;; A normal org table
9077 (org-format-org-table-html lines)
9078 ;; Table made by table.el - test for spanning
9079 (let* ((hlines (delq nil (mapcar
9080 (lambda (x)
9081 (if (string-match "^[ \t]*\\+-" x) x
9082 nil))
9083 lines)))
9084 (first (car hlines))
9085 (ll (and (string-match "\\S-+" first)
9086 (match-string 0 first)))
9087 (re (concat "^[ \t]*" (regexp-quote ll)))
9088 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9089 hlines))))
9090 (if (and (not spanning)
9091 (not org-export-prefer-native-exporter-for-tables))
9092 ;; We can use my own converter with HTML conversions
9093 (org-format-table-table-html lines)
9094 ;; Need to use the code generator in table.el, with the original text.
9095 (org-format-table-table-html-using-table-generate-source olines)))))
9096
9097 (defun org-format-org-table-html (lines)
9098 "Format a table into html."
9099 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9100 (setq lines (nreverse lines))
9101 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9102 (setq lines (nreverse lines))
9103 (let ((head (and org-export-highlight-first-table-line
9104 (delq nil (mapcar
9105 (lambda (x) (string-match "^[ \t]*|-" x))
9106 (cdr lines)))))
9107 line fields html)
9108 (setq html (concat org-export-html-table-tag "\n"))
9109 (while (setq line (pop lines))
9110 (catch 'next-line
9111 (if (string-match "^[ \t]*|-" line)
9112 (progn
9113 (setq head nil) ;; head ends here, first time around
9114 ;; ignore this line
9115 (throw 'next-line t)))
9116 ;; Break the line into fields
9117 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9118 (setq html (concat
9119 html
9120 "<tr>"
9121 (mapconcat (lambda (x)
9122 (if head
9123 (concat "<th>" x "</th>")
9124 (concat "<td valign=\"top\">" x "</td>")))
9125 fields "")
9126 "</tr>\n"))))
9127 (setq html (concat html "</table>\n"))
9128 html))
9129
9130 (defun org-fake-empty-table-line (line)
9131 "Replace everything except \"|\" with spaces."
9132 (let ((i (length line))
9133 (newstr (copy-sequence line)))
9134 (while (> i 0)
9135 (setq i (1- i))
9136 (if (not (eq (aref newstr i) ?|))
9137 (aset newstr i ?\ )))
9138 newstr))
9139
9140 (defun org-format-table-table-html (lines)
9141 "Format a table generated by table.el into html.
9142 This conversion does *not* use `table-generate-source' from table.el.
9143 This has the advantage that Org-mode's HTML conversions can be used.
9144 But it has the disadvantage, that no cell- or row-spanning is allowed."
9145 (let (line field-buffer
9146 (head org-export-highlight-first-table-line)
9147 fields html empty)
9148 (setq html (concat org-export-html-table-tag "\n"))
9149 (while (setq line (pop lines))
9150 (setq empty "&nbsp")
9151 (catch 'next-line
9152 (if (string-match "^[ \t]*\\+-" line)
9153 (progn
9154 (if field-buffer
9155 (progn
9156 (setq html (concat
9157 html
9158 "<tr>"
9159 (mapconcat
9160 (lambda (x)
9161 (if (equal x "") (setq x empty))
9162 (if head
9163 (concat "<th valign=\"top\">" x
9164 "</th>\n")
9165 (concat "<td valign=\"top\">" x
9166 "</td>\n")))
9167 field-buffer "\n")
9168 "</tr>\n"))
9169 (setq head nil)
9170 (setq field-buffer nil)))
9171 ;; Ignore this line
9172 (throw 'next-line t)))
9173 ;; Break the line into fields and store the fields
9174 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9175 (if field-buffer
9176 (setq field-buffer (mapcar
9177 (lambda (x)
9178 (concat x "<br>" (pop fields)))
9179 field-buffer))
9180 (setq field-buffer fields))))
9181 (setq html (concat html "</table>\n"))
9182 html))
9183
9184 (defun org-format-table-table-html-using-table-generate-source (lines)
9185 "Format a table into html, using `table-generate-source' from table.el.
9186 This has the advantage that cell- or row-spanning is allowed.
9187 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9188 (require 'table)
9189 (with-current-buffer (get-buffer-create " org-tmp1 ")
9190 (erase-buffer)
9191 (insert (mapconcat 'identity lines "\n"))
9192 (goto-char (point-min))
9193 (if (not (re-search-forward "|[^+]" nil t))
9194 (error "Error processing table"))
9195 (table-recognize-table)
9196 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9197 (table-generate-source 'html " org-tmp2 ")
9198 (set-buffer " org-tmp2 ")
9199 (buffer-substring (point-min) (point-max))))
9200
9201 (defun org-html-expand (string)
9202 "Prepare STRING for HTML export. Applies all active conversions."
9203 ;; First check if there is a link in the line - if yes, apply conversions
9204 ;; only before the start of the link.
9205 (let* ((m (string-match org-link-regexp string))
9206 (s (if m (substring string 0 m) string))
9207 (r (if m (substring string m) "")))
9208 ;; convert < to &lt; and > to &gt;
9209 (while (string-match "<" s)
9210 (setq s (replace-match "&lt;" t t s)))
9211 (while (string-match ">" s)
9212 (setq s (replace-match "&gt;" t t s)))
9213 (if org-export-html-expand
9214 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9215 (setq s (replace-match "<\\1>" nil nil s))))
9216 (if org-export-with-emphasize
9217 (setq s (org-export-html-convert-emphasize s)))
9218 (if org-export-with-sub-superscripts
9219 (setq s (org-export-html-convert-sub-super s)))
9220 (if org-export-with-TeX-macros
9221 (let ((start 0) wd ass)
9222 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9223 (setq wd (match-string 1 s))
9224 (if (setq ass (assoc wd org-html-entities))
9225 (setq s (replace-match (or (cdr ass)
9226 (concat "&" (car ass) ";"))
9227 t t s))
9228 (setq start (+ start (length wd)))))))
9229 (concat s r)))
9230
9231 (defun org-create-multibrace-regexp (left right n)
9232 "Create a regular expression which will match a balanced sexp.
9233 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9234 as single character strings.
9235 The regexp returned will match the entire expression including the
9236 delimiters. It will also define a single group which contains the
9237 match except for the outermost delimiters. The maximum depth of
9238 stacked delimiters is N. Escaping delimiters is not possible."
9239 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9240 (or "\\|")
9241 (re nothing)
9242 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9243 (while (> n 1)
9244 (setq n (1- n)
9245 re (concat re or next)
9246 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9247 (concat left "\\(" re "\\)" right)))
9248
9249 (defvar org-match-substring-regexp
9250 (concat
9251 "\\([^\\]\\)\\([_^]\\)\\("
9252 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9253 "\\|"
9254 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9255 "\\|"
9256 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9257 "The regular expression matching a sub- or superscript.")
9258
9259 (defun org-export-html-convert-sub-super (string)
9260 "Convert sub- and superscripts in STRING to HTML."
9261 (let (key c)
9262 (while (string-match org-match-substring-regexp string)
9263 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9264 (setq c (or (match-string 8 string)
9265 (match-string 6 string)
9266 (match-string 5 string)))
9267 (setq string (replace-match
9268 (concat (match-string 1 string)
9269 "<" key ">" c "</" key ">")
9270 t t string)))
9271 (while (string-match "\\\\\\([_^]\\)" string)
9272 (setq string (replace-match (match-string 1 string) t t string))))
9273 string)
9274
9275 (defun org-export-html-convert-emphasize (string)
9276 (while (string-match
9277 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9278 string)
9279 (setq string (replace-match
9280 (concat "<b>" (match-string 3 string) "</b>")
9281 t t string 2)))
9282 (while (string-match
9283 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9284 string)
9285 (setq string (replace-match
9286 (concat "<i>" (match-string 3 string) "</i>")
9287 t t string 2)))
9288 (while (string-match
9289 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9290 string)
9291 (setq string (replace-match
9292 (concat "<u>" (match-string 3 string) "</u>")
9293 t t string 2)))
9294 string)
9295
9296 (defun org-parse-key-lines ()
9297 "Find the special key lines with the information for exporters."
9298 (save-excursion
9299 (goto-char 0)
9300 (let ((re (org-make-options-regexp
9301 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9302 key)
9303 (while (re-search-forward re nil t)
9304 (setq key (match-string 1))
9305 (cond ((string-equal key "TITLE")
9306 (setq title (match-string 2)))
9307 ((string-equal key "AUTHOR")
9308 (setq author (match-string 2)))
9309 ((string-equal key "EMAIL")
9310 (setq email (match-string 2)))
9311 ((string-equal key "LANGUAGE")
9312 (setq language (match-string 2)))
9313 ((string-equal key "TEXT")
9314 (setq text (concat text "\n" (match-string 2))))
9315 ((string-equal key "OPTIONS")
9316 (setq options (match-string 2))))))))
9317
9318 (defun org-parse-export-options (s)
9319 "Parse the export options line."
9320 (let ((op '(("H" . org-export-headline-levels)
9321 ("num" . org-export-with-section-numbers)
9322 ("toc" . org-export-with-toc)
9323 ("\\n" . org-export-preserve-breaks)
9324 ("@" . org-export-html-expand)
9325 (":" . org-export-with-fixed-width)
9326 ("|" . org-export-with-tables)
9327 ("^" . org-export-with-sub-superscripts)
9328 ("*" . org-export-with-emphasize)
9329 ("TeX" . org-export-with-TeX-macros)))
9330 o)
9331 (while (setq o (pop op))
9332 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9333 s)
9334 (set (make-local-variable (cdr o))
9335 (car (read-from-string (match-string 1 s))))))))
9336
9337 (defun org-html-level-start (level title umax with-toc head-count)
9338 "Insert a new level in HTML export."
9339 (let ((l (1+ (max level umax))))
9340 (while (<= l org-level-max)
9341 (if (aref levels-open (1- l))
9342 (progn
9343 (org-html-level-close l)
9344 (aset levels-open (1- l) nil)))
9345 (setq l (1+ l)))
9346 (if (> level umax)
9347 (progn
9348 (if (aref levels-open (1- level))
9349 (insert "<li>" title "<p>\n")
9350 (aset levels-open (1- level) t)
9351 (insert "<ul><li>" title "<p>\n")))
9352 (if org-export-with-section-numbers
9353 (setq title (concat (org-section-number level) " " title)))
9354 (setq level (+ level 1))
9355 (if with-toc
9356 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9357 level head-count title level))
9358 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9359
9360 (defun org-html-level-close (&rest args)
9361 "Terminate one level in HTML export."
9362 (insert "</ul>"))
9363
9364
9365 ;; Variable holding the vector with section numbers
9366 (defvar org-section-numbers (make-vector org-level-max 0))
9367
9368 (defun org-init-section-numbers ()
9369 "Initialize the vector for the section numbers."
9370 (let* ((level -1)
9371 (numbers (nreverse (org-split-string "" "\\.")))
9372 (depth (1- (length org-section-numbers)))
9373 (i depth) number-string)
9374 (while (>= i 0)
9375 (if (> i level)
9376 (aset org-section-numbers i 0)
9377 (setq number-string (or (car numbers) "0"))
9378 (if (string-match "\\`[A-Z]\\'" number-string)
9379 (aset org-section-numbers i
9380 (- (string-to-char number-string) ?A -1))
9381 (aset org-section-numbers i (string-to-number number-string)))
9382 (pop numbers))
9383 (setq i (1- i)))))
9384
9385 (defun org-section-number (&optional level)
9386 "Return a string with the current section number.
9387 When LEVEL is non-nil, increase section numbers on that level."
9388 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9389 (when level
9390 (when (> level -1)
9391 (aset org-section-numbers
9392 level (1+ (aref org-section-numbers level))))
9393 (setq idx (1+ level))
9394 (while (<= idx depth)
9395 (if (not (= idx 1))
9396 (aset org-section-numbers idx 0))
9397 (setq idx (1+ idx))))
9398 (setq idx 0)
9399 (while (<= idx depth)
9400 (setq n (aref org-section-numbers idx))
9401 (setq string (concat string (if (not (string= string "")) "." "")
9402 (int-to-string n)))
9403 (setq idx (1+ idx)))
9404 (save-match-data
9405 (if (string-match "\\`\\([@0]\\.\\)+" string)
9406 (setq string (replace-match "" nil nil string)))
9407 (if (string-match "\\(\\.0\\)+\\'" string)
9408 (setq string (replace-match "" nil nil string))))
9409 string))
9410
9411
9412 ;;; Key bindings
9413
9414 ;; - Bindings in Org-mode map are currently
9415 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9416 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9417 ;; e (?) useful from outline-mode
9418 ;; i k @ expendable from outline-mode
9419 ;; 0123456789 ! %^& ()_{} " `' free
9420
9421 ;; Make `C-c C-x' a prefix key
9422 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
9423
9424 ;; TAB key with modifiers
9425 (define-key org-mode-map "\C-i" 'org-cycle)
9426 (define-key org-mode-map [(meta tab)] 'org-complete)
9427 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
9428 ;; The following line is necessary under Suse GNU/Linux
9429 (unless org-xemacs-p
9430 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9431 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9432
9433 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9434 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
9435 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9436 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
9437 (define-key org-mode-map [(meta return)] 'org-meta-return)
9438 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
9439 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
9440
9441 ;; Cursor keys with modifiers
9442 (define-key org-mode-map [(meta left)] 'org-metaleft)
9443 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
9444 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
9445 (define-key org-mode-map [(meta right)] 'org-metaright)
9446 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
9447 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
9448 (define-key org-mode-map [(meta up)] 'org-metaup)
9449 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
9450 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
9451 (define-key org-mode-map [(meta down)] 'org-metadown)
9452 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
9453 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
9454
9455 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9456 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
9457 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9458 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
9459 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9460 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
9461 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9462 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
9463 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9464 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
9465 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9466 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
9467 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9468 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-timestamp-down-day)
9469 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9470 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-timestamp-up-day)
9471
9472 ;; All the other keys
9473 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9474 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9475 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9476 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9477 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9478 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9479 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9480 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9481 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9482 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9483 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9484 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9485 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9486 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9487 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9488 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
9489 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9490 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9491 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9492 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9493 (define-key org-mode-map "\C-c[" 'org-add-file)
9494 (define-key org-mode-map "\C-c]" 'org-remove-file)
9495 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9496 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9497 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9498 (define-key org-mode-map "\C-m" 'org-return)
9499 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9500 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9501 (define-key org-mode-map "\C-c+" 'org-table-sum)
9502 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9503 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9504 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9505 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9506 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9507 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9508 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9509 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9510 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9511 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9512 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9513 ;; OPML support is only planned
9514 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9515 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9516 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9517 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9518 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9519 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
9520 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
9521
9522 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
9523 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
9524 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
9525
9526 (defsubst org-table-p () (org-at-table-p))
9527
9528 (defun org-self-insert-command (N)
9529 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9530 If the cursor is in a table looking at whitespace, the whitespace is
9531 overwritten, and the table is not marked as requiring realignment."
9532 (interactive "p")
9533 (if (and (org-table-p)
9534 (or
9535 (and org-table-auto-blank-field
9536 (member last-command
9537 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
9538 (org-table-blank-field))
9539 t)
9540 (eq N 1)
9541 (looking-at "[^|\n]* +|"))
9542 (let (org-table-may-need-update)
9543 (goto-char (1- (match-end 0)))
9544 (delete-backward-char 1)
9545 (goto-char (match-beginning 0))
9546 (self-insert-command N))
9547 (setq org-table-may-need-update t)
9548 (self-insert-command N)))
9549
9550 ;; FIXME:
9551 ;; The following two functions might still be optimized to trigger
9552 ;; re-alignment less frequently.
9553
9554 (defun org-delete-backward-char (N)
9555 "Like `delete-backward-char', insert whitespace at field end in tables.
9556 When deleting backwards, in tables this function will insert whitespace in
9557 front of the next \"|\" separator, to keep the table aligned. The table will
9558 still be marked for re-alignment, because a narrow field may lead to a
9559 reduced column width."
9560 (interactive "p")
9561 (if (and (org-table-p)
9562 (eq N 1)
9563 (string-match "|" (buffer-substring (point-at-bol) (point)))
9564 (looking-at ".*?|"))
9565 (let ((pos (point)))
9566 (backward-delete-char N)
9567 (skip-chars-forward "^|")
9568 (insert " ")
9569 (goto-char (1- pos)))
9570 (backward-delete-char N)))
9571
9572 (defun org-delete-char (N)
9573 "Like `delete-char', but insert whitespace at field end in tables.
9574 When deleting characters, in tables this function will insert whitespace in
9575 front of the next \"|\" separator, to keep the table aligned. The table
9576 will still be marked for re-alignment, because a narrow field may lead to
9577 a reduced column width."
9578 (interactive "p")
9579 (if (and (org-table-p)
9580 (not (bolp))
9581 (not (= (char-after) ?|))
9582 (eq N 1))
9583 (if (looking-at ".*?|")
9584 (let ((pos (point)))
9585 (replace-match (concat
9586 (substring (match-string 0) 1 -1)
9587 " |"))
9588 (goto-char pos)))
9589 (delete-char N)))
9590
9591 ;; How to do this: Measure non-white length of current string
9592 ;; If equal to column width, we should realign.
9593
9594 (defun org-remap (map &rest commands)
9595 "In MAP, remap the functions given in COMMANDS.
9596 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
9597 (let (new old)
9598 (while commands
9599 (setq old (pop commands) new (pop commands))
9600 (if (fboundp 'command-remapping)
9601 (define-key map (vector 'remap old) new)
9602 (substitute-key-definition old new map global-map)))))
9603
9604 (when (eq org-enable-table-editor 'optimized)
9605 ;; If the user wants maximum table support, we need to hijack
9606 ;; some standard editing functions
9607 (org-remap org-mode-map
9608 'self-insert-command 'org-self-insert-command
9609 'delete-char 'org-delete-char
9610 'delete-backward-char 'org-delete-backward-char)
9611 (define-key org-mode-map "|" 'org-force-self-insert))
9612
9613 (defun org-shiftcursor-error ()
9614 "Throw an error because Shift-Cursor command was applied in wrong context."
9615 (error "This command is only active in tables and on headlines"))
9616
9617 (defun org-shifttab ()
9618 "Global visibility cycling or move to previous table field.
9619 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
9620 See the individual commands for more information."
9621 (interactive)
9622 (cond
9623 ((org-at-table-p) (org-table-previous-field))
9624 (t (org-cycle '(4)))))
9625
9626 (defun org-shiftmetaleft ()
9627 "Promote subtree or delete table column.
9628 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
9629 See the individual commands for more information."
9630 (interactive)
9631 (cond
9632 ((org-at-table-p) (org-table-delete-column))
9633 ((org-on-heading-p) (org-promote-subtree))
9634 (t (org-shiftcursor-error))))
9635
9636 (defun org-shiftmetaright ()
9637 "Demote subtree or insert table column.
9638 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
9639 See the individual commands for more information."
9640 (interactive)
9641 (cond
9642 ((org-at-table-p) (org-table-insert-column))
9643 ((org-on-heading-p) (org-demote-subtree))
9644 (t (org-shiftcursor-error))))
9645
9646 (defun org-shiftmetaup (&optional arg)
9647 "Move subtree up or kill table row.
9648 Calls `org-move-subtree-up' or `org-table-kill-row', depending on context.
9649 See the individual commands for more information."
9650 (interactive "P")
9651 (cond
9652 ((org-at-table-p) (org-table-kill-row))
9653 ((org-on-heading-p) (org-move-subtree-up arg))
9654 (t (org-shiftcursor-error))))
9655 (defun org-shiftmetadown (&optional arg)
9656 "Move subtree down or insert table row.
9657 Calls `org-move-subtree-down' or `org-table-insert-row', depending on context.
9658 See the individual commands for more information."
9659 (interactive "P")
9660 (cond
9661 ((org-at-table-p) (org-table-insert-row arg))
9662 ((org-on-heading-p) (org-move-subtree-down arg))
9663 (t (org-shiftcursor-error))))
9664
9665 (defun org-metaleft (&optional arg)
9666 "Promote heading or move table column to left.
9667 Calls `org-do-promote' or `org-table-move-column', depending on context.
9668 See the individual commands for more information."
9669 (interactive "P")
9670 (cond
9671 ((org-at-table-p) (org-table-move-column 'left))
9672 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9673 (t (backward-word (prefix-numeric-value arg)))))
9674
9675 (defun org-metaright (&optional arg)
9676 "Demote subtree or move table column to right.
9677 Calls `org-do-demote' or `org-table-move-column', depending on context.
9678 See the individual commands for more information."
9679 (interactive "P")
9680 (cond
9681 ((org-at-table-p) (org-table-move-column nil))
9682 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9683 (t (forward-word (prefix-numeric-value arg)))))
9684
9685 (defun org-metaup (&optional arg)
9686 "Move subtree up or move table row up.
9687 Calls `org-move-subtree-up' or `org-table-move-row', depending on context.
9688 See the individual commands for more information."
9689 (interactive "P")
9690 (cond
9691 ((org-at-table-p) (org-table-move-row 'up))
9692 ((org-on-heading-p) (org-move-subtree-up arg))
9693 (t (org-shiftcursor-error))))
9694
9695 (defun org-metadown (&optional arg)
9696 "Move subtree down or move table row down.
9697 Calls `org-move-subtree-down' or `org-table-move-row', depending on context.
9698 See the individual commands for more information."
9699 (interactive "P")
9700 (cond
9701 ((org-at-table-p) (org-table-move-row nil))
9702 ((org-on-heading-p) (org-move-subtree-down arg))
9703 (t (org-shiftcursor-error))))
9704
9705 (defun org-shiftup (&optional arg)
9706 "Increase item in timestamp or increase priority of current item.
9707 Calls `org-timestamp-up' or `org-priority-up', depending on context.
9708 See the individual commands for more information."
9709 (interactive "P")
9710 (cond
9711 ((org-at-timestamp-p) (org-timestamp-up arg))
9712 (t (org-priority-up))))
9713
9714 (defun org-shiftdown (&optional arg)
9715 "Decrease item in timestamp or decrease priority of current item.
9716 Calls `org-timestamp-down' or `org-priority-down', depending on context.
9717 See the individual commands for more information."
9718 (interactive "P")
9719 (cond
9720 ((org-at-timestamp-p) (org-timestamp-down arg))
9721 (t (org-priority-down))))
9722
9723 (defun org-copy-special ()
9724 "Copy region in table or copy current subtree.
9725 Calls `org-table-copy' or `org-copy-subtree', depending on context.
9726 See the individual commands for more information."
9727 (interactive)
9728 (call-interactively
9729 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9730
9731 (defun org-cut-special ()
9732 "Cut region in table or cut current subtree.
9733 Calls `org-table-copy' or `org-cut-subtree', depending on context.
9734 See the individual commands for more information."
9735 (interactive)
9736 (call-interactively
9737 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9738
9739 (defun org-paste-special (arg)
9740 "Paste rectangular region into table, or past subtree relative to level.
9741 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
9742 See the individual commands for more information."
9743 (interactive "P")
9744 (if (org-at-table-p)
9745 (org-table-paste-rectangle)
9746 (org-paste-subtree arg)))
9747
9748 (defun org-ctrl-c-ctrl-c (&optional arg)
9749 "Call realign table, or recognize a table.el table, or update keywords.
9750 When the cursor is inside a table created by the table.el package,
9751 activate that table. Otherwise, if the cursor is at a normal table
9752 created with org.el, re-align that table. This command works even if
9753 the automatic table editor has been turned off.
9754 If the cursor is in one of the special #+KEYWORD lines, this triggers
9755 scanning the buffer for these lines and updating the information.
9756 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
9757 (interactive "P")
9758 (let ((org-enable-table-editor t))
9759 (cond
9760 ((org-at-table.el-p)
9761 (require 'table)
9762 (beginning-of-line 1)
9763 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9764 (table-recognize-table))
9765 ((org-at-table-p)
9766 (org-table-maybe-eval-formula)
9767 (if arg
9768 (org-table-recalculate t)
9769 (org-table-maybe-recalculate-line))
9770 (org-table-align))
9771 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9772 (cond
9773 ((equal (match-string 1) "TBLFM")
9774 ;; Recalculate the table before this line
9775 (save-excursion
9776 (beginning-of-line 1)
9777 (skip-chars-backward " \r\n\t")
9778 (if (org-at-table-p) (org-table-recalculate t))))
9779 (t
9780 (org-mode-restart))))
9781 ((org-region-active-p)
9782 (org-table-convert-region (region-beginning) (region-end) arg))
9783 ((and (region-beginning) (region-end))
9784 (if (y-or-n-p "Convert inactive region to table? ")
9785 (org-table-convert-region (region-beginning) (region-end) arg)
9786 (error "Abort")))
9787 (t (error "No table at point, and no region to make one")))))
9788
9789 (defun org-mode-restart ()
9790 "Restart Org-mode, to scan again for special lines.
9791 Also updates the keyword regular expressions."
9792 (interactive)
9793 (let ((org-inhibit-startup t)) (org-mode))
9794 (message "Org-mode restarted to refresh keyword and special line setup"))
9795
9796 (defun org-return ()
9797 "Goto next table row or insert a newline.
9798 Calls `org-table-next-row' or `newline', depending on context.
9799 See the individual commands for more information."
9800 (interactive)
9801 (cond
9802 ((org-at-table-p)
9803 (org-table-justify-field-maybe)
9804 (org-table-next-row))
9805 (t (newline))))
9806
9807 (defun org-meta-return (&optional arg)
9808 "Insert a new heading or wrap a region in a table.
9809 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
9810 See the individual commands for more information."
9811 (interactive "P")
9812 (cond
9813 ((org-at-table-p)
9814 (org-table-wrap-region arg))
9815 (t (org-insert-heading))))
9816
9817 ;;; Menu entries
9818
9819 ;; Define the Org-mode menus
9820 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9821 '("Tbl"
9822 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9823 ["Next Field" org-cycle (org-at-table-p)]
9824 ["Previous Field" org-shifttab (org-at-table-p)]
9825 ["Next Row" org-return (org-at-table-p)]
9826 "--"
9827 ["Blank Field" org-table-blank-field (org-at-table-p)]
9828 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9829 "--"
9830 ("Column"
9831 ["Move Column Left" org-metaleft (org-at-table-p)]
9832 ["Move Column Right" org-metaright (org-at-table-p)]
9833 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9834 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9835 ("Row"
9836 ["Move Row Up" org-metaup (org-at-table-p)]
9837 ["Move Row Down" org-metadown (org-at-table-p)]
9838 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9839 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9840 "--"
9841 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9842 ("Rectangle"
9843 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9844 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9845 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9846 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9847 "--"
9848 ("Calculate"
9849 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
9850 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9851 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
9852 "--"
9853 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9854 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9855 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9856 "--"
9857 ["Sum Column/Rectangle" org-table-sum
9858 (or (org-at-table-p) (org-region-active-p))]
9859 ["Which Column?" org-table-current-column (org-at-table-p)])
9860 ["Debug Formulas"
9861 (setq org-table-formula-debug (not org-table-formula-debug))
9862 :style toggle :selected org-table-formula-debug]
9863 "--"
9864 ["Invisible Vlines" org-table-toggle-vline-visibility
9865 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9866 "--"
9867 ["Create" org-table-create (and (not (org-at-table-p))
9868 org-enable-table-editor)]
9869 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9870 ["Import from File" org-table-import (not (org-at-table-p))]
9871 ["Export to File" org-table-export (org-at-table-p)]
9872 "--"
9873 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9874
9875 (easy-menu-define org-org-menu org-mode-map "Org menu"
9876 '("Org"
9877 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9878 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
9879 ["Sparse Tree" org-occur t]
9880 ["Show All" show-all t]
9881 "--"
9882 ["New Heading" org-insert-heading t]
9883 ("Navigate Headings"
9884 ["Up" outline-up-heading t]
9885 ["Next" outline-next-visible-heading t]
9886 ["Previous" outline-previous-visible-heading t]
9887 ["Next Same Level" outline-forward-same-level t]
9888 ["Previous Same Level" outline-backward-same-level t]
9889 "--"
9890 ["Jump" org-goto t])
9891 ("Edit Structure"
9892 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9893 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9894 "--"
9895 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9896 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9897 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9898 "--"
9899 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9900 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9901 ["Demote Heading" org-metaright (not (org-at-table-p))]
9902 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9903 "--"
9904 ["Archive Subtree" org-archive-subtree t])
9905 "--"
9906 ("TODO Lists"
9907 ["TODO/DONE/-" org-todo t]
9908 ["Show TODO Tree" org-show-todo-tree t]
9909 "--"
9910 ["Set Priority" org-priority t]
9911 ["Priority Up" org-shiftup t]
9912 ["Priority Down" org-shiftdown t])
9913 ("Dates and Scheduling"
9914 ["Timestamp" org-time-stamp t]
9915 ["Timestamp (inactive)" org-time-stamp-inactive t]
9916 ("Change Date"
9917 ["1 Day Later" org-timestamp-up-day t]
9918 ["1 Day Earlier" org-timestamp-down-day t]
9919 ["1 ... Later" org-shiftup t]
9920 ["1 ... Earlier" org-shiftdown t])
9921 ["Compute Time Range" org-evaluate-time-range t]
9922 ["Schedule Item" org-schedule t]
9923 ["Deadline" org-deadline t]
9924 "--"
9925 ["Goto Calendar" org-goto-calendar t]
9926 ["Date from Calendar" org-date-from-calendar t])
9927 "--"
9928 ("Timeline/Agenda"
9929 ["Show TODO Tree this File" org-show-todo-tree t]
9930 ["Check Deadlines this File" org-check-deadlines t]
9931 ["Timeline Current File" org-timeline t]
9932 "--"
9933 ["Agenda" org-agenda t])
9934 ("File List for Agenda")
9935 "--"
9936 ("Hyperlinks"
9937 ["Store Link (Global)" org-store-link t]
9938 ["Insert Link" org-insert-link t]
9939 ["Follow Link" org-open-at-point t])
9940 "--"
9941 ("Export"
9942 ["ASCII" org-export-as-ascii t]
9943 ["Extract Visible Text" org-export-copy-visible t]
9944 ["HTML" org-export-as-html t]
9945 ["HTML and Open" org-export-as-html-and-open t]
9946 ; ["OPML" org-export-as-opml nil]
9947 "--"
9948 ["Option Template" org-insert-export-options-template t]
9949 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9950 "--"
9951 ("Documentation"
9952 ["Show Version" org-version t]
9953 ["Info Documentation" org-info t])
9954 ("Customize"
9955 ["Browse Org Group" org-customize t]
9956 "--"
9957 ["Build Full Customize Menu" org-create-customize-menu
9958 (fboundp 'customize-menu-create)])
9959 "--"
9960 ["Refresh setup" org-mode-restart t]
9961 ))
9962
9963 (defun org-info (&optional node)
9964 "Read documentation for Org-mode in the info system.
9965 With optional NODE, go directly to that node."
9966 (interactive)
9967 (require 'info)
9968 (Info-goto-node (format "(org)%s" (or node ""))))
9969
9970 (defun org-install-agenda-files-menu ()
9971 (easy-menu-change
9972 '("Org") "File List for Agenda"
9973 (append
9974 (list
9975 ["Edit File List" (customize-variable 'org-agenda-files) t]
9976 ["Add Current File to List" org-add-file t]
9977 ["Remove Current File from List" org-remove-file t]
9978 "--")
9979 (mapcar 'org-file-menu-entry org-agenda-files))))
9980
9981 ;;; Documentation
9982
9983 (defun org-customize ()
9984 "Call the customize function with org as argument."
9985 (interactive)
9986 (customize-browse 'org))
9987
9988 (defun org-create-customize-menu ()
9989 "Create a full customization menu for Org-mode, insert it into the menu."
9990 (interactive)
9991 (if (fboundp 'customize-menu-create)
9992 (progn
9993 (easy-menu-change
9994 '("Org") "Customize"
9995 `(["Browse Org group" org-customize t]
9996 "--"
9997 ,(customize-menu-create 'org)
9998 ["Set" Custom-set t]
9999 ["Save" Custom-save t]
10000 ["Reset to Current" Custom-reset-current t]
10001 ["Reset to Saved" Custom-reset-saved t]
10002 ["Reset to Standard Settings" Custom-reset-standard t]))
10003 (message "\"Org\"-menu now contains full customization menu"))
10004 (error "Cannot expand menu (outdated version of cus-edit.el)")))
10005
10006 ;;; Miscellaneous stuff
10007
10008 (defun org-move-line-down (arg)
10009 "Move the current line down. With prefix argument, move it past ARG lines."
10010 (interactive "p")
10011 (let ((col (current-column))
10012 beg end pos)
10013 (beginning-of-line 1) (setq beg (point))
10014 (beginning-of-line 2) (setq end (point))
10015 (beginning-of-line (+ 1 arg))
10016 (setq pos (move-marker (make-marker) (point)))
10017 (insert (delete-and-extract-region beg end))
10018 (goto-char pos)
10019 (move-to-column col)))
10020
10021 (defun org-move-line-up (arg)
10022 "Move the current line up. With prefix argument, move it past ARG lines."
10023 (interactive "p")
10024 (let ((col (current-column))
10025 beg end pos)
10026 (beginning-of-line 1) (setq beg (point))
10027 (beginning-of-line 2) (setq end (point))
10028 (beginning-of-line (- arg))
10029 (setq pos (move-marker (make-marker) (point)))
10030 (insert (delete-and-extract-region beg end))
10031 (goto-char pos)
10032 (move-to-column col)))
10033
10034 ;; Functions needed for Emacs/XEmacs region compatibility
10035
10036 (defun org-region-active-p ()
10037 "Is `transient-mark-mode' on and the region active?
10038 Works on both Emacs and XEmacs."
10039 (if org-ignore-region
10040 nil
10041 (if org-xemacs-p
10042 (and zmacs-regions (region-active-p))
10043 (and transient-mark-mode mark-active))))
10044
10045 (defun org-add-to-invisibility-spec (arg)
10046 "Add elements to `buffer-invisibility-spec'.
10047 See documentation for `buffer-invisibility-spec' for the kind of elements
10048 that can be added."
10049 (cond
10050 ((fboundp 'add-to-invisibility-spec)
10051 (add-to-invisibility-spec arg))
10052 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
10053 (setq buffer-invisibility-spec (list arg)))
10054 (t
10055 (setq buffer-invisibility-spec
10056 (cons arg buffer-invisibility-spec)))))
10057
10058 (defun org-remove-from-invisibility-spec (arg)
10059 "Remove elements from `buffer-invisibility-spec'."
10060 (if (fboundp 'remove-from-invisibility-spec)
10061 (remove-from-invisibility-spec arg)
10062 (if (consp buffer-invisibility-spec)
10063 (setq buffer-invisibility-spec
10064 (delete arg buffer-invisibility-spec)))))
10065
10066 (defun org-in-invisibility-spec-p (arg)
10067 "Is ARG a member of `buffer-invisibility-spec'?."
10068 (if (consp buffer-invisibility-spec)
10069 (member arg buffer-invisibility-spec)
10070 nil))
10071
10072 (defun org-image-file-name-regexp ()
10073 "Return regexp matching the file names of images."
10074 (if (fboundp 'image-file-name-regexp)
10075 (image-file-name-regexp)
10076 (let ((image-file-name-extensions
10077 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
10078 "xbm" "xpm" "pbm" "pgm" "ppm")))
10079 (concat "\\."
10080 (regexp-opt (nconc (mapcar 'upcase
10081 image-file-name-extensions)
10082 image-file-name-extensions)
10083 t)
10084 "\\'"))))
10085
10086 ;; Functions needed for compatibility with old outline.el
10087
10088 ;; The following functions capture almost the entire compatibility code
10089 ;; between the different versions of outline-mode. The only other place
10090 ;; where this is important are the font-lock-keywords. Search for
10091 ;; `org-noutline-p' to find it.
10092
10093 ;; C-a should go to the beginning of a *visible* line, also in the
10094 ;; new outline.el. I guess this should be patched into Emacs?
10095 (defun org-beginning-of-line ()
10096 "Go to the beginning of the current line. If that is invisible, continue
10097 to a visible line beginning. This makes the function of C-a more intuitive."
10098 (interactive)
10099 (beginning-of-line 1)
10100 (if (bobp)
10101 nil
10102 (backward-char 1)
10103 (if (org-invisible-p)
10104 (while (and (not (bobp)) (org-invisible-p))
10105 (backward-char 1)
10106 (beginning-of-line 1))
10107 (forward-char 1))))
10108 (when org-noutline-p
10109 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
10110
10111 (defun org-invisible-p ()
10112 "Check if point is at a character currently not visible."
10113 (if org-noutline-p
10114 ;; Early versions of noutline don't have `outline-invisible-p'.
10115 (if (fboundp 'outline-invisible-p)
10116 (outline-invisible-p)
10117 (get-char-property (point) 'invisible))
10118 (save-excursion
10119 (skip-chars-backward "^\r\n")
10120 (equal (char-before) ?\r))))
10121
10122 (defun org-back-to-heading (&optional invisible-ok)
10123 "Move to previous heading line, or beg of this line if it's a heading.
10124 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
10125 (if org-noutline-p
10126 (outline-back-to-heading invisible-ok)
10127 (if (looking-at outline-regexp)
10128 t
10129 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
10130 outline-regexp)
10131 nil t)
10132 (if invisible-ok
10133 (progn (goto-char (match-end 1))
10134 (looking-at outline-regexp)))
10135 (error "Before first heading")))))
10136
10137 (defun org-on-heading-p (&optional invisible-ok)
10138 "Return t if point is on a (visible) heading line.
10139 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
10140 (if org-noutline-p
10141 (outline-on-heading-p 'invisible-ok)
10142 (save-excursion
10143 (skip-chars-backward "^\n\r")
10144 (and (looking-at outline-regexp)
10145 (or invisible-ok
10146 (bobp)
10147 (equal (char-before) ?\n))))))
10148
10149 (defun org-up-heading-all (arg)
10150 "Move to the heading line of which the present line is a subheading.
10151 This function considers both visible and invisible heading lines.
10152 With argument, move up ARG levels."
10153 (if org-noutline-p
10154 (if (fboundp 'outline-up-heading-all)
10155 (outline-up-heading-all arg) ; emacs 21 version of outline.el
10156 (outline-up-heading arg t)) ; emacs 22 version of outline.el
10157 (org-back-to-heading t)
10158 (looking-at outline-regexp)
10159 (if (<= (- (match-end 0) (match-beginning 0)) arg)
10160 (error "Cannot move up %d levels" arg)
10161 (re-search-backward
10162 (concat "[\n\r]" (regexp-quote
10163 (make-string (- (match-end 0) (match-beginning 0) arg)
10164 ?*))
10165 "[^*]"))
10166 (forward-char 1))))
10167
10168 (defun org-show-hidden-entry ()
10169 "Show an entry where even the heading is hidden."
10170 (save-excursion
10171 (if (not org-noutline-p)
10172 (progn
10173 (org-back-to-heading t)
10174 (org-flag-heading nil)))
10175 (org-show-entry)))
10176
10177 (defun org-check-occur-regexp (regexp)
10178 "If REGEXP starts with \"^\", modify it to check for \\r as well.
10179 Of course, only for the old outline mode."
10180 (if org-noutline-p
10181 regexp
10182 (if (string-match "^\\^" regexp)
10183 (concat "[\n\r]" (substring regexp 1))
10184 regexp)))
10185
10186 (defun org-flag-heading (flag &optional entry)
10187 "Flag the current heading. FLAG non-nil means make invisible.
10188 When ENTRY is non-nil, show the entire entry."
10189 (save-excursion
10190 (org-back-to-heading t)
10191 (if (not org-noutline-p)
10192 ;; Make the current headline visible
10193 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
10194 ;; Check if we should show the entire entry
10195 (if entry
10196 (progn
10197 (org-show-entry)
10198 (save-excursion ;; FIXME: Is this the fix for points in the -|
10199 ;; middle of text? |
10200 (and (outline-next-heading) ;; |
10201 (org-flag-heading nil)))) ; show the next heading _|
10202 (outline-flag-region (max 1 (1- (point)))
10203 (save-excursion (outline-end-of-heading) (point))
10204 (if org-noutline-p
10205 flag
10206 (if flag ?\r ?\n))))))
10207
10208 (defun org-show-subtree ()
10209 "Show everything after this heading at deeper levels."
10210 (outline-flag-region
10211 (point)
10212 (save-excursion
10213 (outline-end-of-subtree) (outline-next-heading) (point))
10214 (if org-noutline-p nil ?\n)))
10215
10216 (defun org-show-entry ()
10217 "Show the body directly following this heading.
10218 Show the heading too, if it is currently invisible."
10219 (interactive)
10220 (save-excursion
10221 (org-back-to-heading t)
10222 (outline-flag-region
10223 (1- (point))
10224 (save-excursion
10225 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
10226 (or (match-beginning 1) (point-max)))
10227 (if org-noutline-p nil ?\n))))
10228
10229
10230 (defun org-make-options-regexp (kwds)
10231 "Make a regular expression for keyword lines."
10232 (concat
10233 (if org-noutline-p "^" "[\n\r]")
10234 "#?[ \t]*\\+\\("
10235 (mapconcat 'regexp-quote kwds "\\|")
10236 "\\):[ \t]*"
10237 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10238
10239 ;; Make `bookmark-jump' show the jump location if it was hidden.
10240 (eval-after-load "bookmark"
10241 '(if (boundp 'bookmark-after-jump-hook)
10242 ;; We can use the hook
10243 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
10244 ;; Hook not available, use advice
10245 (defadvice bookmark-jump (after org-make-visible activate)
10246 "Make the position visible."
10247 (org-bookmark-jump-unhide))))
10248
10249 (defun org-bookmark-jump-unhide ()
10250 "Unhide the current position, to show the bookmark location."
10251 (and (eq major-mode 'org-mode)
10252 (or (org-invisible-p)
10253 (save-excursion (goto-char (max (point-min) (1- (point))))
10254 (org-invisible-p)))
10255 (org-show-hierarchy-above)))
10256
10257 ;;; Finish up
10258
10259 (provide 'org)
10260
10261 (run-hooks 'org-load-hook)
10262
10263 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10264 ;;; org.el ends here