]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-table-sum): Fix format string.
[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.16
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.16
84 ;; - In tables, directly after the field motion commands like TAB and RET,
85 ;; typing a character will blank the field. Can be turned off with
86 ;; variable `org-table-auto-blank-field'.
87 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
88 ;; and are not linked to the calendar.
89 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
90 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
91 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
92 ;; standard meaning of C-h after a prefix key (show prefix bindings).
93 ;;
94 ;; Version 3.15
95 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
96 ;; of unmodified entry text. `C-c :' toggles this keyword.
97 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
98 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
99 ;; color, to reduce the amount of aggressive color in the buffer.
100 ;;
101 ;; Version 3.14
102 ;; - Formulas for individual fields in table.
103 ;; - Automatic recalculation in calculating tables.
104 ;; - Named fields and columns in tables.
105 ;; - Fixed bug with calling `org-archive' several times in a row.
106 ;;
107 ;; Version 3.13
108 ;; - Efficiency improvements: Fewer table re-alignments needed.
109 ;; - New special lines in tables, for defining names for individual cells.
110 ;;
111 ;; Version 3.12
112 ;; - Tables can store formulas (one per column) and compute fields.
113 ;; Not quite like a full spreadsheet, but very powerful.
114 ;; - table.el keybinding is now `C-c ~'.
115 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
116 ;; - Small changes to keys in agenda buffer. Affected keys:
117 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
118 ;; - Bug fixes.
119 ;;
120 ;; Version 3.11
121 ;; - Links inserted with C-c C-l are now by default enclosed in angle
122 ;; brackets. See the new variable `org-link-format'.
123 ;; - ">" terminates a link, this is a way to have several links in a line.
124 ;; Both "<" and ">" are no longer allowed as characters in a link.
125 ;; - Archiving of finished tasks.
126 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
127 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
128 ;; - Compatibility problems with viper-mode fixed.
129 ;; - Improved html export of tables.
130 ;; - Various clean-up changes.
131 ;;
132 ;; Version 3.10
133 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
134 ;;
135 ;; Version 3.09
136 ;; - Time-of-day specifications in agenda are extracted and placed
137 ;; into the prefix. Timed entries can be placed into a time grid for
138 ;; day.
139 ;;
140 ;; Version 3.08
141 ;; - "|" no longer allowed as part of a link, to allow links in tables.
142 ;; - The prefix of items in the agenda buffer can be configured.
143 ;; - Cleanup.
144 ;;
145 ;; Version 3.07
146 ;; - Some folding incinsistencies removed.
147 ;; - BBDB links to company-only entries.
148 ;; - Bug fixes and global cleanup.
149 ;;
150 ;; Version 3.06
151 ;; - M-S-RET inserts a new TODO heading.
152 ;; - New startup option `content'.
153 ;; - Better visual response when TODO items in agenda change status.
154 ;; - Window positioning after visibility state changes optimized and made
155 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
156 ;;
157 ;; Version 3.05
158 ;; - Agenda entries from the diary are linked to the diary file, so
159 ;; adding and editing diary entries can be done directly from the agenda.
160 ;; - Many calendar/diary commands available directly from agenda.
161 ;; - Field copying in tables with S-RET does increment.
162 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
163 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
164 ;;
165 ;; Version 3.04
166 ;; - Table editor optimized to need fewer realignments, and to keep
167 ;; table shape when typing in fields.
168 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
169 ;; into arbitrary major modes.
170 ;; - Fixed bug with realignment in XEmacs.
171 ;; - Startup options can be set with special #+STARTUP line.
172 ;; - Heading following a match in org-occur can be suppressed.
173 ;;
174 ;; Version 3.03
175 ;; - Copyright transfer to the FSF.
176 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
177 ;; - Timeline now always contains today, and `.' jumps to it.
178 ;; - Table editor:
179 ;; - cut and paste of rectangular regions in tables
180 ;; - command to convert org-mode table to table.el table and back
181 ;; - command to treat several cells like a paragraph and fill it
182 ;; - command to convert a buffer region to a table
183 ;; - import/export tables as tab-separated files (exchange with Excel)
184 ;; - Agenda:
185 ;; - Sorting mechanism for agenda items rewritten from scratch.
186 ;; - Sorting fully configurable.
187 ;; - Entries specifying a time are sorted together.
188 ;; - Completion also covers option keywords after `#-'.
189 ;; - Bug fixes.
190 ;;
191 ;; Version 3.01
192 ;; - New reference card, thanks to Philip Rooke for creating it.
193 ;; - Single file agenda renamed to "Timeline". It no longer shows
194 ;; warnings about upcoming deadlines/overdue scheduled items.
195 ;; That functionality is now limited to the (multifile) agenda.
196 ;; - When reading a date, the calendar can be manipulated with keys.
197 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
198 ;; - Minor bug fixes and documentation improvements.
199
200 ;;; Code:
201
202 (eval-when-compile (require 'cl) (require 'calendar))
203 (require 'outline)
204 (require 'time-date)
205 (require 'easymenu)
206
207 (defvar calc-embedded-close-formula)
208 (defvar calc-embedded-open-formula)
209 (defvar font-lock-unfontify-region-function)
210
211 ;;; Customization variables
212
213 (defvar org-version "3.16"
214 "The version number of the file org.el.")
215 (defun org-version ()
216 (interactive)
217 (message "Org-mode version %s" org-version))
218
219 ;; The following two constants are for compatibility with different Emacs
220 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
221 ;; The compatibility code in org.el is based on these two constants.
222 (defconst org-xemacs-p (featurep 'xemacs)
223 "Are we running xemacs?")
224 (defconst org-noutline-p (featurep 'noutline)
225 "Are we using the new outline mode?")
226
227 (defgroup org nil
228 "Outline-based notes management and organizer "
229 :tag "Org"
230 :group 'outlines
231 :group 'hypermedia
232 :group 'calendar)
233
234 (defgroup org-startup nil
235 "Options concerning startup of Org-mode."
236 :tag "Org Startup"
237 :group 'org)
238
239 (defcustom org-CUA-compatible nil
240 "Non-nil means use alternative key bindings for S-<cursor movement>.
241 Org-mode used S-<cursor movement> for changing timestamps and priorities.
242 S-<cursor movement> is also used for example by `CUA-mode' to select text.
243 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
244 alternative bindings. Setting this variable to t will replace the following
245 keys both in Org-mode and in the Org-agenda buffer.
246
247 S-RET -> C-S-RET
248 S-up -> M-p
249 S-down -> M-n
250 S-left -> M--
251 S-right -> M-+
252
253 If you do not like the alternative keys, take a look at the variable
254 `org-disputed-keys'.
255
256 This option is only relevant at load-time of Org-mode. Changing it requires
257 a restart of Emacs to become effective."
258 :group 'org-startup
259 :type 'boolean)
260
261 (defvar org-disputed-keys
262 '((S-up [(shift up)] [(meta ?p)])
263 (S-down [(shift down)] [(meta ?n)])
264 (S-left [(shift left)] [(meta ?-)])
265 (S-right [(shift right)] [(meta ?+)])
266 (S-return [(shift return)] [(control shift return)]))
267 "Keys for which Org-mode and other modes compete.
268 This is an alist, cars are symbols for lookup, 1st element is the default key,
269 second element will be used when `org-CUA-compatible' is t.")
270
271 (defun org-key (key)
272 "Select a key according to `org-CUA-compatible'."
273 (nth (if org-CUA-compatible 2 1)
274 (or (assq key org-disputed-keys)
275 (error "Invalid Key %s in `org-key'" key))))
276
277 (defcustom org-startup-folded t
278 "Non-nil means, entering Org-mode will switch to OVERVIEW.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281
282 #+STARTUP: fold
283 #+STARTUP: nofold
284 #+STARTUP: content"
285 :group 'org-startup
286 :type '(choice
287 (const :tag "nofold: show all" nil)
288 (const :tag "fold: overview" t)
289 (const :tag "content: all headlines" content)))
290
291 (defcustom org-startup-truncated t
292 "Non-nil means, entering Org-mode will set `truncate-lines'.
293 This is useful since some lines containing links can be very long and
294 uninteresting. Also tables look terrible when wrapped."
295 :group 'org-startup
296 :type 'boolean)
297
298 (defcustom org-startup-with-deadline-check nil
299 "Non-nil means, entering Org-mode will run the deadline check.
300 This means, if you start editing an org file, you will get an
301 immediate reminder of any due deadlines.
302 This can also be configured on a per-file basis by adding one of
303 the following lines anywhere in the buffer:
304
305 #+STARTUP: dlcheck
306 #+STARTUP: nodlcheck"
307 :group 'org-startup
308 :type 'boolean)
309
310 (defcustom org-insert-mode-line-in-empty-file nil
311 "Non-nil means insert the first line setting Org-mode in empty files.
312 When the function `org-mode' is called interactively in an empty file, this
313 normally means that the file name does not automatically trigger Org-mode.
314 To ensure that the file will always be in Org-mode in the future, a
315 line enforcing Org-mode will be inserted into the buffer, if this option
316 has been set."
317 :group 'org-startup
318 :type 'boolean)
319
320 (defgroup org-keywords nil
321 "Options concerning TODO items in Org-mode."
322 :tag "Org Keywords"
323 :group 'org)
324
325 (defcustom org-todo-keywords '("TODO" "DONE")
326 "List of TODO entry keywords.
327 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
328 considered to mean that the entry is \"done\". All the other mean that
329 action is required, and will make the entry show up in todo lists, diaries
330 etc.
331 The command \\[org-todo] cycles an entry through these states, and an
332 additional state where no keyword is present. For details about this
333 cycling, see also the variable `org-todo-interpretation'
334 Changes become only effective after restarting Emacs."
335 :group 'org-keywords
336 :type '(repeat (string :tag "Keyword")))
337
338 (defcustom org-todo-interpretation 'sequence
339 "Controls how TODO keywords are interpreted.
340 \\<org-mode-map>Possible values are `sequence' and `type'.
341 This variable is only relevant if `org-todo-keywords' contains more than two
342 states. There are two ways how these keywords can be used:
343
344 - As a sequence in the process of working on a TODO item, for example
345 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
346 org-todo-interpretation 'sequence)
347
348 - As different types of TODO items, for example
349 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
350 org-todo-interpretation 'type)
351
352 When the states are interpreted as a sequence, \\[org-todo] always cycles
353 to the next state, in order to walk through all different states. So with
354 \\[org-todo], you turn an empty entry into the state TODO. When you started
355 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
356 later to VERIFY and finally to DONE.
357
358 When the states are interpreted as types, \\[org-todo] still cycles through
359 when it is called several times in direct succession, in order to initially
360 select the type. However, if not called immediately after a previous
361 \\[org-todo], it switches from each type directly to DONE. So with the
362 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
363 RELAXED. If you later return to this entry and press \\[org-todo] again,
364 RELAXED will not be changed REMIND, but directly to DONE.
365
366 You can create a large number of types. To initially select a
367 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
368 type with completion. Of course, you can also type the keyword
369 directly into the buffer. M-TAB completes TODO keywords at the
370 beginning of a headline."
371 :group 'org-keywords
372 :type '(choice (const sequence)
373 (const type)))
374
375 (defcustom org-default-priority ?B
376 "The default priority of TODO items.
377 This is the priority an item get if no explicit priority is given."
378 :group 'org-keywords
379 :type 'character)
380
381 (defcustom org-lowest-priority ?C
382 "The lowest priority of TODO items. A character like ?A, ?B etc."
383 :group 'org-keywords
384 :type 'character)
385
386 (defcustom org-deadline-string "DEADLINE:"
387 "String to mark deadline entries.
388 A deadline is this string, followed by a time stamp. Should be a word,
389 terminated by a colon. You can insert a schedule keyword and
390 a timestamp with \\[org-deadline].
391 Changes become only effective after restarting Emacs."
392 :group 'org-keywords
393 :type 'string)
394
395 (defcustom org-scheduled-string "SCHEDULED:"
396 "String to mark scheduled TODO entries.
397 A schedule is this string, followed by a time stamp. Should be a word,
398 terminated by a colon. You can insert a schedule keyword and
399 a timestamp with \\[org-schedule].
400 Changes become only effective after restarting Emacs."
401 :group 'org-keywords
402 :type 'string)
403
404 (defcustom org-comment-string "COMMENT"
405 "Entries starting with this keyword will never be exported.
406 An entry can be toggled between COMMENT and normal with
407 \\[org-toggle-comment].
408 Changes become only effective after restarting Emacs."
409 :group 'org-keywords
410 :type 'string)
411
412 (defcustom org-quote-string "QUOTE"
413 "Entries starting with this keyword will be exported in fixed-width font.
414 Quoting applies only to the text in the entry following the headline, and does
415 not extend beyond the next headline, even if that is lower level.
416 An entry can be toggled between QUOTE and normal with
417 \\[org-toggle-fixed-width-section]"
418 :group 'org-keywords
419 :type 'string)
420
421 (defcustom org-after-todo-state-change-hook nil
422 "Hook which is run after the state of a TODO item was changed.
423 The new state (a string with a todo keyword, or nil) is available in the
424 Lisp variable `state'."
425 :group 'org-keywords
426 :type 'hook)
427
428 ;; Variables for pre-computed regular expressions, all buffer local
429 (defvar org-todo-kwd-priority-p nil
430 "Do TODO items have priorities?")
431 (make-variable-buffer-local 'org-todo-kwd-priority-p)
432 (defvar org-todo-kwd-max-priority nil
433 "Maximum priority of TODO items.")
434 (make-variable-buffer-local 'org-todo-kwd-max-priority)
435 (defvar org-ds-keyword-length 12
436 "Maximum length of the Deadline and SCHEDULED keywords.")
437 (make-variable-buffer-local 'org-ds-keyword-length)
438 (defvar org-done-string nil
439 "The last string in `org-todo-keywords', indicating an item is DONE.")
440 (make-variable-buffer-local 'org-done-string)
441 (defvar org-todo-regexp nil
442 "Matches any of the TODO state keywords.")
443 (make-variable-buffer-local 'org-todo-regexp)
444 (defvar org-not-done-regexp nil
445 "Matches any of the TODO state keywords except the last one.")
446 (make-variable-buffer-local 'org-not-done-regexp)
447 (defvar org-todo-line-regexp nil
448 "Matches a headline and puts TODO state into group 2 if present.")
449 (make-variable-buffer-local 'org-todo-line-regexp)
450 (defvar org-nl-done-regexp nil
451 "Matches newline followed by a headline with the DONE keyword.")
452 (make-variable-buffer-local 'org-nl-done-regexp)
453 (defvar org-looking-at-done-regexp nil
454 "Matches the DONE keyword a point.")
455 (make-variable-buffer-local 'org-looking-at-done-regexp)
456 (defvar org-deadline-regexp nil
457 "Matches the DEADLINE keyword.")
458 (make-variable-buffer-local 'org-deadline-regexp)
459 (defvar org-deadline-time-regexp nil
460 "Matches the DEADLINE keyword together with a time stamp.")
461 (make-variable-buffer-local 'org-deadline-time-regexp)
462 (defvar org-deadline-line-regexp nil
463 "Matches the DEADLINE keyword and the rest of the line.")
464 (make-variable-buffer-local 'org-deadline-line-regexp)
465 (defvar org-scheduled-regexp nil
466 "Matches the SCHEDULED keyword.")
467 (make-variable-buffer-local 'org-scheduled-regexp)
468 (defvar org-scheduled-time-regexp nil
469 "Matches the SCHEDULED keyword together with a time stamp.")
470 (make-variable-buffer-local 'org-scheduled-time-regexp)
471
472 (defvar org-category nil
473 "Variable used by org files to set a category for agenda display.
474 Such files should use a file variable to set it, for example
475
476 -*- mode: org; org-category: \"ELisp\"
477
478 or contain a special line
479
480 #+CATEGORY: ELisp
481
482 If the file does not specify a category, then file's base name
483 is used instead.")
484
485 (defun org-set-regexps-and-options ()
486 "Precompute regular expressions for current buffer."
487 (when (eq major-mode 'org-mode)
488 (let ((re (org-make-options-regexp
489 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
490 "STARTUP" "ARCHIVE")))
491 (splitre "[ \t]+")
492 kwds int key value cat arch)
493 (save-excursion
494 (save-restriction
495 (widen)
496 (goto-char (point-min))
497 (while (re-search-forward re nil t)
498 (setq key (match-string 1) value (match-string 2))
499 (cond
500 ((equal key "CATEGORY")
501 (if (string-match "[ \t]+$" value)
502 (setq value (replace-match "" t t value)))
503 (setq cat (intern value)))
504 ((equal key "SEQ_TODO")
505 (setq int 'sequence
506 kwds (append kwds (org-split-string value splitre))))
507 ((equal key "PRI_TODO")
508 (setq int 'priority
509 kwds (append kwds (org-split-string value splitre))))
510 ((equal key "TYP_TODO")
511 (setq int 'type
512 kwds (append kwds (org-split-string value splitre))))
513 ((equal key "STARTUP")
514 (let ((opts (org-split-string value splitre))
515 (set '(("fold" org-startup-folded t)
516 ("nofold" org-startup-folded nil)
517 ("content" org-startup-folded content)
518 ("dlcheck" org-startup-with-deadline-check t)
519 ("nodlcheck" org-startup-with-deadline-check nil)))
520 l var val)
521 (while (setq l (assoc (pop opts) set))
522 (setq var (nth 1 l) val (nth 2 l))
523 (set (make-local-variable var) val))))
524 ((equal key "ARCHIVE")
525 (string-match " *$" value)
526 (setq arch (replace-match "" t t value))
527 (remove-text-properties 0 (length arch)
528 '(face t fontified t) arch)))
529 )))
530 (and cat (set (make-local-variable 'org-category) cat))
531 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
532 (and arch (set (make-local-variable 'org-archive-location) arch))
533 (and int (set (make-local-variable 'org-todo-interpretation) int)))
534 ;; Compute the regular expressions and other local variables
535 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
536 org-todo-kwd-max-priority (1- (length org-todo-keywords))
537 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
538 (length org-scheduled-string)))
539 org-done-string
540 (nth (1- (length org-todo-keywords)) org-todo-keywords)
541 org-todo-regexp
542 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
543 "\\|") "\\)\\>")
544 org-not-done-regexp
545 (concat "\\<\\("
546 (mapconcat 'regexp-quote
547 (nreverse (cdr (reverse org-todo-keywords)))
548 "\\|")
549 "\\)\\>")
550 org-todo-line-regexp
551 (concat "^\\(\\*+\\)[ \t]*\\("
552 (mapconcat 'regexp-quote org-todo-keywords "\\|")
553 "\\)? *\\(.*\\)")
554 org-nl-done-regexp
555 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
556 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
557 org-deadline-regexp (concat "\\<" org-deadline-string)
558 org-deadline-time-regexp
559 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
560 org-deadline-line-regexp
561 (concat "\\<\\(" org-deadline-string "\\).*")
562 org-scheduled-regexp
563 (concat "\\<" org-scheduled-string)
564 org-scheduled-time-regexp
565 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
566 (org-set-font-lock-defaults)))
567
568 (defgroup org-time nil
569 "Options concerning time stamps and deadlines in Org-mode."
570 :tag "Org Time"
571 :group 'org)
572
573 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
574 "Formats for `format-time-string' which are used for time stamps.
575 It is not recommended to change this constant.")
576
577
578 (defcustom org-deadline-warning-days 30
579 "No. of days before expiration during which a deadline becomes active.
580 This variable governs the display in the org file."
581 :group 'org-time
582 :type 'number)
583
584 (defcustom org-popup-calendar-for-date-prompt t
585 "Non-nil means, pop up a calendar when prompting for a date.
586 In the calendar, the date can be selected with mouse-1. However, the
587 minibuffer will also be active, and you can simply enter the date as well.
588 When nil, only the minibuffer will be available."
589 :group 'org-time
590 :type 'number)
591
592 (defcustom org-calendar-follow-timestamp-change t
593 "Non-nil means, make the calendar window follow timestamp changes.
594 When a timestamp is modified and the calendar window is visible, it will be
595 moved to the new date."
596 :group 'org-time
597 :type 'boolean)
598
599 (defgroup org-agenda nil
600 "Options concerning agenda display Org-mode."
601 :tag "Org Agenda"
602 :group 'org)
603
604 (defcustom org-agenda-files nil
605 "A list of org files for agenda/diary display.
606 Entries are added to this list with \\[org-add-file] and removed with
607 \\[org-remove-file]. You can also use customize to edit the list."
608 :group 'org-agenda
609 :type '(repeat file))
610
611 (defcustom org-select-timeline-window t
612 "Non-nil means, after creating a timeline, move cursor into Timeline window.
613 When nil, cursor will remain in the current window."
614 :group 'org-agenda
615 :type 'boolean)
616
617 (defcustom org-select-agenda-window t
618 "Non-nil means, after creating an agenda, move cursor into Agenda window.
619 When nil, cursor will remain in the current window."
620 :group 'org-agenda
621 :type 'boolean)
622
623 (defcustom org-fit-agenda-window t
624 "Non-nil means, change window size of agenda to fit content."
625 :group 'org-agenda
626 :type 'boolean)
627
628 (defcustom org-agenda-show-all-dates t
629 "Non-nil means, `org-agenda' shows every day in the selected range.
630 When nil, only the days which actually have entries are shown."
631 :group 'org-agenda
632 :type 'boolean)
633
634 ;; FIXME: First day of month works only for current month because it would
635 ;; require a variable ndays treatment.
636 (defcustom org-agenda-start-on-weekday 1
637 "Non-nil means, start the overview always on the specified weekday.
638 0 Denotes Sunday, 1 denotes Monday etc.
639 When nil, always start on the current day."
640 :group 'org-agenda
641 :type '(choice (const :tag "Today" nil)
642 (const :tag "First day of month" t)
643 (number :tag "Weekday No.")))
644
645 (defcustom org-agenda-ndays 7
646 "Number of days to include in overview display."
647 :group 'org-agenda
648 :type 'number)
649
650 (defcustom org-agenda-include-all-todo t
651 "Non-nil means, the agenda will always contain all TODO entries.
652 When nil, date-less entries will only be shown if `org-agenda' is called
653 with a prefix argument.
654 When non-nil, the TODO entries will be listed at the top of the agenda, before
655 the entries for specific days."
656 :group 'org-agenda
657 :type 'boolean)
658
659 (defcustom org-agenda-include-diary nil
660 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
661 :group 'org-agenda
662 :type 'boolean)
663
664 (defcustom org-calendar-to-agenda-key [?c]
665 "The key to be installed in `calendar-mode-map' for switching to the agenda.
666 The command `org-calendar-goto-agenda' will be bound to this key. The
667 default is the character `c' because then`c' can be used to switch back and
668 force between agenda and calendar."
669 :group 'org-agenda
670 :type 'sexp)
671
672 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
673 "Sorting structure for the agenda items of a single day.
674 This is a list of symbols which will be used in sequence to determine
675 if an entry should be listed before another entry. The following
676 symbols are recognized.
677
678 time-up Put entries with time-of-day indications first, early first
679 time-down Put entries with time-of-day indications first, late first
680 category-keep Keep the default order of categories, corresponding to the
681 sequence in `org-agenda-files'.
682 category-up Sort alphabetically by category, A-Z.
683 category-down Sort alphabetically by category, Z-A.
684 priority-up Sort numerically by priority, high priority last.
685 priority-down Sort numerically by priority, high priority first.
686
687 The different possibilities will be tried in sequence, and testing stops
688 if one comparison returns a \"not-equal\". For example, the default
689 '(time-up category-keep priority-down)
690 means: Pull out all entries having a specified time of day and sort them,
691 in order to make a time schedule for the current day the first thing in the
692 agenda listing for the day. Of the entries without a time indication, keep
693 the grouped in categories, don't sort the categories, but keep them in
694 the sequence given in `org-agenda-files'. Within each category sort by
695 priority.
696
697 Leaving out `category-keep' would mean that items will be sorted across
698 categories by priority."
699 :group 'org-agenda
700 :type '(repeat
701 (choice
702 (const time-up)
703 (const time-down)
704 (const category-keep)
705 (const category-up)
706 (const category-down)
707 (const priority-up)
708 (const priority-down))))
709
710 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
711 "Format specification for the prefix of items in the agenda buffer.
712 This format works similar to a printf format, with the following meaning:
713
714 %c the category of the item, \"Diary\" for entries from the diary, or
715 as given by the CATEGORY keyword or derived from the file name.
716 %t the time-of-day specification if one applies to the entry, in the
717 format HH:MM
718 %s Scheduling/Deadline information, a short string
719
720 All specifiers work basically like the standard `%s' of printf, but may
721 contain two additional characters: A question mark just after the `%' and
722 a whitespace/punctuation character just before the final letter.
723
724 If the first character after `%' is a question mark, the entire field
725 will only be included if the corresponding value applies to the
726 current entry. This is useful for fields which should have fixed
727 width when present, but zero width when absent. For example,
728 \"%?-12t\" will result in a 12 character time field if a time of the
729 day is specified, but will completely disappear in entries which do
730 not contain a time.
731
732 If there is punctuation or whitespace character just before the final
733 format letter, this character will be appended to the field value if
734 the value is not empty. For example, the format \"%-12:c\" leads to
735 \"Diary: \" if the category is \"Diary\". If the category were be
736 empty, no additional colon would be interted.
737
738 The default value of this option is \" %-12:c%?-12t% s\", meaning:
739 - Indent the line with two space characters
740 - Give the category in a 12 chars wide field, padded with whitespace on
741 the right (because of `-'). Append a colon if there is a category
742 (because of `:').
743 - If there is a time-of-day, put it into a 12 chars wide field. If no
744 time, don't put in an empty field, just skip it (because of '?').
745 - Finally, put the scheduling information and append a whitespace.
746
747 As another example, if you don't want the time-of-day of entries in
748 the prefix, you could use:
749
750 (setq org-agenda-prefix-format \" %-11:c% s\")
751
752 See also the variable `org-agenda-remove-times-when-in-prefix'."
753 :type 'string
754 :group 'org-agenda)
755
756 (defcustom org-timeline-prefix-format " % s"
757 "Like `org-agenda-prefix-format', but for the timeline of a single file."
758 :type 'string
759 :group 'org-agenda)
760
761 (defvar org-prefix-format-compiled nil
762 "The compiled version of the most recently used prefix format.
763 Depending on which command was used last, this may be the compiled version
764 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
765
766 (defcustom org-agenda-use-time-grid t
767 "Non-nil means, show a time grid in the agenda schedule.
768 A time grid is a set of lines for specific times (like every two hours between
769 8:00 and 20:00. The items scheduled for a day at specific times are
770 sorted in between these lines.
771 For deails about when the grid will be shown, and what it will look like, see
772 the variable `org-agenda-time-grid'."
773 :group 'org-agenda
774 :type 'boolean)
775
776 (defcustom org-agenda-time-grid
777 '((daily today require-timed)
778 "----------------"
779 (800 1000 1200 1400 1600 1800 2000))
780
781 "The settings for time grid for agenda display.
782 This is a list of three items. The first item is again a list. It contains
783 symbols specifying conditions when the grid should be displayed:
784
785 daily if the agenda shows a single day
786 weekly if the agenda shows an entire week
787 today show grid on current date, independent of daily/weekly display
788 require-timed show grid only if at least on item has a time specification
789
790 The second item is a string which will be places behing the grid time.
791
792 The third item is a list of integers, indicating the times that should have
793 a grid line."
794 :group 'org-agenda
795 :type
796 '(list
797 (set :greedy t :tag "Grid Display Options"
798 (const :tag "Show grid in single day agenda display" daily)
799 (const :tag "Show grid in weekly agenda display" weekly)
800 (const :tag "Always show grid for today" today)
801 (const :tag "Show grid only if any timed entries are present"
802 require-timed)
803 (const :tag "Skip grid times already present in an entry"
804 remove-match))
805 (string :tag "Grid String")
806 (repeat :tag "Grid Times" (integer :tag "Time"))))
807
808 (defcustom org-agenda-remove-times-when-in-prefix t
809 "Non-nil means, remove duplicate time specifications in agenda items.
810 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
811 time-of-day specification in a headline or diary entry is extracted and
812 placed into the prefix. If this option is non-nil, the original specification
813 \(a timestamp or -range, or just a plain time(range) specification like
814 11:30-4pm) will be removed for agenda display. This makes the agenda less
815 cluttered.
816 The option can be t or nil. It may also be the symbol `beg', indicating
817 that the time should only be removed what it is located at the beginning of
818 the headline/diary entry."
819 :group 'org-agenda
820 :type '(choice
821 (const :tag "Always" t)
822 (const :tag "Never" nil)
823 (const :tag "When at beginning of entry" beg)))
824
825 (defcustom org-sort-agenda-notime-is-late t
826 "Non-nil means, items without time are considered late.
827 This is only relevant for sorting. When t, items which have no explicit
828 time like 15:30 will be considered as 24:01, i.e. later than any items which
829 do have a time. When nil, the default time is before 0:00. You can use this
830 option to decide if the schedule for today should come before or after timeless
831 agenda entries."
832 :group 'org-agenda
833 :type 'boolean)
834
835 (defgroup org-structure nil
836 "Options concerning structure editing in Org-mode."
837 :tag "Org Structure"
838 :group 'org)
839
840 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
841 "Hook that is run after `org-cycle' has changed the buffer visibility.
842 The function(s) in this hook must accept a single argument which indicates
843 the new state that was set by the most recent `org-cycle' command. The
844 argument is a symbol. After a global state change, it can have the values
845 `overview', `content', or `all'. After a local state change, it can have
846 the values `folded', `children', or `subtree'."
847 :group 'org-structure
848 :type 'hook)
849
850 (defcustom org-occur-hook '(org-first-headline-recenter)
851 "Hook that is run after `org-occur' has constructed a sparse tree.
852 This can be used to recenter the window to show as much of the structure
853 as possible."
854 :group 'org-structure
855 :type 'hook)
856
857 (defcustom org-level-color-stars-only nil
858 "Non-nil means fontify only the stars in each headline.
859 When nil, the entire headline is fontified.
860 After changin this, requires restart of Emacs to become effective."
861 :group 'org-structure
862 :type 'boolean)
863
864 (defcustom org-adapt-indentation t
865 "Non-nil means, adapt indentation when promoting and demoting.
866 When this is set and the *entire* text in an entry is indented, the
867 indentation is increased by one space in a demotion command, and
868 decreased by one in a promotion command. If any line in the entry
869 body starts at column 0, indentation is not changed at all."
870 :group 'org-structure
871 :type 'boolean)
872
873 (defcustom org-enable-fixed-width-editor t
874 "Non-nil means, lines starting with \":\" are treated as fixed-width.
875 This currently only means, they are never auto-wrapped.
876 When nil, such lines will be treated like ordinary lines.
877 See also the QUOTE keyword."
878 :group 'org-structure
879 :type 'boolean)
880
881 (defcustom org-cycle-emulate-tab t
882 "Where should `org-cycle' emulate TAB.
883 nil Never
884 white Only in completely white lines
885 t Everywhere except in headlines"
886 :group 'org-structure
887 :type '(choice (const :tag "Never" nil)
888 (const :tag "Only in completely white lines" white)
889 (const :tag "Everywhere except in headlines" t)
890 ))
891
892 (defcustom org-show-following-heading t
893 "Non-nil means, show heading following match in `org-occur'.
894 When doing an `org-occur' it is useful to show the headline which
895 follows the match, even if they do not match the regexp. This makes it
896 easier to edit directly inside the sparse tree. However, if you use
897 org-occur mainly as an overview, the following headlines are
898 unnecessary clutter."
899 :group 'org-structure
900 :type 'boolean)
901
902 (defcustom org-archive-location "%s_archive::"
903 "The location where subtrees should be archived.
904 This string consists of two parts, separated by a double-colon.
905
906 The first part is a file name - when omitted, archiving happens in the same
907 file. %s will be replaced by the current file name (without directory part).
908 Archiving to a different file is useful to keep archived entries from
909 contributing to the Org-mode Agenda.
910
911 The part after the double colon is a headline. The archived entries will be
912 filed under that headline. When omitted, the subtrees are simply filed away
913 at the end of the file, as top-level entries.
914
915 Here are a few examples:
916 \"%s_archive::\"
917 If the current file is Projects.org, archive in file
918 Projects.org_archive, as top-level trees. This is the default.
919
920 \"::* Archived Tasks\"
921 Archive in the current file, under the top-level headline
922 \"* Archived Tasks\".
923
924 \"~/org/archive.org::\"
925 Archive in file ~/org/archive.org (absolute path), as top-level trees.
926
927 \"basement::** Finished Tasks\"
928 Archive in file ./basement (relative path), as level 3 trees
929 below the level 2 heading \"** Finished Tasks\".
930
931 You may set this option on a per-file basis by adding to the buffer a
932 line like
933
934 #+ARCHIVE: basement::** Finished Tasks"
935 :group 'org-structure
936 :type 'string)
937
938 (defcustom org-archive-mark-done t
939 "Non-nil means, mark archived entries as DONE."
940 :group 'org-structure
941 :type 'boolean)
942
943 (defcustom org-archive-stamp-time t
944 "Non-nil means, add a time stamp to archived entries.
945 The time stamp will be added directly after the TODO state keyword in the
946 first line, so it is probably best to use this in combinations with
947 `org-archive-mark-done'."
948 :group 'org-structure
949 :type 'boolean)
950
951 (defgroup org-link nil
952 "Options concerning links in Org-mode."
953 :tag "Org Link"
954 :group 'org)
955
956 (defcustom org-link-format "<%s>"
957 "Default format for linkes in the buffer.
958 This is a format string for printf, %s will be replaced by the link text.
959 If you want to make sure that your link is always properly terminated,
960 include angle brackets into this format, like \"<%s>\". Some people also
961 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
962 :group 'org-link
963 :type '(choice
964 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
965 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
966 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
967 (string :tag "Other" :value "<%s>")))
968
969 (defcustom org-allow-space-in-links t
970 "Non-nil means, file names in links may contain space characters.
971 When nil, it becomes possible to put several links into a line.
972 Note that in tables, a link never extends accross fields, so in a table
973 it is always possible to put several links into a line.
974 Changing this varable requires a re-launch of Emacs of become effective."
975 :group 'org-link
976 :type 'boolean)
977
978 (defcustom org-line-numbers-in-file-links t
979 "Non-nil means, file links from `org-store-link' contain line numbers.
980 The line number will be added to the file name with :NNN and interpreted
981 by the command `org-open-at-point'.
982 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
983 negates this setting for the duration of the command."
984 :group 'org-link
985 :type 'boolean)
986
987 (defcustom org-keep-stored-link-after-insertion nil
988 "Non-nil means, keep link in list for entire session.
989
990 The command `org-store-link' adds a link pointing to the current
991 location to an internal list. These links accumulate during a session.
992 The command `org-insert-link' can be used to insert links into any
993 Org-mode file (offering completion for all stored links). When this
994 option is nil, every link which has been inserted once using \\[org-insert-link]
995 will be removed from the list, to make completing the unused links
996 more efficient."
997 :group 'org-link
998 :type 'boolean)
999
1000 (defcustom org-link-frame-setup
1001 '((vm . vm-visit-folder-other-frame)
1002 (gnus . gnus-other-frame)
1003 (file . find-file-other-window))
1004 "Setup the frame configuration for following links.
1005 When following a link with Emacs, it may often be useful to display
1006 this link in another window or frame. This variable can be used to
1007 set this up for the different types of links.
1008 For VM, use any of
1009 `vm-visit-folder'
1010 `vm-visit-folder-other-frame'
1011 For Gnus, use any of
1012 `gnus'
1013 `gnus-other-frame'
1014 For FILE, use any of
1015 `find-file'
1016 `find-file-other-window'
1017 `find-file-other-frame'
1018 For the calendar, use the variable `calendar-setup'.
1019 For BBDB, it is currently only possible to display the matches in
1020 another window."
1021 :group 'org-link
1022 :type '(list
1023 (cons (const vm)
1024 (choice
1025 (const vm-visit-folder)
1026 (const vm-visit-folder-other-window)
1027 (const vm-visit-folder-other-frame)))
1028 (cons (const gnus)
1029 (choice
1030 (const gnus)
1031 (const gnus-other-frame)))
1032 (cons (const file)
1033 (choice
1034 (const find-file)
1035 (const find-file-other-window)
1036 (const find-file-other-frame)))))
1037
1038 (defcustom org-usenet-links-prefer-google nil
1039 "Non-nil means, `org-store-link' will create web links to google groups.
1040 When nil, Gnus will be used for such links.
1041 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1042 negates this setting for the duration of the command."
1043 :group 'org-link
1044 :type 'boolean)
1045
1046 (defcustom org-open-non-existing-files nil
1047 "Non-nil means, `org-open-file' will open non-existing file.
1048 When nil, an error will be generated."
1049 :group 'org-link
1050 :type 'boolean)
1051
1052 (defcustom org-confirm-shell-links t
1053 "Non-nil means, ask for confirmation before executing shell links.
1054 The default is true, to keep new users from shooting into their own foot."
1055 :group 'org-link
1056 :type 'boolean)
1057
1058 (defconst org-file-apps-defaults-gnu
1059 '((t . emacs)
1060 ("jpg" . "xv %s")
1061 ("gif" . "xv %s")
1062 ("ppm" . "xv %s")
1063 ("pgm" . "xv %s")
1064 ("pbm" . "xv %s")
1065 ("tif" . "xv %s")
1066 ("png" . "xv %s")
1067 ("ps" . "gv %s")
1068 ("ps.gz" . "gv %s")
1069 ("eps" . "gv %s")
1070 ("eps.gz" . "gv %s")
1071 ("dvi" . "xdvi %s")
1072 ("mpeg" . "plaympeg %s")
1073 ("mp3" . "plaympeg %s")
1074 ("fig" . "xfig %s")
1075 ("pdf" . "acroread %s")
1076 ("doc" . "soffice %s")
1077 ("ppt" . "soffice %s")
1078 ("pps" . "soffice %s")
1079 ("html" . "netscape -remote openURL(%s,new-window)")
1080 ("htm" . "netscape -remote openURL(%s,new-window)")
1081 ("xs" . "soffice %s"))
1082 "Default file applications on a UNIX/LINUX system.
1083 See `org-file-apps'.")
1084
1085 (defconst org-file-apps-defaults-macosx
1086 '((t . "open %s")
1087 ("ps" . "gv %s")
1088 ("ps.gz" . "gv %s")
1089 ("eps" . "gv %s")
1090 ("eps.gz" . "gv %s")
1091 ("dvi" . "xdvi %s")
1092 ("fig" . "xfig %s"))
1093 "Default file applications on a MacOS X system.
1094 The system \"open\" is known as a default, but we use X11 applications
1095 for some files for which the OS does not have a good default.
1096 See `org-file-apps'.")
1097
1098 (defconst org-file-apps-defaults-windowsnt
1099 '((t . (w32-shell-execute "open" file)))
1100 "Default file applications on a Windows NT system.
1101 The system \"open\" is used for most files.
1102 See `org-file-apps'.")
1103
1104 (defcustom org-file-apps
1105 '(
1106 ("txt" . emacs)
1107 ("tex" . emacs)
1108 ("ltx" . emacs)
1109 ("org" . emacs)
1110 ("el" . emacs)
1111 )
1112 "External applications for opening `file:path' items in a document.
1113 Org-mode uses system defaults for different file types, but
1114 you can use this variable to set the application for a given file
1115 extension. The entries in this list are cons cells with a file extension
1116 and the corresponding command. Possible values for the command are:
1117 `emacs' The file will be visited by the current Emacs process.
1118 `default' Use the default application for this file type.
1119 string A command to be executed by a shell; %s will be replaced
1120 by the path to the file.
1121 sexp A Lisp form which will be evaluated. The file path will
1122 be available in the Lisp variable `file'.
1123 For more examples, see the system specific constants
1124 `org-file-apps-defaults-macosx'
1125 `org-file-apps-defaults-windowsnt'
1126 `org-file-apps-defaults-gnu'."
1127 :group 'org-link
1128 :type '(repeat
1129 (cons (string :tag "Extension")
1130 (choice :value ""
1131 (const :tag "Visit with Emacs" 'emacs)
1132 (const :tag "Use system default" 'default)
1133 (string :tag "Command")
1134 (sexp :tag "Lisp form")))))
1135
1136
1137 (defgroup org-remember nil
1138 "Options concerning interaction with remember.el."
1139 :tag "Org Remember"
1140 :group 'org)
1141
1142 (defcustom org-directory "~/org"
1143 "Directory with org files.
1144 This directory will be used as default to prompt for org files.
1145 Used by the hooks for remember.el."
1146 :group 'org-remember
1147 :type 'directory)
1148
1149 (defcustom org-default-notes-file "~/.notes"
1150 "Default target for storing notes.
1151 Used by the hooks for remember.el. This can be a string, or nil to mean
1152 the value of `remember-data-file'."
1153 :group 'org-remember
1154 :type '(choice
1155 (const :tag "Default from remember-data-file" nil)
1156 file))
1157
1158 (defcustom org-reverse-note-order nil
1159 "Non-nil means, store new notes at the beginning of a file or entry.
1160 When nil, new notes will be filed to the end of a file or entry."
1161 :group 'org-remember
1162 :type '(choice
1163 (const :tag "Reverse always" t)
1164 (const :tag "Reverse never" nil)
1165 (repeat :tag "By file name regexp"
1166 (cons regexp boolean))))
1167
1168 (defgroup org-table nil
1169 "Options concerning tables in Org-mode."
1170 :tag "Org Table"
1171 :group 'org)
1172
1173 (defcustom org-enable-table-editor 'optimized
1174 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1175 When nil, such lines will be treated like ordinary lines.
1176
1177 When equal to the symbol `optimized', the table editor will be optimized to
1178 do the following
1179 - Use automatic overwrite mode in front of whitespace in table fields.
1180 This make the structure of the table stay in tact as long as the edited
1181 field does not exceed the column width.
1182 - Minimize the number of realigns. Normally, the table is aligned each time
1183 TAB or RET are pressed to move to another field. With optimization this
1184 happens only if changes to a field might have changed the column width.
1185 Optimization requires replacing the functions `self-insert-command',
1186 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1187 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1188 very good at guessing when a re-align will be necessary, but you can always
1189 force one with \\[org-ctrl-c-ctrl-c].
1190
1191 If you would like to use the optimized version in Org-mode, but the
1192 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1193
1194 This variable can be used to turn on and off the table editor during a session,
1195 but in order to toggle optimization, a restart is required.
1196
1197 See also the variable `org-table-auto-blank-field'."
1198 :group 'org-table
1199 :type '(choice
1200 (const :tag "off" nil)
1201 (const :tag "on" t)
1202 (const :tag "on, optimized" optimized)))
1203
1204 (defcustom org-table-auto-blank-field t
1205 "Non-nil means, automatically blank table field when starting to type into it.
1206 This only happens when typing immediately after a field motion
1207 command (TAB, S-TAB or RET).
1208 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1209 :group 'org-table
1210 :type 'boolean)
1211
1212 (defcustom org-table-default-size "5x2"
1213 "The default size for newly created tables, Columns x Rows."
1214 :group 'org-table
1215 :type 'string)
1216
1217 (defcustom org-table-automatic-realign t
1218 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1219 When nil, aligning is only done with \\[org-table-align], or after column
1220 removal/insertion."
1221 :group 'org-table
1222 :type 'boolean)
1223
1224 (defcustom org-table-spaces-around-separators '(1 . 1)
1225 "The number of spaces to be placed before and after separators."
1226 :group 'org-table
1227 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1228
1229 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1230 "The number of spaces to be placed before and after separators.
1231 This option applies when the column separators have been made invisible."
1232 :group 'org-table
1233 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1234
1235 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1236 "Regular expression for recognizing numbers in table columns.
1237 If a table column contains mostly numbers, it will be aligned to the
1238 right. If not, it will be aligned to the left.
1239
1240 The default value of this option is a regular expression which allows
1241 anything which looks remotely like a number as used in scientific
1242 context. For example, all of the following will be considered a
1243 number:
1244 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1245
1246 Other options offered by the customize interface are more restrictive."
1247 :group 'org-table
1248 :type '(choice
1249 (const :tag "Positive Integers"
1250 "^[0-9]+$")
1251 (const :tag "Integers"
1252 "^[-+]?[0-9]+$")
1253 (const :tag "Floating Point Numbers"
1254 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1255 (const :tag "Floating Point Number or Integer"
1256 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1257 (const :tag "Exponential, Floating point, Integer"
1258 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1259 (const :tag "Very General Number-Like"
1260 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1261 (string :tag "Regexp:")))
1262
1263 (defcustom org-table-number-fraction 0.5
1264 "Fraction of numbers in a column required to make the column align right.
1265 In a column all non-white fields are considered. If at least this
1266 fraction of fields is matched by `org-table-number-fraction',
1267 alignment to the right border applies."
1268 :group 'org-table
1269 :type 'number)
1270
1271 (defcustom org-export-highlight-first-table-line t
1272 "Non-nil means, highlight the first table line.
1273 In HTML export, this means use <th> instead of <td>.
1274 In tables created with table.el, this applies to the first table line.
1275 In Org-mode tables, all lines before the first horizontal separator
1276 line will be formatted with <th> tags."
1277 :group 'org-table
1278 :type 'boolean)
1279
1280 (defcustom org-table-tab-recognizes-table.el t
1281 "Non-nil means, TAB will automatically notice a table.el table.
1282 When it sees such a table, it moves point into it and - if necessary -
1283 calls `table-recognize-table'."
1284 :group 'org-table
1285 :type 'boolean)
1286
1287 (defgroup org-table-calculation nil
1288 "Options concerning tables in Org-mode."
1289 :tag "Org Table Calculation"
1290 :group 'org)
1291
1292 (defcustom org-table-copy-increment t
1293 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1294 :group 'org-table-calculation
1295 :type 'boolean)
1296
1297 (defcustom org-calc-default-modes
1298 '(calc-internal-prec 12
1299 calc-float-format (float 5)
1300 calc-angle-mode deg
1301 calc-prefer-frac nil
1302 calc-symbolic-mode nil
1303 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1304 calc-display-working-message t
1305 )
1306 "List with Calc mode settings for use in calc-eval for table formulas.
1307 The list must contain alternating symbols (calc modes variables and values.
1308 Don't remove any of the default settings, just change the values. Org-mode
1309 relies on the variables to be present in the list."
1310 :group 'org-table-calculation
1311 :type 'plist)
1312
1313 (defcustom org-table-formula-evaluate-inline t
1314 "Non-nil means, TAB and RET evaluate a formula in current table field.
1315 If the current field starts with an equal sign, it is assumed to be a formula
1316 which should be evaluated as described in the manual and in the documentation
1317 string of the command `org-table-eval-formula'. This feature requires the
1318 Emacs calc package.
1319 When this variable is nil, formula calculation is only available through
1320 the command \\[org-table-eval-formula]."
1321 :group 'org-table-calculation
1322 :type 'boolean)
1323
1324
1325 (defcustom org-table-formula-use-constants t
1326 "Non-nil means, interpret constants in formulas in tables.
1327 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1328 by the value given in `org-table-formula-constants', or by a value obtained
1329 from the `constants.el' package."
1330 :group 'org-table-calculation
1331 :type 'boolean)
1332
1333 (defcustom org-table-formula-constants nil
1334 "Alist with constant names and values, for use in table formulas.
1335 The car of each element is a name of a constant, without the `$' before it.
1336 The cdr is the value as a string. For example, if you'd like to use the
1337 speed of light in a formula, you would configure
1338
1339 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1340
1341 and then use it in an equation like `$1*$c'."
1342 :group 'org-table-calculation
1343 :type '(repeat
1344 (cons (string :tag "name")
1345 (string :tag "value"))))
1346
1347 (defcustom org-table-formula-numbers-only nil
1348 "Non-nil means, calculate only with numbers in table formulas.
1349 Then all input fields will be converted to a number, and the result
1350 must also be a number. When nil, calc's full potential is available
1351 in table calculations, including symbolics etc."
1352 :group 'org-table-calculation
1353 :type 'boolean)
1354
1355 (defcustom org-table-allow-automatic-line-recalculation t
1356 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1357 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1358 :group 'org-table-calculation
1359 :type 'boolean)
1360
1361 (defgroup org-export nil
1362 "Options for exporting org-listings."
1363 :tag "Org Export"
1364 :group 'org)
1365
1366 (defcustom org-export-language-setup
1367 '(("en" "Author" "Date" "Table of Contents")
1368 ("da" "Ophavsmand" "Dato" "Indhold")
1369 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1370 ("es" "Autor" "Fecha" "\xccndice")
1371 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1372 ("it" "Autore" "Data" "Indice")
1373 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1374 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1375 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1376 "Terms used in export text, translated to different languages.
1377 Use the variable `org-export-default-language' to set the language,
1378 or use the +OPTION lines for a per-file setting."
1379 :group 'org-export
1380 :type '(repeat
1381 (list
1382 (string :tag "HTML language tag")
1383 (string :tag "Author")
1384 (string :tag "Date")
1385 (string :tag "Table of Contents"))))
1386
1387 (defcustom org-export-default-language "en"
1388 "The default language of HTML export, as a string.
1389 This should have an association in `org-export-language-setup'"
1390 :group 'org-export
1391 :type 'string)
1392
1393 (defcustom org-export-headline-levels 3
1394 "The last level which is still exported as a headline.
1395 Inferior levels will produce itemize lists when exported.
1396 Note that a numeric prefix argument to an exporter function overrides
1397 this setting.
1398
1399 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1400 :group 'org-export
1401 :type 'number)
1402
1403 (defcustom org-export-with-section-numbers t
1404 "Non-nil means, add section numbers to headlines when exporting.
1405
1406 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1407 :group 'org-export
1408 :type 'boolean)
1409
1410 (defcustom org-export-with-toc t
1411 "Non-nil means, create a table of contents in exported files.
1412 The TOC contains headlines with levels up to`org-export-headline-levels'.
1413
1414 Headlines which contain any TODO items will be marked with \"(*)\" in
1415 ASCII export, and with red color in HTML output.
1416
1417 In HTML output, the TOC will be clickable.
1418
1419 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1420 :group 'org-export
1421 :type 'boolean)
1422
1423 (defcustom org-export-preserve-breaks nil
1424 "Non-nil means, preserve all line breaks when exporting.
1425 Normally, in HTML output paragraphs will be reformatted. In ASCII
1426 export, line breaks will always be preserved, regardless of this variable.
1427
1428 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1429 :group 'org-export
1430 :type 'boolean)
1431
1432 (defcustom org-export-html-inline-images t
1433 "Non-nil means, inline images into exported HTML pages.
1434 The link will still be to the original location of the image file.
1435 So if you are moving the page, lets say to your public HTML site,
1436 you will have to move the image and maybe change the link."
1437 :group 'org-export
1438 :type 'boolean)
1439
1440 (defcustom org-export-html-expand t
1441 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1442 When nil, these tags will be exported as plain text and therefore
1443 not be interpreted by a browser.
1444
1445 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1446 :group 'org-export
1447 :type 'boolean)
1448
1449 (defcustom org-export-with-fixed-width t
1450 "Non-nil means, lines starting with \":\" will be in fixed width font.
1451 This can be used to have pre-formatted text, fragments of code etc. For
1452 example
1453 : ;; Some Lisp examples
1454 : (while (defc cnt)
1455 : (ding))
1456 will be looking just like this in also HTML. In ASCII export, this option
1457 has no effect.
1458
1459 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1460 :group 'org-export
1461 :type 'boolean)
1462
1463 (defcustom org-export-with-tables t
1464 "If non-nil, lines starting with \"|\" define a table.
1465 For example:
1466
1467 | Name | Address | Birthday |
1468 |-------------+----------+-----------|
1469 | Arthur Dent | England | 29.2.2100 |
1470
1471 In ASCII export, this option has no effect.
1472
1473 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1474 :group 'org-export
1475 :type 'boolean)
1476
1477 (defcustom org-export-prefer-native-exporter-for-tables nil
1478 "Non-nil means, always export tables created with table.el natively.
1479 Natively means, use the HTML code generator in table.el.
1480 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1481 the table does not use row- or column-spanning). This has the
1482 advantage, that the automatic HTML conversions for math symbols and
1483 sub/superscripts can be applied. Org-mode's HTML generator is also
1484 much faster."
1485 :group 'org-export
1486 :type 'boolean)
1487
1488 (defcustom org-export-html-table-tag
1489 "<table border=1 cellspacing=0 cellpadding=6>"
1490 "The HTML tag used to start a table.
1491 This must be a <table> tag, but you may change the options like
1492 borders and spacing."
1493 :group 'org-export
1494 :type 'string)
1495
1496 (defcustom org-export-with-emphasize t
1497 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1498 If the export target supports emphasizing text, the word will be
1499 typeset in bold, italic, or underlined, respectively. Works only for
1500 single words, but you can say: I *really* *mean* *this*.
1501 In ASCII export, this option has no effect.
1502
1503 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1504 :group 'org-export
1505 :type 'boolean)
1506
1507 (defcustom org-match-sexp-depth 3
1508 "Number of stacked braces for sub/superscript matching.
1509 This has to be set before loading org.el to be effective."
1510 :group 'org-export
1511 :type 'integer)
1512
1513 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1514 (defcustom org-export-with-sub-superscripts t
1515 "Non-nil means, interpret \"_\" and \"^\" for export.
1516 When this option is turned on, you can use TeX-like syntax for sub- and
1517 superscripts. Several characters after \"_\" or \"^\" will be
1518 considered as a single item - so grouping with {} is normally not
1519 needed. For example, the following things will be parsed as single
1520 sub- or superscripts.
1521
1522 10^24 or 10^tau several digits will be considered 1 item
1523 10^-12 or 10^-tau a leading sign with digits or a word
1524 x^2-y^3 will be read as x^2 - y^3, because items are
1525 terminated by almost any nonword/nondigit char.
1526 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1527
1528 Still, ambiguity is possible - so when in doubt use {} to enclose the
1529 sub/superscript.
1530 In ASCII export, this option has no effect.
1531
1532 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1533 :group 'org-export
1534 :type 'boolean)
1535
1536 (defcustom org-export-with-TeX-macros t
1537 "Non-nil means, interpret simple TeX-like macros when exporting.
1538 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1539 No only real TeX macros will work here, but the standard HTML entities
1540 for math can be used as macro names as well. For a list of supported
1541 names in HTML export, see the constant `org-html-entities'.
1542 In ASCII export, this option has no effect.
1543
1544 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1545 :group 'org-export
1546 :type 'boolean)
1547
1548 (defcustom org-export-html-with-timestamp nil
1549 "If non-nil, write `org-export-html-html-helper-timestamp'
1550 into the exported html text. Otherwise, the buffer will just be saved
1551 to a file."
1552 :group 'org-export
1553 :type 'boolean)
1554
1555 (defcustom org-export-html-html-helper-timestamp
1556 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1557 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1558 :group 'org-export
1559 :type 'string)
1560
1561 (defcustom org-export-ascii-show-new-buffer t
1562 "Non-nil means, popup buffer containing the exported ASCII text.
1563 Otherwise the buffer will just be saved to a file and stay hidden."
1564 :group 'org-export
1565 :type 'boolean)
1566
1567 (defcustom org-export-html-show-new-buffer nil
1568 "Non-nil means, popup buffer containing the exported html text.
1569 Otherwise, the buffer will just be saved to a file and stay hidden."
1570 :group 'org-export
1571 :type 'boolean)
1572
1573 (defgroup org-faces nil
1574 "Faces for highlighting in Org-mode."
1575 :tag "Org Faces"
1576 :group 'org)
1577
1578 (defface org-level-1 ;; font-lock-function-name-face
1579 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1580 (((class color) (background light)) (:foreground "Blue"))
1581 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1582 (t (:inverse-video t :bold t)))
1583 "Face used for level 1 headlines."
1584 :group 'org-faces)
1585
1586 (defface org-level-2 ;; font-lock-variable-name-face
1587 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1588 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1589 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1590 (t (:bold t :italic t)))
1591 "Face used for level 2 headlines."
1592 :group 'org-faces)
1593
1594 (defface org-level-3 ;; font-lock-keyword-face
1595 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1596 (((class color) (background light)) (:foreground "Purple"))
1597 (((class color) (background dark)) (:foreground "Cyan"))
1598 (t (:bold t)))
1599 "Face used for level 3 headlines."
1600 :group 'org-faces)
1601
1602 (defface org-level-4 ;; font-lock-comment-face
1603 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1604 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1605 (((class color) (background light)) (:foreground "Firebrick"))
1606 (((class color) (background dark)) (:foreground "chocolate1"))
1607 (t (:bold t :italic t)))
1608 "Face used for level 4 headlines."
1609 :group 'org-faces)
1610
1611 (defface org-level-5 ;; font-lock-type-face
1612 '((((type tty) (class color)) (:foreground "green"))
1613 (((class color) (background light)) (:foreground "ForestGreen"))
1614 (((class color) (background dark)) (:foreground "PaleGreen"))
1615 (t (:bold t :underline t)))
1616 "Face used for level 5 headlines."
1617 :group 'org-faces)
1618
1619 (defface org-level-6 ;; font-lock-constant-face
1620 '((((type tty) (class color)) (:foreground "magenta"))
1621 (((class color) (background light)) (:foreground "CadetBlue"))
1622 (((class color) (background dark)) (:foreground "Aquamarine"))
1623 (t (:bold t :underline t)))
1624 "Face used for level 6 headlines."
1625 :group 'org-faces)
1626
1627 (defface org-level-7 ;; font-lock-builtin-face
1628 '((((type tty) (class color)) (:foreground "blue" :weight light))
1629 (((class color) (background light)) (:foreground "Orchid"))
1630 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1631 (t (:bold t)))
1632 "Face used for level 7 headlines."
1633 :group 'org-faces)
1634
1635 (defface org-level-8 ;; font-lock-string-face
1636 '((((type tty) (class color)) (:foreground "green"))
1637 (((class color) (background light)) (:foreground "RosyBrown"))
1638 (((class color) (background dark)) (:foreground "LightSalmon"))
1639 (t (:italic t)))
1640 "Face used for level 8 headlines."
1641 :group 'org-faces)
1642
1643 (defface org-special-keyword ;; font-lock-string-face
1644 '((((type tty) (class color)) (:foreground "green"))
1645 (((class color) (background light)) (:foreground "RosyBrown"))
1646 (((class color) (background dark)) (:foreground "LightSalmon"))
1647 (t (:italic t)))
1648 "Face used for level 8 headlines."
1649 :group 'org-faces)
1650
1651 (defface org-warning ;; font-lock-warning-face
1652 '((((type tty) (class color)) (:foreground "red"))
1653 (((class color) (background light)) (:foreground "Red" :bold t))
1654 (((class color) (background dark)) (:foreground "Red1" :bold t))
1655 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1656 (t (:inverse-video t :bold t)))
1657 "Face for deadlines and TODO keywords."
1658 :group 'org-faces)
1659
1660 (defcustom org-fontify-done-headline nil
1661 "Non-nil means, change the face of a headline if it is marked DONE.
1662 Normally, only the TODO/DONE keyword indicates the state of a headline.
1663 When this is non-nil, the headline after the keyword is set to the
1664 `org-headline-done' as an additional indication."
1665 :group 'org-faces
1666 :type 'boolean)
1667
1668 (defface org-headline-done ;; font-lock-string-face
1669 '((((type tty) (class color)) (:foreground "green"))
1670 (((class color) (background light)) (:foreground "RosyBrown"))
1671 (((class color) (background dark)) (:foreground "LightSalmon"))
1672 (t (:italic t)))
1673 "Face used to indicate that a headline is DONE. See also the variable
1674 `org-fontify-done-headline'."
1675 :group 'org-faces)
1676
1677 ;; Inheritance does not yet work for xemacs. So we just copy...
1678
1679 (defface org-deadline-announce
1680 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1681 (((class color) (background light)) (:foreground "Blue"))
1682 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1683 (t (:inverse-video t :bold t)))
1684 "Face for upcoming deadlines."
1685 :group 'org-faces)
1686
1687 (defface org-scheduled-today
1688 '((((type tty) (class color)) (:foreground "green"))
1689 (((class color) (background light)) (:foreground "DarkGreen"))
1690 (((class color) (background dark)) (:foreground "PaleGreen"))
1691 (t (:bold t :underline t)))
1692 "Face for items scheduled for a certain day."
1693 :group 'org-faces)
1694
1695 (defface org-scheduled-previously
1696 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1697 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1698 (((class color) (background light)) (:foreground "Firebrick"))
1699 (((class color) (background dark)) (:foreground "chocolate1"))
1700 (t (:bold t :italic t)))
1701 "Face for items scheduled previously, and not yet done."
1702 :group 'org-faces)
1703
1704 (defface org-formula
1705 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1706 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1707 (((class color) (background light)) (:foreground "Firebrick"))
1708 (((class color) (background dark)) (:foreground "chocolate1"))
1709 (t (:bold t :italic t)))
1710 "Face for items scheduled previously, and not yet done."
1711 :group 'org-faces)
1712
1713 (defface org-link
1714 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1715 (((class color) (background light)) (:foreground "Purple"))
1716 (((class color) (background dark)) (:foreground "Cyan"))
1717 (t (:bold t)))
1718 "Face for links."
1719 :group 'org-faces)
1720
1721 (defface org-done ;; font-lock-type-face
1722 '((((type tty) (class color)) (:foreground "green"))
1723 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1724 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1725 (t (:bold t :underline t)))
1726 "Face used for DONE."
1727 :group 'org-faces)
1728
1729 (defface org-table ;; font-lock-function-name-face
1730 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1731 (((class color) (background light)) (:foreground "Blue"))
1732 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1733 (t (:inverse-video t :bold t)))
1734 "Face used for tables."
1735 :group 'org-faces)
1736
1737 (defface org-time-grid ;; font-lock-variable-name-face
1738 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1739 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1740 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1741 (t (:bold t :italic t)))
1742 "Face used for level 2 headlines."
1743 :group 'org-faces)
1744
1745 (defvar org-level-faces
1746 '(
1747 org-level-1
1748 org-level-2
1749 org-level-3
1750 org-level-4
1751 org-level-5
1752 org-level-6
1753 org-level-7
1754 org-level-8
1755 ))
1756 (defvar org-n-levels (length org-level-faces))
1757
1758 ;; Tell the compiler about dynamically scoped variables,
1759 ;; and variables from other packages
1760 (eval-when-compile
1761 (defvar zmacs-regions)
1762 (defvar original-date)
1763 (defvar org-transient-mark-mode)
1764 (defvar org-old-auto-fill-inhibit-regexp)
1765 (defvar orgtbl-mode-menu)
1766 (defvar org-html-entities)
1767 (defvar org-goto-start-pos)
1768 (defvar org-cursor-color)
1769 (defvar org-time-was-given)
1770 (defvar org-ts-what)
1771 (defvar mark-active)
1772 (defvar timecnt)
1773 (defvar levels-open)
1774 (defvar title)
1775 (defvar author)
1776 (defvar email)
1777 (defvar text)
1778 (defvar entry)
1779 (defvar date)
1780 (defvar language)
1781 (defvar options)
1782 (defvar ans1)
1783 (defvar ans2)
1784 (defvar starting-day)
1785 (defvar include-all-loc)
1786 (defvar vm-message-pointer)
1787 (defvar vm-folder-directory)
1788 (defvar wl-summary-buffer-elmo-folder)
1789 (defvar wl-summary-buffer-folder-name)
1790 (defvar gnus-group-name)
1791 (defvar gnus-article-current)
1792 (defvar w3m-current-url)
1793 (defvar org-selected-point)
1794 (defvar calendar-mode-map)
1795 (defvar remember-save-after-remembering)
1796 (defvar remember-data-file))
1797
1798
1799 ;;; Define the mode
1800
1801 (defvar org-mode-map (copy-keymap outline-mode-map)
1802 "Keymap for Org-mode.")
1803
1804 (defvar org-struct-menu)
1805 (defvar org-org-menu)
1806 (defvar org-tbl-menu)
1807
1808 ;; We use a before-change function to check if a table might need
1809 ;; an update.
1810 (defvar org-table-may-need-update t
1811 "Indicates of a table might need an update.
1812 This variable is set by `org-before-change-function'. `org-table-align'
1813 sets it back to nil.")
1814 (defvar org-mode-hook nil)
1815 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1816
1817
1818 ;;;###autoload
1819 (define-derived-mode org-mode outline-mode "Org"
1820 "Outline-based notes management and organizer, alias
1821 \"Carstens outline-mode for keeping track of everything.\"
1822
1823 Org-mode develops organizational tasks around a NOTES file which
1824 contains information about projects as plain text. Org-mode is
1825 implemented on top of outline-mode, which is ideal to keep the content
1826 of large files well structured. It supports ToDo items, deadlines and
1827 time stamps, which magically appear in the diary listing of the Emacs
1828 calendar. Tables are easily created with a built-in table editor.
1829 Plain text URL-like links connect to websites, emails (VM), Usenet
1830 messages (Gnus), BBDB entries, and any files related to the project.
1831 For printing and sharing of notes, an Org-mode file (or a part of it)
1832 can be exported as a structured ASCII or HTML file.
1833
1834 The following commands are available:
1835
1836 \\{org-mode-map}"
1837 (easy-menu-add org-org-menu)
1838 (easy-menu-add org-tbl-menu)
1839 (org-install-agenda-files-menu)
1840 (setq outline-regexp "\\*+")
1841 (if org-startup-truncated (setq truncate-lines t))
1842 (org-set-regexps-and-options)
1843 (set (make-local-variable 'font-lock-unfontify-region-function)
1844 'org-unfontify-region)
1845 ;; Activate before-change-function
1846 (set (make-local-variable 'org-table-may-need-update) t)
1847 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1848 (add-hook 'before-change-functions 'org-before-change-function nil
1849 'local)
1850 ;; Paragraph regular expressions
1851 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1852 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1853 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1854 (set (make-local-variable 'auto-fill-inhibit-regexp)
1855 (concat "\\*\\|#"
1856 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1857 (concat
1858 "\\|[ \t]*["
1859 (if org-enable-table-editor "|" "")
1860 (if org-enable-fixed-width-editor ":" "")
1861 "]"))))
1862 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1863 ;; Settings for Calc embedded mode
1864 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1865 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1866 (if (and org-insert-mode-line-in-empty-file
1867 (interactive-p)
1868 (= (point-min) (point-max)))
1869 (insert " -*- mode: org -*-\n\n"))
1870
1871 ;; Get rid of Outline menus, they are not needed
1872 ;; Need to do this here because define-derived-mode sets up
1873 ;; the keymap so late.
1874 (if org-xemacs-p
1875 (progn
1876 (delete-menu-item '("Headings"))
1877 (delete-menu-item '("Show"))
1878 (delete-menu-item '("Hide"))
1879 (set-menubar-dirty-flag))
1880 (define-key org-mode-map [menu-bar headings] 'undefined)
1881 (define-key org-mode-map [menu-bar hide] 'undefined)
1882 (define-key org-mode-map [menu-bar show] 'undefined))
1883
1884 (unless org-inhibit-startup
1885 (if org-startup-with-deadline-check
1886 (call-interactively 'org-check-deadlines)
1887 (cond
1888 ((eq org-startup-folded t)
1889 (org-cycle '(4)))
1890 ((eq org-startup-folded 'content)
1891 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1892 (org-cycle '(4)) (org-cycle '(4))))))))
1893
1894 (defun org-fill-paragraph (&optional justify)
1895 "Re-align a table, pass through to fill-paragraph if no table."
1896 (save-excursion
1897 (beginning-of-line 1)
1898 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1899
1900 (defsubst org-current-line (&optional pos)
1901 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1902
1903 ;;; Font-Lock stuff
1904
1905 (defvar org-mouse-map (make-sparse-keymap))
1906 (define-key org-mouse-map
1907 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1908 (define-key org-mouse-map
1909 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1910
1911 (require 'font-lock)
1912
1913 (defconst org-non-link-chars "\t\n\r|<>\000")
1914 (defconst org-link-regexp
1915 (if org-allow-space-in-links
1916 (concat
1917 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1918 (concat
1919 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1920 )
1921 "Regular expression for matching links.")
1922 (defconst org-link-maybe-angles-regexp
1923 (concat "<?\\(" org-link-regexp "\\)>?")
1924 "Matches a link and optionally surrounding angle brackets.")
1925 (defconst org-protected-link-regexp
1926 (concat "\000" org-link-regexp "\000")
1927 "Matches a link and optionally surrounding angle brackets.")
1928
1929 (defconst org-ts-lengths
1930 (cons (length (format-time-string (car org-time-stamp-formats)))
1931 (length (format-time-string (cdr org-time-stamp-formats))))
1932 "This holds the lengths of the two different time formats.")
1933 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1934 "Regular expression for fast time stamp matching.")
1935 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1936 "Regular expression matching time strings for analysis.")
1937 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1938 "Regular expression matching time stamps, with groups.")
1939 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1940 "Regular expression matching a time stamp range.")
1941 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1942 org-ts-regexp "\\)?")
1943 "Regular expression matching a time stamp or time stamp range.")
1944
1945 (defun org-activate-links (limit)
1946 "Run through the buffer and add overlays to links."
1947 (if (re-search-forward org-link-regexp limit t)
1948 (progn
1949 (add-text-properties (match-beginning 0) (match-end 0)
1950 (list 'mouse-face 'highlight
1951 'keymap org-mouse-map))
1952 t)))
1953
1954 (defun org-activate-dates (limit)
1955 "Run through the buffer and add overlays to dates."
1956 (if (re-search-forward org-tsr-regexp limit t)
1957 (progn
1958 (add-text-properties (match-beginning 0) (match-end 0)
1959 (list 'mouse-face 'highlight
1960 'keymap org-mouse-map))
1961 t)))
1962
1963 (defun org-font-lock-level ()
1964 (save-excursion
1965 (org-back-to-heading t)
1966 (- (match-end 0) (match-beginning 0))))
1967
1968 (defvar org-font-lock-keywords nil)
1969
1970 (defun org-set-font-lock-defaults ()
1971 (let ((org-font-lock-extra-keywords
1972 (list
1973 '(org-activate-links (0 'org-link))
1974 '(org-activate-dates (0 'org-link))
1975 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1976 '(1 'org-warning t))
1977 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
1978 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1979 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1980 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
1981 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
1982 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1983 ;; (3 'bold))
1984 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1985 ;; (3 'italic))
1986 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1987 ;; (3 'underline))
1988 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1989 ; '(1 'org-warning t))
1990 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
1991 "\\|" org-quote-string "\\)\\>")
1992 '(1 'org-special-keyword t))
1993 '("^#.*" (0 'font-lock-comment-face t))
1994 (if org-fontify-done-headline
1995 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1996 '(1 'org-done t) '(2 'org-headline-done t))
1997 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1998 '(1 'org-done t)))
1999 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2000 (1 'org-table t))
2001 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2002 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2003 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2004 )))
2005 (set (make-local-variable 'org-font-lock-keywords)
2006 (append
2007 (if org-noutline-p ; FIXME: I am not sure if eval will work
2008 ; on XEmacs if noutline is ever ported
2009 `((eval . (list "^\\(\\*+\\).*"
2010 ,(if org-level-color-stars-only 1 0)
2011 '(nth ;; FIXME: 1<->0 ????
2012 (% (- (match-end 1) (match-beginning 1) 1)
2013 org-n-levels)
2014 org-level-faces)
2015 nil t)))
2016 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2017 (,(if org-level-color-stars-only 2 0)
2018 (nth (% (- (match-end 2) (match-beginning 2) 1)
2019 org-n-levels)
2020 org-level-faces)
2021 nil t))))
2022 org-font-lock-extra-keywords))
2023 (set (make-local-variable 'font-lock-defaults)
2024 '(org-font-lock-keywords t nil nil backward-paragraph))
2025 (kill-local-variable 'font-lock-keywords) nil))
2026
2027 (defun org-unfontify-region (beg end &optional maybe_loudly)
2028 "Remove fontification and activation overlays from links."
2029 (font-lock-default-unfontify-region beg end)
2030 (let* ((buffer-undo-list t)
2031 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2032 (inhibit-modification-hooks t)
2033 deactivate-mark buffer-file-name buffer-file-truename)
2034 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2035
2036 ;;; Visibility cycling
2037
2038 (defvar org-cycle-global-status nil)
2039 (defvar org-cycle-subtree-status nil)
2040 (defun org-cycle (&optional arg)
2041 "Visibility cycling for Org-mode.
2042
2043 - When this function is called with a prefix argument, rotate the entire
2044 buffer through 3 states (global cycling)
2045 1. OVERVIEW: Show only top-level headlines.
2046 2. CONTENTS: Show all headlines of all levels, but no body text.
2047 3. SHOW ALL: Show everything.
2048
2049 - When point is at the beginning of a headline, rotate the subtree started
2050 by this line through 3 different states (local cycling)
2051 1. FOLDED: Only the main headline is shown.
2052 2. CHILDREN: The main headline and the direct children are shown. From
2053 this state, you can move to one of the children and
2054 zoom in further.
2055 3. SUBTREE: Show the entire subtree, including body text.
2056
2057 - When there is a numeric prefix, go up to a heading with level ARG, do
2058 a `show-subtree' and return to the previous cursor position. If ARG
2059 is negative, go up that many levels.
2060
2061 - When point is not at the beginning of a headline, execute
2062 `indent-relative', like TAB normally does. See the option
2063 `org-cycle-emulate-tab' for details.
2064
2065 - Special case: if point is the the beginning of the buffer and there is
2066 no headline in line 1, this function will act as if called with prefix arg."
2067 (interactive "P")
2068
2069 (if (or (and (bobp) (not (looking-at outline-regexp)))
2070 (equal arg '(4)))
2071 ;; special case: use global cycling
2072 (setq arg t))
2073
2074 (cond
2075
2076 ((org-at-table-p 'any)
2077 ;; Enter the table or move to the next field in the table
2078 (or (org-table-recognize-table.el)
2079 (progn
2080 (org-table-justify-field-maybe)
2081 (org-table-next-field))))
2082
2083 ((eq arg t) ;; Global cycling
2084
2085 (cond
2086 ((and (eq last-command this-command)
2087 (eq org-cycle-global-status 'overview))
2088 ;; We just created the overview - now do table of contents
2089 ;; This can be slow in very large buffers, so indicate action
2090 (message "CONTENTS...")
2091 (save-excursion
2092 ;; Visit all headings and show their offspring
2093 (goto-char (point-max))
2094 (catch 'exit
2095 (while (and (progn (condition-case nil
2096 (outline-previous-visible-heading 1)
2097 (error (goto-char (point-min))))
2098 t)
2099 (looking-at outline-regexp))
2100 (show-branches)
2101 (if (bobp) (throw 'exit nil))))
2102 (message "CONTENTS...done"))
2103 (setq org-cycle-global-status 'contents)
2104 (run-hook-with-args 'org-cycle-hook 'contents))
2105
2106 ((and (eq last-command this-command)
2107 (eq org-cycle-global-status 'contents))
2108 ;; We just showed the table of contents - now show everything
2109 (show-all)
2110 (message "SHOW ALL")
2111 (setq org-cycle-global-status 'all)
2112 (run-hook-with-args 'org-cycle-hook 'all))
2113
2114 (t
2115 ;; Default action: go to overview
2116 (hide-sublevels 1)
2117 (message "OVERVIEW")
2118 (setq org-cycle-global-status 'overview)
2119 (run-hook-with-args 'org-cycle-hook 'overview))))
2120
2121 ((integerp arg)
2122 ;; Show-subtree, ARG levels up from here.
2123 (save-excursion
2124 (org-back-to-heading)
2125 (outline-up-heading (if (< arg 0) (- arg)
2126 (- (outline-level) arg)))
2127 (org-show-subtree)))
2128
2129 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2130 ;; At a heading: rotate between three different views
2131 (org-back-to-heading)
2132 (let ((goal-column 0) eoh eol eos)
2133 ;; First, some boundaries
2134 (save-excursion
2135 (org-back-to-heading)
2136 (save-excursion
2137 (beginning-of-line 2)
2138 (while (and (not (eobp)) ;; this is like `next-line'
2139 (get-char-property (1- (point)) 'invisible))
2140 (beginning-of-line 2)) (setq eol (point)))
2141 (outline-end-of-heading) (setq eoh (point))
2142 (outline-end-of-subtree) (setq eos (point))
2143 (outline-next-heading))
2144 ;; Find out what to do next and set `this-command'
2145 (cond
2146 ((= eos eoh)
2147 ;; Nothing is hidden behind this heading
2148 (message "EMPTY ENTRY")
2149 (setq org-cycle-subtree-status nil))
2150 ((>= eol eos)
2151 ;; Entire subtree is hidden in one line: open it
2152 (org-show-entry)
2153 (show-children)
2154 (message "CHILDREN")
2155 (setq org-cycle-subtree-status 'children)
2156 (run-hook-with-args 'org-cycle-hook 'children))
2157 ((and (eq last-command this-command)
2158 (eq org-cycle-subtree-status 'children))
2159 ;; We just showed the children, now show everything.
2160 (org-show-subtree)
2161 (message "SUBTREE")
2162 (setq org-cycle-subtree-status 'subtree)
2163 (run-hook-with-args 'org-cycle-hook 'subtree))
2164 (t
2165 ;; Default action: hide the subtree.
2166 (hide-subtree)
2167 (message "FOLDED")
2168 (setq org-cycle-subtree-status 'folded)
2169 (run-hook-with-args 'org-cycle-hook 'folded)))))
2170
2171 ;; TAB emulation
2172 (buffer-read-only (org-back-to-heading))
2173 ((if (and (eq org-cycle-emulate-tab 'white)
2174 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2175 t
2176 (eq org-cycle-emulate-tab t))
2177 (if (and (looking-at "[ \n\r\t]")
2178 (string-match "^[ \t]*$" (buffer-substring
2179 (point-at-bol) (point))))
2180 (progn
2181 (beginning-of-line 1)
2182 (and (looking-at "[ \t]+") (replace-match ""))))
2183 (indent-relative))
2184
2185 (t (save-excursion
2186 (org-back-to-heading)
2187 (org-cycle)))))
2188
2189 (defun org-optimize-window-after-visibility-change (state)
2190 "Adjust the window after a change in outline visibility.
2191 This function is the default value of the hook `org-cycle-hook'."
2192 (cond
2193 ((eq state 'overview) (org-first-headline-recenter 1))
2194 ((eq state 'content) nil)
2195 ((eq state 'all) nil)
2196 ((eq state 'folded) nil)
2197 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2198 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2199
2200 (defun org-subtree-end-visible-p ()
2201 "Is the end of the current subtree visible?"
2202 (pos-visible-in-window-p
2203 (save-excursion (outline-end-of-subtree) (point))))
2204
2205 (defun org-first-headline-recenter (&optional N)
2206 "Move cursor to the first headline and recenter the headline.
2207 Optional argument N means, put the headline into the Nth line of the window."
2208 (goto-char (point-min))
2209 (when (re-search-forward (concat "^" outline-regexp) nil t)
2210 (beginning-of-line)
2211 (recenter (prefix-numeric-value N))))
2212
2213 (defvar org-goto-window-configuration nil)
2214 (defvar org-goto-marker nil)
2215 (defvar org-goto-map (make-sparse-keymap))
2216 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2217 (while (setq cmd (pop cmds))
2218 (substitute-key-definition cmd cmd org-goto-map global-map)))
2219 (define-key org-goto-map "\C-m" 'org-goto-ret)
2220 (define-key org-goto-map [(left)] 'org-goto-left)
2221 (define-key org-goto-map [(right)] 'org-goto-right)
2222 (define-key org-goto-map [(?q)] 'org-goto-quit)
2223 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2224 (define-key org-goto-map "\C-i" 'org-cycle)
2225 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2226 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2227 (define-key org-goto-map "n" 'outline-next-visible-heading)
2228 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2229 (define-key org-goto-map "f" 'outline-forward-same-level)
2230 (define-key org-goto-map "b" 'outline-backward-same-level)
2231 (define-key org-goto-map "u" 'outline-up-heading)
2232 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2233 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2234 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2235 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2236 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2237 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2238 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2239
2240 (defconst org-goto-help
2241 "Select a location to jump to, press RET
2242 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2243
2244 (defun org-goto ()
2245 "Go to a different location of the document, keeping current visibility.
2246
2247 When you want to go to a different location in a document, the fastest way
2248 is often to fold the entire buffer and then dive into the tree. This
2249 method has the disadvantage, that the previous location will be folded,
2250 which may not be what you want.
2251
2252 This command works around this by showing a copy of the current buffer in
2253 overview mode. You can dive into the tree in that copy, to find the
2254 location you want to reach. When pressing RET, the command returns to the
2255 original buffer in which the visibility is still unchanged. It then jumps
2256 to the new location, making it and the headline hierarchy above it visible."
2257 (interactive)
2258 (let* ((org-goto-start-pos (point))
2259 (selected-point
2260 (org-get-location (current-buffer) org-goto-help)))
2261 (if selected-point
2262 (progn
2263 (goto-char selected-point)
2264 (if (org-invisible-p) (org-show-hierarchy-above)))
2265 (error "Quit"))))
2266
2267 (defun org-get-location (buf help)
2268 "Let the user select a location in the Org-mode buffer BUF.
2269 This function uses a recursive edit. It returns the selected position
2270 or nil."
2271 (let (org-selected-point)
2272 (save-excursion
2273 (save-window-excursion
2274 (delete-other-windows)
2275 (switch-to-buffer (get-buffer-create "*org-goto*"))
2276 (with-output-to-temp-buffer "*Help*"
2277 (princ help))
2278 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2279 (setq buffer-read-only nil)
2280 (erase-buffer)
2281 (insert-buffer-substring buf)
2282 (let ((org-startup-truncated t)
2283 (org-startup-folded t)
2284 (org-startup-with-deadline-check nil))
2285 (org-mode))
2286 (setq buffer-read-only t)
2287 (if (boundp 'org-goto-start-pos)
2288 (goto-char org-goto-start-pos)
2289 (goto-char (point-min)))
2290 (org-beginning-of-line)
2291 (message "Select location and press RET")
2292 ;; now we make sure that during selection, ony very few keys work
2293 ;; and that it is impossible to switch to another window.
2294 (let ((gm (current-global-map))
2295 (overriding-local-map org-goto-map))
2296 (unwind-protect
2297 (progn
2298 (use-global-map org-goto-map)
2299 (recursive-edit))
2300 (use-global-map gm)))))
2301 (kill-buffer "*org-goto*")
2302 org-selected-point))
2303
2304 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2305 (defun org-goto-ret (&optional arg)
2306 "Finish org-goto by going to the new location."
2307 (interactive "P")
2308 (setq org-selected-point (point)
2309 current-prefix-arg arg)
2310 (throw 'exit nil))
2311
2312 (defun org-goto-left ()
2313 "Finish org-goto by going to the new location."
2314 (interactive)
2315 (if (org-on-heading-p)
2316 (progn
2317 (beginning-of-line 1)
2318 (setq org-selected-point (point)
2319 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2320 (throw 'exit nil))
2321 (error "Not on a heading")))
2322
2323 (defun org-goto-right ()
2324 "Finish org-goto by going to the new location."
2325 (interactive)
2326 (if (org-on-heading-p)
2327 (progn
2328 (outline-end-of-subtree)
2329 (or (eobp) (forward-char 1))
2330 (setq org-selected-point (point)
2331 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2332 (throw 'exit nil))
2333 (error "Not on a heading")))
2334
2335 (defun org-goto-quit ()
2336 "Finish org-goto without cursor motion."
2337 (interactive)
2338 (setq org-selected-point nil)
2339 (throw 'exit nil))
2340
2341 ;;; Promotion, Demotion, Inserting new headlines
2342
2343 (defvar org-ignore-region nil
2344 "To temporarily disable the active region.")
2345
2346 (defun org-insert-heading ()
2347 "Insert a new heading with same depth at point."
2348 (interactive)
2349 (let* ((head (save-excursion
2350 (condition-case nil
2351 (org-back-to-heading)
2352 (error (outline-next-heading)))
2353 (prog1 (match-string 0)
2354 (funcall outline-level)))))
2355 (unless (bolp) (newline))
2356 (insert head)
2357 (unless (eolp)
2358 (save-excursion (newline-and-indent)))
2359 (unless (equal (char-before) ?\ )
2360 (insert " "))
2361 (run-hooks 'org-insert-heading-hook)))
2362
2363 (defun org-insert-todo-heading (arg)
2364 "Insert a new heading with the same level and TODO state as current heading.
2365 If the heading has no TODO state, or if the state is DONE, use the first
2366 state (TODO by default). Also with prefix arg, force first state."
2367 (interactive "P")
2368 (org-insert-heading)
2369 (save-excursion
2370 (org-back-to-heading)
2371 (outline-previous-heading)
2372 (looking-at org-todo-line-regexp))
2373 (if (or arg
2374 (not (match-beginning 2))
2375 (equal (match-string 2) org-done-string))
2376 (insert (car org-todo-keywords) " ")
2377 (insert (match-string 2) " ")))
2378
2379 (defun org-promote-subtree ()
2380 "Promote the entire subtree.
2381 See also `org-promote'."
2382 (interactive)
2383 (save-excursion
2384 (org-map-tree 'org-promote)))
2385
2386 (defun org-demote-subtree ()
2387 "Demote the entire subtree. See `org-demote'.
2388 See also `org-promote'."
2389 (interactive)
2390 (save-excursion
2391 (org-map-tree 'org-demote)))
2392
2393 (defun org-do-promote ()
2394 "Promote the current heading higher up the tree.
2395 If the region is active in `transient-mark-mode', promote all headings
2396 in the region."
2397 (interactive)
2398 (save-excursion
2399 (if (org-region-active-p)
2400 (org-map-region 'org-promote (region-beginning) (region-end))
2401 (org-promote)))
2402 (org-fix-position-after-promote))
2403
2404 (defun org-do-demote ()
2405 "Demote the current heading lower down the tree.
2406 If the region is active in `transient-mark-mode', demote all headings
2407 in the region."
2408 (interactive)
2409 (save-excursion
2410 (if (org-region-active-p)
2411 (org-map-region 'org-demote (region-beginning) (region-end))
2412 (org-demote)))
2413 (org-fix-position-after-promote))
2414
2415 (defun org-fix-position-after-promote ()
2416 "Make sure that after pro/demotion cursor position is right."
2417 (and (equal (char-after) ?\ )
2418 (equal (char-before) ?*)
2419 (forward-char 1)))
2420
2421 (defun org-promote ()
2422 "Promote the current heading higher up the tree.
2423 If the region is active in `transient-mark-mode', promote all headings
2424 in the region."
2425 (org-back-to-heading t)
2426 (let* ((level (save-match-data (funcall outline-level)))
2427 (up-head (make-string (1- level) ?*)))
2428 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2429 (replace-match up-head nil t)
2430 (if org-adapt-indentation
2431 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2432
2433 (defun org-demote ()
2434 "Demote the current heading lower down the tree.
2435 If the region is active in `transient-mark-mode', demote all headings
2436 in the region."
2437 (org-back-to-heading t)
2438 (let* ((level (save-match-data (funcall outline-level)))
2439 (down-head (make-string (1+ level) ?*)))
2440 (replace-match down-head nil t)
2441 (if org-adapt-indentation
2442 (org-fixup-indentation "^ " " " "^\\S-"))))
2443
2444 (defun org-map-tree (fun)
2445 "Call FUN for every heading underneath the current one."
2446 (org-back-to-heading)
2447 (let ((level (outline-level)))
2448 (save-excursion
2449 (funcall fun)
2450 (while (and (progn
2451 (outline-next-heading)
2452 (> (funcall outline-level) level))
2453 (not (eobp)))
2454 (funcall fun)))))
2455
2456 (defun org-map-region (fun beg end)
2457 "Call FUN for every heading between BEG and END."
2458 (let ((org-ignore-region t))
2459 (save-excursion
2460 (setq end (copy-marker end))
2461 (goto-char beg)
2462 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2463 (< (point) end))
2464 (funcall fun))
2465 (while (and (progn
2466 (outline-next-heading)
2467 (< (point) end))
2468 (not (eobp)))
2469 (funcall fun)))))
2470
2471 (defun org-fixup-indentation (from to prohibit)
2472 "Change the indentation in the current entry by re-replacing FROM with TO.
2473 However, if the regexp PROHIBIT matches at all, don't do anything.
2474 This is being used to change indentation along with the length of the
2475 heading marker. But if there are any lines which are not indented, nothing
2476 is changed at all."
2477 (save-excursion
2478 (let ((end (save-excursion (outline-next-heading)
2479 (point-marker))))
2480 (unless (save-excursion (re-search-forward prohibit end t))
2481 (while (re-search-forward from end t)
2482 (replace-match to)
2483 (beginning-of-line 2)))
2484 (move-marker end nil))))
2485
2486 ;;; Vertical tree motion, cutting and pasting of subtrees
2487
2488 (defun org-move-subtree-up (&optional arg)
2489 "Move the current subtree up past ARG headlines of the same level."
2490 (interactive "p")
2491 (org-move-subtree-down (- (prefix-numeric-value arg))))
2492
2493 (defun org-move-subtree-down (&optional arg)
2494 "Move the current subtree down past ARG headlines of the same level."
2495 (interactive "p")
2496 (setq arg (prefix-numeric-value arg))
2497 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2498 'outline-get-last-sibling))
2499 (ins-point (make-marker))
2500 (cnt (abs arg))
2501 beg end txt folded)
2502 ;; Select the tree
2503 (org-back-to-heading)
2504 (setq beg (point))
2505 (save-match-data
2506 (save-excursion (outline-end-of-heading)
2507 (setq folded (org-invisible-p)))
2508 (outline-end-of-subtree))
2509 (outline-next-heading)
2510 (setq end (point))
2511 ;; Find insertion point, with error handling
2512 (goto-char beg)
2513 (while (> cnt 0)
2514 (or (and (funcall movfunc) (looking-at outline-regexp))
2515 (progn (goto-char beg)
2516 (error "Cannot move past superior level or buffer limit")))
2517 (setq cnt (1- cnt)))
2518 (if (> arg 0)
2519 ;; Moving forward - still need to move over subtree
2520 (progn (outline-end-of-subtree)
2521 (outline-next-heading)
2522 (if (not (or (looking-at (concat "^" outline-regexp))
2523 (bolp)))
2524 (newline))))
2525 (move-marker ins-point (point))
2526 (setq txt (buffer-substring beg end))
2527 (delete-region beg end)
2528 (insert txt)
2529 (goto-char ins-point)
2530 (if folded (hide-subtree))
2531 (move-marker ins-point nil)))
2532
2533 (defvar org-subtree-clip ""
2534 "Clipboard for cut and paste of subtrees.
2535 This is actually only a copy of the kill, because we use the normal kill
2536 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2537
2538 (defvar org-subtree-clip-folded nil
2539 "Was the last copied subtree folded?
2540 This is used to fold the tree back after pasting.")
2541
2542 (defun org-cut-subtree ()
2543 "Cut the current subtree into the clipboard.
2544 This is a short-hand for marking the subtree and then cutting it."
2545 (interactive)
2546 (org-copy-subtree 'cut))
2547
2548 (defun org-copy-subtree (&optional cut)
2549 "Cut the current subtree into the clipboard.
2550 This is a short-hand for marking the subtree and then copying it.
2551 If CUT is non nil, actually cut the subtree."
2552 (interactive)
2553 (let (beg end folded)
2554 (org-back-to-heading)
2555 (setq beg (point))
2556 (save-match-data
2557 (save-excursion (outline-end-of-heading)
2558 (setq folded (org-invisible-p)))
2559 (outline-end-of-subtree))
2560 (if (equal (char-after) ?\n) (forward-char 1))
2561 (setq end (point))
2562 (goto-char beg)
2563 (when (> end beg)
2564 (setq org-subtree-clip-folded folded)
2565 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2566 (setq org-subtree-clip (current-kill 0))
2567 (message "%s: Subtree with %d characters"
2568 (if cut "Cut" "Copied")
2569 (length org-subtree-clip)))))
2570
2571 (defun org-paste-subtree (&optional level tree)
2572 "Paste the clipboard as a subtree, with modification of headline level.
2573 The entire subtree is promoted or demoted in order to match a new headline
2574 level. By default, the new level is derived from the visible headings
2575 before and after the insertion point, and taken to be the inferior headline
2576 level of the two. So if the previous visible heading is level 3 and the
2577 next is level 4 (or vice versa), level 4 will be used for insertion.
2578 This makes sure that the subtree remains an independent subtree and does
2579 not swallow low level entries.
2580
2581 You can also force a different level, either by using a numeric prefix
2582 argument, or by inserting the heading marker by hand. For example, if the
2583 cursor is after \"*****\", then the tree will be shifted to level 5.
2584
2585 If you want to insert the tree as is, just use \\[yank].
2586
2587 If optional TREE is given, use this text instead of the kill ring."
2588 (interactive "P")
2589 (unless (org-kill-is-subtree-p tree)
2590 (error
2591 (substitute-command-keys
2592 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2593 (let* ((txt (or tree (current-kill 0)))
2594 (^re (concat "^\\(" outline-regexp "\\)"))
2595 (re (concat "\\(" outline-regexp "\\)"))
2596 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2597
2598 (old-level (if (string-match ^re txt)
2599 (- (match-end 0) (match-beginning 0))
2600 -1))
2601 (force-level (cond (level (prefix-numeric-value level))
2602 ((string-match
2603 ^re_ (buffer-substring (point-at-bol) (point)))
2604 (- (match-end 0) (match-beginning 0)))
2605 (t nil)))
2606 (previous-level (save-excursion
2607 (condition-case nil
2608 (progn
2609 (outline-previous-visible-heading 1)
2610 (if (looking-at re)
2611 (- (match-end 0) (match-beginning 0))
2612 1))
2613 (error 1))))
2614 (next-level (save-excursion
2615 (condition-case nil
2616 (progn
2617 (outline-next-visible-heading 1)
2618 (if (looking-at re)
2619 (- (match-end 0) (match-beginning 0))
2620 1))
2621 (error 1))))
2622 (new-level (or force-level (max previous-level next-level)))
2623 (shift (if (or (= old-level -1)
2624 (= new-level -1)
2625 (= old-level new-level))
2626 0
2627 (- new-level old-level)))
2628 (shift1 shift)
2629 (delta (if (> shift 0) -1 1))
2630 (func (if (> shift 0) 'org-demote 'org-promote))
2631 beg end)
2632 ;; Remove the forces level indicator
2633 (if force-level
2634 (delete-region (point-at-bol) (point)))
2635 ;; Make sure we start at the beginning of an empty line
2636 (if (not (bolp)) (insert "\n"))
2637 (if (not (looking-at "[ \t]*$"))
2638 (progn (insert "\n") (backward-char 1)))
2639 ;; Paste
2640 (setq beg (point))
2641 (insert txt)
2642 (setq end (point))
2643 (goto-char beg)
2644 ;; Shift if necessary
2645 (if (= shift 0)
2646 (message "Pasted at level %d, without shift" new-level)
2647 (save-restriction
2648 (narrow-to-region beg end)
2649 (while (not (= shift 0))
2650 (org-map-region func (point-min) (point-max))
2651 (setq shift (+ delta shift)))
2652 (goto-char (point-min))
2653 (message "Pasted at level %d, with shift by %d levels"
2654 new-level shift1)))
2655 (if (and (eq org-subtree-clip (current-kill 0))
2656 org-subtree-clip-folded)
2657 ;; The tree was folded before it was killed/copied
2658 (hide-subtree))))
2659
2660 (defun org-kill-is-subtree-p (&optional txt)
2661 "Check if the current kill is an outline subtree, or a set of trees.
2662 Returns nil if kill does not start with a headline, or if the first
2663 headline level is not the largest headline level in the tree.
2664 So this will actually accept several entries of equal levels as well,
2665 which is OK for `org-paste-subtree'.
2666 If optional TXT is given, check this string instead of the current kill."
2667 (let* ((kill (or txt (current-kill 0) ""))
2668 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2669 (- (match-end 0) (match-beginning 0))))
2670 (re (concat "^" outline-regexp))
2671 (start 1))
2672 (if (not start-level)
2673 nil ;; does not even start with a heading
2674 (catch 'exit
2675 (while (setq start (string-match re kill (1+ start)))
2676 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2677 (throw 'exit nil)))
2678 t))))
2679
2680 (defun org-archive-subtree ()
2681 "Move the current subtree to the archive.
2682 The archive can be a certain top-level heading in the current file, or in
2683 a different file. The tree will be moved to that location, the subtree
2684 heading be marked DONE, and the current time will be added."
2685 (interactive)
2686 ;; Save all relevant TODO keyword-relatex variables
2687 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2688 (tr-org-todo-keywords org-todo-keywords)
2689 (tr-org-todo-interpretation org-todo-interpretation)
2690 (tr-org-done-string org-done-string)
2691 (tr-org-todo-regexp org-todo-regexp)
2692 (tr-org-todo-line-regexp org-todo-line-regexp)
2693 (this-buffer (current-buffer))
2694 file heading buffer level newfile-p)
2695 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2696 (progn
2697 (setq file (format (match-string 1 org-archive-location)
2698 (file-name-nondirectory (buffer-file-name)))
2699 heading (match-string 2 org-archive-location)))
2700 (error "Invalid `org-archive-location'"))
2701 (if (> (length file) 0)
2702 (setq newfile-p (not (file-exists-p file))
2703 buffer (find-file-noselect file))
2704 (setq buffer (current-buffer)))
2705 (unless buffer
2706 (error "Cannot access file \"%s\"" file))
2707 (if (and (> (length heading) 0)
2708 (string-match "^\\*+" heading))
2709 (setq level (match-end 0))
2710 (setq heading nil level 0))
2711 (save-excursion
2712 ;; We first only copy, in case something goes wrong
2713 ;; we need to protect this-command, to avoid kill-region sets it,
2714 ;; which would lead to duplication of subtrees
2715 (let (this-command) (org-copy-subtree))
2716 (set-buffer buffer)
2717 ;; Enforce org-mode for the archive buffer
2718 (if (not (eq major-mode 'org-mode))
2719 ;; Force the mode for future visits.
2720 (let ((org-insert-mode-line-in-empty-file t))
2721 (call-interactively 'org-mode)))
2722 (when newfile-p
2723 (goto-char (point-max))
2724 (insert (format "\nArchived entries from file %s\n\n"
2725 (buffer-file-name this-buffer))))
2726 ;; Force the TODO keywords of the original buffer
2727 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2728 (org-todo-keywords tr-org-todo-keywords)
2729 (org-todo-interpretation tr-org-todo-interpretation)
2730 (org-done-string tr-org-done-string)
2731 (org-todo-regexp tr-org-todo-regexp)
2732 (org-todo-line-regexp tr-org-todo-line-regexp))
2733 (goto-char (point-min))
2734 (if heading
2735 (progn
2736 (if (re-search-forward
2737 (concat "\\(^\\|\r\\)"
2738 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2739 nil t)
2740 (goto-char (match-end 0))
2741 ;; Heading not found, just insert it at the end
2742 (goto-char (point-max))
2743 (or (bolp) (insert "\n"))
2744 (insert "\n" heading "\n")
2745 (end-of-line 0))
2746 ;; Make the heading visible, and the following as well
2747 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2748 (if (re-search-forward
2749 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2750 nil t)
2751 (progn (goto-char (match-beginning 0)) (insert "\n")
2752 (beginning-of-line 0))
2753 (goto-char (point-max)) (insert "\n")))
2754 (goto-char (point-max)) (insert "\n"))
2755 ;; Paste
2756 (org-paste-subtree (1+ level))
2757 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2758 (if org-archive-mark-done
2759 (org-todo (length org-todo-keywords)))
2760 ;; Move cursor to right after the TODO keyword
2761 (when org-archive-stamp-time
2762 (beginning-of-line 1)
2763 (looking-at org-todo-line-regexp)
2764 (goto-char (or (match-end 2) (match-beginning 3)))
2765 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2766 (current-time))
2767 ")"))
2768 ;; Save the buffer, if it is not the same buffer.
2769 (if (not (eq this-buffer buffer)) (save-buffer))))
2770 ;; Here we are back in the original buffer. Everything seems to have
2771 ;; worked. So now cut the tree and finish up.
2772 (let (this-command) (org-cut-subtree))
2773 (if (looking-at "[ \t]*$") (kill-line))
2774 (message "Subtree archived %s"
2775 (if (eq this-buffer buffer)
2776 (concat "under heading: " heading)
2777 (concat "in file: " (abbreviate-file-name file))))))
2778
2779 ;;; Completion
2780
2781 (defun org-complete (&optional arg)
2782 "Perform completion on word at point.
2783 At the beginning of a headline, this completes TODO keywords as given in
2784 `org-todo-keywords'.
2785 If the current word is preceded by a backslash, completes the TeX symbols
2786 that are supported for HTML support.
2787 If the current word is preceded by \"#+\", completes special words for
2788 setting file options.
2789 At all other locations, this simply calls `ispell-complete-word'."
2790 (interactive "P")
2791 (catch 'exit
2792 (let* ((end (point))
2793 (beg (save-excursion
2794 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2795 (skip-chars-backward "a-zA-Z0-9_:$")
2796 (point)))
2797 (texp (equal (char-before beg) ?\\))
2798 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2799 beg)
2800 "#+"))
2801 (pattern (buffer-substring-no-properties beg end))
2802 (completion-ignore-case opt)
2803 (type nil)
2804 (table (cond
2805 (opt
2806 (setq type :opt)
2807 (mapcar (lambda (x)
2808 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2809 (cons (match-string 2 x) (match-string 1 x)))
2810 (org-split-string (org-get-current-options) "\n")))
2811 (texp
2812 (setq type :tex)
2813 org-html-entities)
2814 ((string-match "\\`\\*+[ \t]*\\'"
2815 (buffer-substring (point-at-bol) beg))
2816 (setq type :todo)
2817 (mapcar 'list org-todo-keywords))
2818 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2819 (completion (try-completion pattern table)))
2820 (cond ((eq completion t)
2821 (if (equal type :opt)
2822 (insert (substring (cdr (assoc (upcase pattern) table))
2823 (length pattern)))))
2824 ((null completion)
2825 (message "Can't find completion for \"%s\"" pattern)
2826 (ding))
2827 ((not (string= pattern completion))
2828 (delete-region beg end)
2829 (if (string-match " +$" completion)
2830 (setq completion (replace-match "" t t completion)))
2831 (insert completion)
2832 (if (get-buffer-window "*Completions*")
2833 (delete-window (get-buffer-window "*Completions*")))
2834 (if (and (eq type :todo)
2835 (assoc completion table))
2836 (insert " "))
2837 (if (and (equal type :opt) (assoc completion table))
2838 (message "%s" (substitute-command-keys
2839 "Press \\[org-complete] again to insert example settings"))))
2840 (t
2841 (message "Making completion list...")
2842 (let ((list (sort (all-completions pattern table) 'string<)))
2843 (with-output-to-temp-buffer "*Completions*"
2844 (display-completion-list list)))
2845 (message "Making completion list...%s" "done"))))))
2846
2847 ;;; Comments, TODO and DEADLINE
2848
2849 (defun org-toggle-comment ()
2850 "Change the COMMENT state of an entry."
2851 (interactive)
2852 (save-excursion
2853 (org-back-to-heading)
2854 (if (looking-at (concat outline-regexp
2855 "\\( +\\<" org-comment-string "\\>\\)"))
2856 (replace-match "" t t nil 1)
2857 (if (looking-at outline-regexp)
2858 (progn
2859 (goto-char (match-end 0))
2860 (insert " " org-comment-string))))))
2861
2862 (defvar org-last-todo-state-is-todo nil
2863 "This is non-nil when the last TODO state change led to a TODO state.
2864 If the last change removed the TODO tag or switched to DONE, then
2865 this is nil.")
2866
2867 (defun org-todo (&optional arg)
2868 "Change the TODO state of an item.
2869 The state of an item is given by a keyword at the start of the heading,
2870 like
2871 *** TODO Write paper
2872 *** DONE Call mom
2873
2874 The different keywords are specified in the variable `org-todo-keywords'. By
2875 default the available states are \"TODO\" and \"DONE\".
2876 So for this example: when the item starts with TODO, it is changed to DONE.
2877 When it starts with DONE, the DONE is removed. And when neither TODO nor
2878 DONE are present, add TODO at the beginning of the heading.
2879
2880 With prefix arg, use completion to determined the new state. With numeric
2881 prefix arg, switch to that state."
2882 (interactive "P")
2883 (save-excursion
2884 (org-back-to-heading)
2885 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2886 (or (looking-at (concat " +" org-todo-regexp " *"))
2887 (looking-at " *"))
2888 (let* ((this (match-string 1))
2889 (completion-ignore-case t)
2890 (member (member this org-todo-keywords))
2891 (tail (cdr member))
2892 (state (cond
2893 ((equal arg '(4))
2894 ;; Read a state with completion
2895 (completing-read "State: " (mapcar (lambda(x) (list x))
2896 org-todo-keywords)
2897 nil t))
2898 (arg
2899 ;; user requests a specific state
2900 (nth (1- (prefix-numeric-value arg))
2901 org-todo-keywords))
2902 ((null member) (car org-todo-keywords))
2903 ((null tail) nil) ;; -> first entry
2904 ((eq org-todo-interpretation 'sequence)
2905 (car tail))
2906 ((memq org-todo-interpretation '(type priority))
2907 (if (eq this-command last-command)
2908 (car tail)
2909 (if (> (length tail) 0) org-done-string nil)))
2910 (t nil)))
2911 (next (if state (concat " " state " ") " ")))
2912 (replace-match next t t)
2913 (setq org-last-todo-state-is-todo
2914 (not (equal state org-done-string)))
2915 (run-hooks 'org-after-todo-state-change-hook)))
2916 ;; Fixup cursor location if close to the keyword
2917 (if (and (outline-on-heading-p)
2918 (not (bolp))
2919 (save-excursion (beginning-of-line 1)
2920 (looking-at org-todo-line-regexp))
2921 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2922 (progn
2923 (goto-char (or (match-end 2) (match-end 1)))
2924 (just-one-space))))
2925
2926 (defun org-show-todo-tree (arg)
2927 "Make a compact tree which shows all headlines marked with TODO.
2928 The tree will show the lines where the regexp matches, and all higher
2929 headlines above the match."
2930 (interactive "P")
2931 (let ((case-fold-search nil)
2932 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2933 (message "%d TODO entries found"
2934 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2935
2936 (defun org-deadline ()
2937 "Insert the DEADLINE: string to make a deadline.
2938 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2939 to modify it to the correct date."
2940 (interactive)
2941 (insert
2942 org-deadline-string " "
2943 (format-time-string (car org-time-stamp-formats)
2944 (org-read-date nil 'to-time)))
2945 (message "%s" (substitute-command-keys
2946 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2947
2948 (defun org-schedule ()
2949 "Insert the SCHEDULED: string to schedule a TODO item.
2950 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2951 to modify it to the correct date."
2952 (interactive)
2953 (insert
2954 org-scheduled-string " "
2955 (format-time-string (car org-time-stamp-formats)
2956 (org-read-date nil 'to-time)))
2957 (message "%s" (substitute-command-keys
2958 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2959
2960
2961 (defun org-occur (regexp &optional callback)
2962 "Make a compact tree which shows all matches of REGEXP.
2963 The tree will show the lines where the regexp matches, and all higher
2964 headlines above the match. It will also show the heading after the match,
2965 to make sure editing the matching entry is easy.
2966 if CALLBACK is non-nil, it is a function which is called to confirm
2967 that the match should indeed be shown."
2968 (interactive "sRegexp: ")
2969 (setq regexp (org-check-occur-regexp regexp))
2970 (let ((cnt 0))
2971 (save-excursion
2972 (goto-char (point-min))
2973 (hide-sublevels 1)
2974 (while (re-search-forward regexp nil t)
2975 (when (or (not callback)
2976 (funcall callback))
2977 (setq cnt (1+ cnt))
2978 (org-show-hierarchy-above))))
2979 (run-hooks 'org-occur-hook)
2980 (if (interactive-p)
2981 (message "%d match(es) for regexp %s" cnt regexp))
2982 cnt))
2983
2984 (defun org-show-hierarchy-above ()
2985 "Make sure point and the headings hierarchy above is visible."
2986 (if (org-on-heading-p t)
2987 (org-flag-heading nil) ; only show the heading
2988 (org-show-hidden-entry)) ; show entire entry
2989 (save-excursion
2990 (and org-show-following-heading
2991 (outline-next-heading)
2992 (org-flag-heading nil))) ; show the next heading
2993 (save-excursion ; show all higher headings
2994 (while (condition-case nil
2995 (progn (org-up-heading-all 1) t)
2996 (error nil))
2997 (org-flag-heading nil))))
2998
2999 ;;; Priorities
3000
3001 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3002 "Regular expression matching the priority indicator.")
3003
3004 (defvar org-remove-priority-next-time nil)
3005
3006 (defun org-priority-up ()
3007 "Increase the priority of the current item."
3008 (interactive)
3009 (org-priority 'up))
3010
3011 (defun org-priority-down ()
3012 "Decrease the priority of the current item."
3013 (interactive)
3014 (org-priority 'down))
3015
3016 (defun org-priority (&optional action)
3017 "Change the priority of an item by ARG.
3018 ACTION can be set, up, or down."
3019 (interactive)
3020 (setq action (or action 'set))
3021 (let (current new news have remove)
3022 (save-excursion
3023 (org-back-to-heading)
3024 (if (looking-at org-priority-regexp)
3025 (setq current (string-to-char (match-string 2))
3026 have t)
3027 (setq current org-default-priority))
3028 (cond
3029 ((eq action 'set)
3030 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3031 (setq new (read-char-exclusive))
3032 (cond ((equal new ?\ ) (setq remove t))
3033 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3034 (error "Priority must be between `%c' and `%c'"
3035 ?A org-lowest-priority))))
3036 ((eq action 'up)
3037 (setq new (1- current)))
3038 ((eq action 'down)
3039 (setq new (1+ current)))
3040 (t (error "Invalid action")))
3041 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3042 (setq news (format "%c" new))
3043 (if have
3044 (if remove
3045 (replace-match "" t t nil 1)
3046 (replace-match news t t nil 2))
3047 (if remove
3048 (error "No priority cookie found in line")
3049 (looking-at org-todo-line-regexp)
3050 (if (match-end 2)
3051 (progn
3052 (goto-char (match-end 2))
3053 (insert " [#" news "]"))
3054 (goto-char (match-beginning 3))
3055 (insert "[#" news "] ")))))
3056 (if remove
3057 (message "Priority removed")
3058 (message "Priority of current item set to %s" news))))
3059
3060
3061 (defun org-get-priority (s)
3062 "Find priority cookie and return priority."
3063 (save-match-data
3064 (if (not (string-match org-priority-regexp s))
3065 (* 1000 (- org-lowest-priority org-default-priority))
3066 (* 1000 (- org-lowest-priority
3067 (string-to-char (match-string 2 s)))))))
3068
3069 ;;; Timestamps
3070
3071 (defvar org-last-changed-timestamp nil)
3072
3073 (defun org-time-stamp (arg)
3074 "Prompt for a date/time and insert a time stamp.
3075 If the user specifies a time like HH:MM, or if this command is called
3076 with a prefix argument, the time stamp will contain date and time.
3077 Otherwise, only the date will be included. All parts of a date not
3078 specified by the user will be filled in from the current date/time.
3079 So if you press just return without typing anything, the time stamp
3080 will represent the current date/time. If there is already a timestamp
3081 at the cursor, it will be modified."
3082 (interactive "P")
3083 (let ((fmt (if arg (cdr org-time-stamp-formats)
3084 (car org-time-stamp-formats)))
3085 (org-time-was-given nil)
3086 time)
3087 (cond
3088 ((and (org-at-timestamp-p)
3089 (eq last-command 'org-time-stamp)
3090 (eq this-command 'org-time-stamp))
3091 (insert "--")
3092 (setq time (let ((this-command this-command))
3093 (org-read-date arg 'totime)))
3094 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3095 (insert (format-time-string fmt time)))
3096 ((org-at-timestamp-p)
3097 (setq time (let ((this-command this-command))
3098 (org-read-date arg 'totime)))
3099 (and (org-at-timestamp-p) (replace-match
3100 (setq org-last-changed-timestamp
3101 (format-time-string fmt time))
3102 t t))
3103 (message "Timestamp updated"))
3104 (t
3105 (setq time (let ((this-command this-command))
3106 (org-read-date arg 'totime)))
3107 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3108 (insert (format-time-string fmt time))))))
3109
3110 (defun org-time-stamp-inactive (&optional arg)
3111 "Insert an inactive time stamp.
3112 An inactive time stamp is enclosed in square brackets instead of angle
3113 brackets. It is inactive in the sense that it does not trigger agenda entries,
3114 does not link to the calendar and cannot be changed with the S-cursor keys."
3115 (interactive "P")
3116 (let ((fmt (if arg (cdr org-time-stamp-formats)
3117 (car org-time-stamp-formats)))
3118 (org-time-was-given nil)
3119 time)
3120 (setq time (org-read-date arg 'totime))
3121 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3122 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3123 (insert (format-time-string fmt time))))
3124
3125 ;;; FIXME: Make the function take "Fri" as "next friday"
3126 (defun org-read-date (&optional with-time to-time)
3127 "Read a date and make things smooth for the user.
3128 The prompt will suggest to enter an ISO date, but you can also enter anything
3129 which will at least partially be understood by `parse-time-string'.
3130 Unrecognized parts of the date will default to the current day, month ,year,
3131 hour and minute. For example,
3132 3-2-5 --> 2003-02-05
3133 feb 15 --> currentyear-02-15
3134 sep 12 9 --> 2009-09-12
3135 12:45 --> today 12:45
3136 22 sept 0:34 --> currentyear-09-22 0:34
3137 12 --> currentyear-currentmonth-12
3138 etc.
3139 The function understands only English month and weekday abbreviations,
3140 but this can be configured with the variables `parse-time-months' and
3141 `parse-time-weekdays'.
3142
3143 While prompting, a calendar is popped up - you can also select the
3144 date with the mouse (button 1). The calendar shows a period of three
3145 month. To scroll it to other months, use the keys `>' and `<'.
3146 If you don't like the calendar, turn it off with
3147 \(setq org-popup-calendar-for-date-prompt nil).
3148
3149 With optional argument TO-TIME, the date will immediately be converted
3150 to an internal time.
3151 With an optional argument WITH-TIME, the prompt will suggest to also
3152 insert a time. Note that when WITH-TIME is not set, you can still
3153 enter a time, and this function will inform the calling routine about
3154 this change. The calling routine may then choose to change the format
3155 used to insert the time stamp into the buffer to include the time."
3156 (let* ((default-time
3157 ;; Default time is either today, or, when entering a range,
3158 ;; the range start.
3159 (if (save-excursion
3160 (re-search-backward
3161 (concat org-ts-regexp "--\\=")
3162 (- (point) 20) t))
3163 (apply
3164 'encode-time
3165 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3166 (parse-time-string (match-string 1))))
3167 (current-time)))
3168 (timestr (format-time-string
3169 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3170 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3171 ans ans1 ans2
3172 second minute hour day month year tl)
3173
3174 (if org-popup-calendar-for-date-prompt
3175 ;; Also show a calendar for date selection
3176 ;; Copied (with modifications) from planner.el by John Wiegley
3177 (save-excursion
3178 (save-window-excursion
3179 (calendar)
3180 (calendar-forward-day (- (time-to-days default-time)
3181 (calendar-absolute-from-gregorian
3182 (calendar-current-date))))
3183 (let* ((old-map (current-local-map))
3184 (map (copy-keymap calendar-mode-map))
3185 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3186 (define-key map (kbd "RET") 'org-calendar-select)
3187 (define-key map (if org-xemacs-p [button1] [mouse-1])
3188 'org-calendar-select)
3189 (define-key minibuffer-local-map [(meta shift left)]
3190 (lambda () (interactive)
3191 (org-eval-in-calendar '(calendar-backward-month 1))))
3192 (define-key minibuffer-local-map [(meta shift right)]
3193 (lambda () (interactive)
3194 (org-eval-in-calendar '(calendar-forward-month 1))))
3195 (define-key minibuffer-local-map [(shift up)]
3196 (lambda () (interactive)
3197 (org-eval-in-calendar '(calendar-backward-week 1))))
3198 (define-key minibuffer-local-map [(shift down)]
3199 (lambda () (interactive)
3200 (org-eval-in-calendar '(calendar-forward-week 1))))
3201 (define-key minibuffer-local-map [(shift left)]
3202 (lambda () (interactive)
3203 (org-eval-in-calendar '(calendar-backward-day 1))))
3204 (define-key minibuffer-local-map [(shift right)]
3205 (lambda () (interactive)
3206 (org-eval-in-calendar '(calendar-forward-day 1))))
3207 (define-key minibuffer-local-map ">"
3208 (lambda () (interactive)
3209 (org-eval-in-calendar '(scroll-calendar-left 1))))
3210 (define-key minibuffer-local-map "<"
3211 (lambda () (interactive)
3212 (org-eval-in-calendar '(scroll-calendar-right 1))))
3213 (unwind-protect
3214 (progn
3215 (use-local-map map)
3216 (setq ans (read-string prompt "" nil nil))
3217 (setq ans (or ans1 ans2 ans)))
3218 (use-local-map old-map)))))
3219 ;; Naked prompt only
3220 (setq ans (read-string prompt "" nil timestr)))
3221
3222 (if (string-match
3223 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3224 (progn
3225 (setq year (if (match-end 2)
3226 (string-to-number (match-string 2 ans))
3227 (string-to-number (format-time-string "%Y")))
3228 month (string-to-number (match-string 3 ans))
3229 day (string-to-number (match-string 4 ans)))
3230 (if (< year 100) (setq year (+ 2000 year)))
3231 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3232 t t ans))))
3233 (setq tl (parse-time-string ans)
3234 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3235 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3236 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3237 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3238 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3239 second (or (nth 0 tl) 0))
3240 (if (and (boundp 'org-time-was-given)
3241 (nth 2 tl))
3242 (setq org-time-was-given t))
3243 (if (< year 100) (setq year (+ 2000 year)))
3244 (if to-time
3245 (encode-time second minute hour day month year)
3246 (if (or (nth 1 tl) (nth 2 tl))
3247 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3248 (format "%04d-%02d-%02d" year month day)))))
3249
3250 (defun org-eval-in-calendar (form)
3251 "Eval FORM in the calendar window and return to current window.
3252 Also, store the cursor date in variable ans2."
3253 (let ((sw (selected-window)))
3254 (select-window (get-buffer-window "*Calendar*"))
3255 (eval form)
3256 (when (calendar-cursor-to-date)
3257 (let* ((date (calendar-cursor-to-date))
3258 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3259 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3260 (select-window sw)))
3261
3262 (defun org-calendar-select ()
3263 "Return to `org-read-date' with the date currently selected.
3264 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3265 (interactive)
3266 (when (calendar-cursor-to-date)
3267 (let* ((date (calendar-cursor-to-date))
3268 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3269 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3270 (if (active-minibuffer-window) (exit-minibuffer))))
3271
3272 (defun org-check-deadlines (ndays)
3273 "Check if there are any deadlines due or past due.
3274 A deadline is considered due if it happens within `org-deadline-warning-days'
3275 days from today's date. If the deadline appears in an entry marked DONE,
3276 it is not shown. The prefix arg NDAYS can be used to test that many
3277 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3278 (interactive "P")
3279 (let* ((org-warn-days
3280 (cond
3281 ((equal ndays '(4)) 100000)
3282 (ndays (prefix-numeric-value ndays))
3283 (t org-deadline-warning-days)))
3284 (case-fold-search nil)
3285 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3286 (callback
3287 (lambda ()
3288 (and (let ((d1 (time-to-days (current-time)))
3289 (d2 (time-to-days
3290 (org-time-string-to-time (match-string 1)))))
3291 (< (- d2 d1) org-warn-days))
3292 (not (org-entry-is-done-p))))))
3293 (message "%d deadlines past-due or due within %d days"
3294 (org-occur regexp callback)
3295 org-warn-days)))
3296
3297 (defun org-evaluate-time-range (&optional to-buffer)
3298 "Evaluate a time range by computing the difference between start and end.
3299 Normally the result is just printed in the echo area, but with prefix arg
3300 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3301 If the time range is actually in a table, the result is inserted into the
3302 next column.
3303 For time difference computation, a year is assumed to be exactly 365
3304 days in order to avoid rounding problems."
3305 (interactive "P")
3306 (save-excursion
3307 (unless (org-at-date-range-p)
3308 (goto-char (point-at-bol))
3309 (re-search-forward org-tr-regexp (point-at-eol) t))
3310 (if (not (org-at-date-range-p))
3311 (error "Not at a time-stamp range, and none found in current line")))
3312 (let* ((ts1 (match-string 1))
3313 (ts2 (match-string 2))
3314 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3315 (match-end (match-end 0))
3316 (time1 (org-time-string-to-time ts1))
3317 (time2 (org-time-string-to-time ts2))
3318 (t1 (time-to-seconds time1))
3319 (t2 (time-to-seconds time2))
3320 (diff (abs (- t2 t1)))
3321 (negative (< (- t2 t1) 0))
3322 ;; (ys (floor (* 365 24 60 60)))
3323 (ds (* 24 60 60))
3324 (hs (* 60 60))
3325 (fy "%dy %dd %02d:%02d")
3326 (fy1 "%dy %dd")
3327 (fd "%dd %02d:%02d")
3328 (fd1 "%dd")
3329 (fh "%02d:%02d")
3330 y d h m align)
3331 ;; FIXME: Should I re-introduce years, make year refer to same date?
3332 ;; This would be the only useful way to have years, actually.
3333 (if havetime
3334 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3335 y 0
3336 d (floor (/ diff ds)) diff (mod diff ds)
3337 h (floor (/ diff hs)) diff (mod diff hs)
3338 m (floor (/ diff 60)))
3339 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3340 y 0
3341 d (floor (+ (/ diff ds) 0.5))
3342 h 0 m 0))
3343 (if (not to-buffer)
3344 (message (org-make-tdiff-string y d h m))
3345 (when (org-at-table-p)
3346 (goto-char match-end)
3347 (setq align t)
3348 (and (looking-at " *|") (goto-char (match-end 0))))
3349 (if (looking-at
3350 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3351 (replace-match ""))
3352 (if negative (insert " -"))
3353 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3354 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3355 (insert " " (format fh h m))))
3356 (if align (org-table-align))
3357 (message "Time difference inserted"))))
3358
3359 (defun org-make-tdiff-string (y d h m)
3360 (let ((fmt "")
3361 (l nil))
3362 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3363 l (push y l)))
3364 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3365 l (push d l)))
3366 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3367 l (push h l)))
3368 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3369 l (push m l)))
3370 (apply 'format fmt (nreverse l))))
3371
3372 (defun org-time-string-to-time (s)
3373 (apply 'encode-time (org-parse-time-string s)))
3374
3375 (defun org-parse-time-string (s &optional nodefault)
3376 "Parse the standard Org-mode time string.
3377 This should be a lot faster than the normal `parse-time-string'.
3378 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3379 hour and minute fields will be nil if not given."
3380 (if (string-match org-ts-regexp1 s)
3381 (list 0
3382 (if (or (match-beginning 8) (not nodefault))
3383 (string-to-number (or (match-string 8 s) "0")))
3384 (if (or (match-beginning 7) (not nodefault))
3385 (string-to-number (or (match-string 7 s) "0")))
3386 (string-to-number (match-string 4 s))
3387 (string-to-number (match-string 3 s))
3388 (string-to-number (match-string 2 s))
3389 nil nil nil)
3390 (make-list 9 0)))
3391
3392 (defun org-timestamp-up (&optional arg)
3393 "Increase the date item at the cursor by one.
3394 If the cursor is on the year, change the year. If it is on the month or
3395 the day, change that.
3396 With prefix ARG, change by that many units."
3397 (interactive "p")
3398 (org-timestamp-change (prefix-numeric-value arg)))
3399
3400 (defun org-timestamp-down (&optional arg)
3401 "Decrease the date item at the cursor by one.
3402 If the cursor is on the year, change the year. If it is on the month or
3403 the day, change that.
3404 With prefix ARG, change by that many units."
3405 (interactive "p")
3406 (org-timestamp-change (- (prefix-numeric-value arg))))
3407
3408 (defun org-timestamp-up-day (&optional arg)
3409 "Increase the date in the time stamp by one day.
3410 With prefix ARG, change that many days."
3411 (interactive "p")
3412 (org-timestamp-change (prefix-numeric-value arg) 'day))
3413
3414 (defun org-timestamp-down-day (&optional arg)
3415 "Decrease the date in the time stamp by one day.
3416 With prefix ARG, change that many days."
3417 (interactive "p")
3418 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3419
3420 (defsubst org-pos-in-match-range (pos n)
3421 (and (match-beginning n)
3422 (<= (match-beginning n) pos)
3423 (>= (match-end n) pos)))
3424
3425 (defun org-at-timestamp-p ()
3426 "Determine if the cursor is or at a timestamp."
3427 (interactive)
3428 (let* ((tsr org-ts-regexp2)
3429 (pos (point))
3430 (ans (or (looking-at tsr)
3431 (save-excursion
3432 (skip-chars-backward "^<\n\r\t")
3433 (if (> (point) 1) (backward-char 1))
3434 (and (looking-at tsr)
3435 (> (- (match-end 0) pos) -1))))))
3436 (and (boundp 'org-ts-what)
3437 (setq org-ts-what
3438 (cond
3439 ((org-pos-in-match-range pos 2) 'year)
3440 ((org-pos-in-match-range pos 3) 'month)
3441 ((org-pos-in-match-range pos 7) 'hour)
3442 ((org-pos-in-match-range pos 8) 'minute)
3443 ((or (org-pos-in-match-range pos 4)
3444 (org-pos-in-match-range pos 5)) 'day)
3445 (t 'day))))
3446 ans))
3447
3448 (defun org-timestamp-change (n &optional what)
3449 "Change the date in the time stamp at point.
3450 The date will be changed by N times WHAT. WHAT can be `day', `month',
3451 `year', `minute', `second'. If WHAT is not given, the cursor position
3452 in the timestamp determines what will be changed."
3453 (let ((fmt (car org-time-stamp-formats))
3454 org-ts-what
3455 (pos (point))
3456 ts time time0)
3457 (if (not (org-at-timestamp-p))
3458 (error "Not at a timestamp"))
3459 (setq org-ts-what (or what org-ts-what))
3460 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3461 (- (match-end 0) (match-beginning 0))))
3462 1)
3463 (cdr org-time-stamp-formats)
3464 (car org-time-stamp-formats)))
3465 (setq ts (match-string 0))
3466 (replace-match "")
3467 (setq time0 (org-parse-time-string ts))
3468 (setq time
3469 (apply 'encode-time
3470 (append
3471 (list (or (car time0) 0))
3472 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3473 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3474 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3475 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3476 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3477 (nthcdr 6 time0))))
3478 (if (eq what 'calendar)
3479 (let ((cal-date
3480 (save-excursion
3481 (save-match-data
3482 (set-buffer "*Calendar*")
3483 (calendar-cursor-to-date)))))
3484 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3485 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3486 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3487 (setcar time0 (or (car time0) 0))
3488 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3489 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3490 (setq time (apply 'encode-time time0))))
3491 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3492 (goto-char pos)
3493 ;; Try to recenter the calendar window, if any
3494 (if (and org-calendar-follow-timestamp-change
3495 (get-buffer-window "*Calendar*" t)
3496 (memq org-ts-what '(day month year)))
3497 (org-recenter-calendar (time-to-days time)))))
3498
3499 (defun org-recenter-calendar (date)
3500 "If the calendar is visible, recenter it to DATE."
3501 (let* ((win (selected-window))
3502 (cwin (get-buffer-window "*Calendar*" t)))
3503 (when cwin
3504 (select-window cwin)
3505 (calendar-goto-date (if (listp date) date
3506 (calendar-gregorian-from-absolute date)))
3507 (select-window win))))
3508
3509 (defun org-goto-calendar (&optional arg)
3510 "Go to the Emacs calendar at the current date.
3511 If there is a time stamp in the current line, go to that date.
3512 A prefix ARG can be used force the current date."
3513 (interactive "P")
3514 (let ((tsr org-ts-regexp) diff)
3515 (if (or (org-at-timestamp-p)
3516 (save-excursion
3517 (beginning-of-line 1)
3518 (looking-at (concat ".*" tsr))))
3519 (let ((d1 (time-to-days (current-time)))
3520 (d2 (time-to-days
3521 (org-time-string-to-time (match-string 1)))))
3522 (setq diff (- d2 d1))))
3523 (calendar)
3524 (calendar-goto-today)
3525 (if (and diff (not arg)) (calendar-forward-day diff))))
3526
3527 (defun org-date-from-calendar ()
3528 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3529 If there is already a time stamp at the cursor position, update it."
3530 (interactive)
3531 (org-timestamp-change 0 'calendar))
3532
3533 ;;; Agenda, and Diary Integration
3534
3535 ;;; Define the mode
3536
3537 (defvar org-agenda-mode-map (make-sparse-keymap)
3538 "Keymap for `org-agenda-mode'.")
3539
3540 (defvar org-agenda-menu)
3541 (defvar org-agenda-follow-mode nil)
3542 (defvar org-agenda-buffer-name "*Org Agenda*")
3543 (defvar org-agenda-redo-command nil)
3544 (defvar org-agenda-mode-hook nil)
3545
3546 ;;;###autoload
3547 (defun org-agenda-mode ()
3548 "Mode for time-sorted view on action items in Org-mode files.
3549
3550 The following commands are available:
3551
3552 \\{org-agenda-mode-map}"
3553 (interactive)
3554 (kill-all-local-variables)
3555 (setq major-mode 'org-agenda-mode)
3556 (setq mode-name "Org-Agenda")
3557 (use-local-map org-agenda-mode-map)
3558 (easy-menu-add org-agenda-menu)
3559 (if org-startup-truncated (setq truncate-lines t))
3560 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3561 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3562 (setq org-agenda-follow-mode nil)
3563 (easy-menu-change
3564 '("Agenda") "Agenda Files"
3565 (append
3566 (list
3567 ["Edit File List" (customize-variable 'org-agenda-files) t]
3568 "--")
3569 (mapcar 'org-file-menu-entry org-agenda-files)))
3570 (org-agenda-set-mode-name)
3571 (apply
3572 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3573 org-agenda-mode-hook))
3574
3575 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3576 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3577 (define-key org-agenda-mode-map " " 'org-agenda-show)
3578 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3579 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3580 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3581 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3582 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3583 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3584 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3585 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3586 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3587 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
3588 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
3589
3590 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3591 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3592 (while l (define-key org-agenda-mode-map
3593 (int-to-string (pop l)) 'digit-argument)))
3594
3595 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3596 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3597 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3598 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3599 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3600 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3601 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3602 (define-key org-agenda-mode-map "n" 'next-line)
3603 (define-key org-agenda-mode-map "p" 'previous-line)
3604 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3605 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3606 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3607 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3608 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3609 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3610 (eval-after-load "calendar"
3611 '(define-key calendar-mode-map org-calendar-to-agenda-key
3612 'org-calendar-goto-agenda))
3613 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3614 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3615 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3616 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3617 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3618 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3619 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3620 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3621 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3622 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3623 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3624 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
3625 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
3626 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3627 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3628
3629 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3630 "Local keymap for agenda entries from Org-mode.")
3631
3632 (define-key org-agenda-keymap
3633 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3634 (define-key org-agenda-keymap
3635 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3636
3637 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3638 '("Agenda"
3639 ("Agenda Files")
3640 "--"
3641 ["Show" org-agenda-show t]
3642 ["Go To (other window)" org-agenda-goto t]
3643 ["Go To (one window)" org-agenda-switch-to t]
3644 ["Follow Mode" org-agenda-follow-mode
3645 :style toggle :selected org-agenda-follow-mode :active t]
3646 "--"
3647 ["Cycle TODO" org-agenda-todo t]
3648 ("Reschedule"
3649 ["Reschedule +1 day" org-agenda-date-later t]
3650 ["Reschedule -1 day" org-agenda-date-earlier t]
3651 "--"
3652 ["Reschedule to ..." org-agenda-date-prompt t])
3653 ("Priority"
3654 ["Set Priority" org-agenda-priority t]
3655 ["Increase Priority" org-agenda-priority-up t]
3656 ["Decrease Priority" org-agenda-priority-down t]
3657 ["Show Priority" org-agenda-show-priority t])
3658 "--"
3659 ["Rebuild buffer" org-agenda-redo t]
3660 ["Goto Today" org-agenda-goto-today t]
3661 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3662 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3663 "--"
3664 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3665 :style radio :selected (equal org-agenda-ndays 1)]
3666 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3667 :style radio :selected (equal org-agenda-ndays 7)]
3668 "--"
3669 ["Include Diary" org-agenda-toggle-diary
3670 :style toggle :selected org-agenda-include-diary :active t]
3671 ["Use Time Grid" org-agenda-toggle-time-grid
3672 :style toggle :selected org-agenda-use-time-grid :active t]
3673 "--"
3674 ["New Diary Entry" org-agenda-diary-entry t]
3675 ("Calendar Commands"
3676 ["Goto Calendar" org-agenda-goto-calendar t]
3677 ["Phases of the Moon" org-agenda-phases-of-moon t]
3678 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3679 ["Holidays" org-agenda-holidays t]
3680 ["Convert" org-agenda-convert-date t])
3681 "--"
3682 ["Quit" org-agenda-quit t]
3683 ["Exit and Release Buffers" org-agenda-exit t]
3684 ))
3685
3686 (defvar org-agenda-markers nil
3687 "List of all currently active markers created by `org-agenda'.")
3688 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3689 "Creation time of the last agenda marker.")
3690
3691 (defun org-agenda-new-marker (&optional pos)
3692 "Return a new agenda marker.
3693 Org-mode keeps a list of these markers and resets them when they are
3694 no longer in use."
3695 (let ((m (copy-marker (or pos (point)))))
3696 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3697 (push m org-agenda-markers)
3698 m))
3699
3700 (defun org-agenda-maybe-reset-markers (&optional force)
3701 "Reset markers created by `org-agenda'. But only if they are old enough."
3702 (if (or force
3703 (> (- (time-to-seconds (current-time))
3704 org-agenda-last-marker-time)
3705 5))
3706 (while org-agenda-markers
3707 (move-marker (pop org-agenda-markers) nil))))
3708
3709 (defvar org-agenda-new-buffers nil
3710 "Buffers created to visit agenda files.")
3711
3712 (defun org-get-agenda-file-buffer (file)
3713 "Get a buffer visiting FILE. If the buffer needs to be created, add
3714 it to the list of buffers which might be released later."
3715 (let ((buf (find-buffer-visiting file)))
3716 (if buf
3717 buf ; just return it
3718 ;; Make a new buffer and remember it
3719 (setq buf (find-file-noselect file))
3720 (if buf (push buf org-agenda-new-buffers))
3721 buf)))
3722
3723 (defun org-release-buffers (blist)
3724 "Release all buffers in list, asking the user for confirmation when needed.
3725 When a buffer is unmodified, it is just killed. When modified, it is saved
3726 \(if the user agrees) and then killed."
3727 (let (buf file)
3728 (while (setq buf (pop blist))
3729 (setq file (buffer-file-name buf))
3730 (when (and (buffer-modified-p buf)
3731 file
3732 (y-or-n-p (format "Save file %s? " file)))
3733 (with-current-buffer buf (save-buffer)))
3734 (kill-buffer buf))))
3735
3736 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3737
3738 (defun org-timeline (&optional include-all)
3739 "Show a time-sorted view of the entries in the current org file.
3740 Only entries with a time stamp of today or later will be listed. With
3741 one \\[universal-argument] prefix argument, past entries will also be listed.
3742 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3743 under the current date.
3744 If the buffer contains an active region, only check the region for
3745 dates."
3746 (interactive "P")
3747 (require 'calendar)
3748 (org-agenda-maybe-reset-markers 'force)
3749 (org-compile-prefix-format org-timeline-prefix-format)
3750 (let* ((dopast include-all)
3751 (dotodo (equal include-all '(16)))
3752 (entry (buffer-file-name))
3753 (org-agenda-files (list (buffer-file-name)))
3754 (date (calendar-current-date))
3755 (win (selected-window))
3756 (pos1 (point))
3757 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3758 (end (if (org-region-active-p) (region-end) (point-max)))
3759 (day-numbers (org-get-all-dates beg end 'no-ranges
3760 t)) ; always include today
3761 (today (time-to-days (current-time)))
3762 (org-respect-restriction t)
3763 (past t)
3764 s e rtn d)
3765 (setq org-agenda-redo-command
3766 (list 'progn
3767 (list 'switch-to-buffer-other-window (current-buffer))
3768 (list 'org-timeline (list 'quote include-all))))
3769 (if (not dopast)
3770 ;; Remove past dates from the list of dates.
3771 (setq day-numbers (delq nil (mapcar (lambda(x)
3772 (if (>= x today) x nil))
3773 day-numbers))))
3774 (switch-to-buffer-other-window
3775 (get-buffer-create org-agenda-buffer-name))
3776 (setq buffer-read-only nil)
3777 (erase-buffer)
3778 (org-agenda-mode) (setq buffer-read-only nil)
3779 (while (setq d (pop day-numbers))
3780 (if (and (>= d today)
3781 dopast
3782 past)
3783 (progn
3784 (setq past nil)
3785 (insert (make-string 79 ?-) "\n")))
3786 (setq date (calendar-gregorian-from-absolute d))
3787 (setq s (point))
3788 (if dotodo
3789 (setq rtn (org-agenda-get-day-entries
3790 entry date :todo :timestamp))
3791 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3792 (if (or rtn (equal d today))
3793 (progn
3794 (insert (calendar-day-name date) " "
3795 (number-to-string (extract-calendar-day date)) " "
3796 (calendar-month-name (extract-calendar-month date)) " "
3797 (number-to-string (extract-calendar-year date)) "\n")
3798 (put-text-property s (1- (point)) 'face
3799 'org-link)
3800 (if (equal d today)
3801 (put-text-property s (1- (point)) 'org-today t))
3802 (insert (org-finalize-agenda-entries rtn) "\n")
3803 (put-text-property s (1- (point)) 'day d))))
3804 (goto-char (point-min))
3805 (setq buffer-read-only t)
3806 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3807 (point-min)))
3808 (when (not org-select-timeline-window)
3809 (select-window win)
3810 (goto-char pos1))))
3811
3812 ;;;###autoload
3813 (defun org-agenda (&optional include-all start-day ndays)
3814 "Produce a weekly view from all files in variable `org-agenda-files'.
3815 The view will be for the current week, but from the overview buffer you
3816 will be able to go to other weeks.
3817 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3818 also be shown, under the current date.
3819 START-DAY defaults to TODAY, or to the most recent match for the weekday
3820 given in `org-agenda-start-on-weekday'.
3821 NDAYS defaults to `org-agenda-ndays'."
3822 (interactive "P")
3823 (org-agenda-maybe-reset-markers 'force)
3824 (org-compile-prefix-format org-agenda-prefix-format)
3825 (require 'calendar)
3826 (let* ((org-agenda-start-on-weekday
3827 (if (or (equal ndays 1)
3828 (and (null ndays) (equal 1 org-agenda-ndays)))
3829 nil org-agenda-start-on-weekday))
3830 (files (copy-sequence org-agenda-files))
3831 (win (selected-window))
3832 (today (time-to-days (current-time)))
3833 (sd (or start-day today))
3834 (start (if (or (null org-agenda-start-on-weekday)
3835 (< org-agenda-ndays 7))
3836 sd
3837 (let* ((nt (calendar-day-of-week
3838 (calendar-gregorian-from-absolute sd)))
3839 (n1 org-agenda-start-on-weekday)
3840 (d (- nt n1)))
3841 (- sd (+ (if (< d 0) 7 0) d)))))
3842 (day-numbers (list start))
3843 (inhibit-redisplay t)
3844 s e rtn rtnall file date d start-pos end-pos todayp nd)
3845 (setq org-agenda-redo-command
3846 (list 'org-agenda (list 'quote include-all) start-day ndays))
3847 ;; Make the list of days
3848 (setq ndays (or ndays org-agenda-ndays)
3849 nd ndays)
3850 (while (> ndays 1)
3851 (push (1+ (car day-numbers)) day-numbers)
3852 (setq ndays (1- ndays)))
3853 (setq day-numbers (nreverse day-numbers))
3854 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3855 (progn
3856 (delete-other-windows)
3857 (switch-to-buffer-other-window
3858 (get-buffer-create org-agenda-buffer-name))))
3859 (setq buffer-read-only nil)
3860 (erase-buffer)
3861 (org-agenda-mode) (setq buffer-read-only nil)
3862 (set (make-local-variable 'starting-day) (car day-numbers))
3863 (set (make-local-variable 'include-all-loc) include-all)
3864 (when (and (or include-all org-agenda-include-all-todo)
3865 (member today day-numbers))
3866 (setq files org-agenda-files
3867 rtnall nil)
3868 (while (setq file (pop files))
3869 (catch 'nextfile
3870 (org-check-agenda-file file)
3871 (setq date (calendar-gregorian-from-absolute today)
3872 rtn (org-agenda-get-day-entries
3873 file date :todo))
3874 (setq rtnall (append rtnall rtn))))
3875 (when rtnall
3876 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3877 (add-text-properties (point-min) (1- (point))
3878 (list 'face 'org-link))
3879 (insert (org-finalize-agenda-entries rtnall) "\n")))
3880 (while (setq d (pop day-numbers))
3881 (setq date (calendar-gregorian-from-absolute d)
3882 s (point))
3883 (if (or (setq todayp (= d today))
3884 (and (not start-pos) (= d sd)))
3885 (setq start-pos (point))
3886 (if (and start-pos (not end-pos))
3887 (setq end-pos (point))))
3888 (setq files org-agenda-files
3889 rtnall nil)
3890 (while (setq file (pop files))
3891 (catch 'nextfile
3892 (org-check-agenda-file file)
3893 (setq rtn (org-agenda-get-day-entries file date))
3894 (setq rtnall (append rtnall rtn))))
3895 (if org-agenda-include-diary
3896 (progn
3897 (require 'diary-lib)
3898 (setq rtn (org-get-entries-from-diary date))
3899 (setq rtnall (append rtnall rtn))))
3900 (if (or rtnall org-agenda-show-all-dates)
3901 (progn
3902 (insert (format "%-9s %2d %s %4d\n"
3903 (calendar-day-name date)
3904 (extract-calendar-day date)
3905 (calendar-month-name (extract-calendar-month date))
3906 (extract-calendar-year date)))
3907 (put-text-property s (1- (point)) 'face
3908 'org-link)
3909 (if rtnall (insert
3910 (org-finalize-agenda-entries ;; FIXME: condition needed
3911 (org-agenda-add-time-grid-maybe
3912 rtnall nd todayp))
3913 "\n"))
3914 (put-text-property s (1- (point)) 'day d))))
3915 (goto-char (point-min))
3916 (setq buffer-read-only t)
3917 (if org-fit-agenda-window
3918 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3919 (/ (frame-height) 2)))
3920 (unless (and (pos-visible-in-window-p (point-min))
3921 (pos-visible-in-window-p (point-max)))
3922 (goto-char (1- (point-max)))
3923 (recenter -1)
3924 (if (not (pos-visible-in-window-p (or start-pos 1)))
3925 (progn
3926 (goto-char (or start-pos 1))
3927 (recenter 1))))
3928 (goto-char (or start-pos 1))
3929 (if (not org-select-agenda-window) (select-window win))
3930 (message "")))
3931
3932 (defun org-check-agenda-file (file)
3933 "Make sure FILE exists. If not, ask user what to do."
3934 ;; FIXME: this does not correctly change the menus
3935 ;; Could probably be fixed by explicitly going to the buffer.
3936 (when (not (file-exists-p file))
3937 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3938 file)
3939 (let ((r (downcase (read-char-exclusive))))
3940 (cond
3941 ((equal r ?r)
3942 (org-remove-file file)
3943 (throw 'nextfile t))
3944 (t (error "Abort"))))))
3945
3946 (defun org-agenda-quit ()
3947 "Exit agenda by removing the window or the buffer."
3948 (interactive)
3949 (let ((buf (current-buffer)))
3950 (if (not (one-window-p)) (delete-window))
3951 (kill-buffer buf)
3952 (org-agenda-maybe-reset-markers 'force)))
3953
3954 (defun org-agenda-exit ()
3955 "Exit agenda by removing the window or the buffer.
3956 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3957 Org-mode buffers visited directly by the user will not be touched."
3958 (interactive)
3959 (org-release-buffers org-agenda-new-buffers)
3960 (setq org-agenda-new-buffers nil)
3961 (org-agenda-quit))
3962
3963 (defun org-agenda-redo ()
3964 "Rebuild Agenda."
3965 (interactive)
3966 (eval org-agenda-redo-command))
3967
3968 (defun org-agenda-goto-today ()
3969 "Go to today."
3970 (interactive)
3971 (if (boundp 'starting-day)
3972 (let ((cmd (car org-agenda-redo-command))
3973 (iall (nth 1 org-agenda-redo-command))
3974 (nday (nth 3 org-agenda-redo-command)))
3975 (eval (list cmd iall nil nday)))
3976 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3977 (point-min)))))
3978
3979 (defun org-agenda-later (arg)
3980 "Go forward in time by `org-agenda-ndays' days.
3981 With prefix ARG, go forward that many times `org-agenda-ndays'."
3982 (interactive "p")
3983 (unless (boundp 'starting-day)
3984 (error "Not allowed"))
3985 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3986 (+ starting-day (* arg org-agenda-ndays))))
3987
3988 (defun org-agenda-earlier (arg)
3989 "Go back in time by `org-agenda-ndays' days.
3990 With prefix ARG, go back that many times `org-agenda-ndays'."
3991 (interactive "p")
3992 (unless (boundp 'starting-day)
3993 (error "Not allowed"))
3994 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3995 (- starting-day (* arg org-agenda-ndays))))
3996
3997 (defun org-agenda-week-view ()
3998 "Switch to weekly view for agenda."
3999 (interactive)
4000 (unless (boundp 'starting-day)
4001 (error "Not allowed"))
4002 (setq org-agenda-ndays 7)
4003 (org-agenda include-all-loc
4004 (or (get-text-property (point) 'day)
4005 starting-day))
4006 (org-agenda-set-mode-name)
4007 (message "Switched to week view"))
4008
4009 (defun org-agenda-day-view ()
4010 "Switch to weekly view for agenda."
4011 (interactive)
4012 (unless (boundp 'starting-day)
4013 (error "Not allowed"))
4014 (setq org-agenda-ndays 1)
4015 (org-agenda include-all-loc
4016 (or (get-text-property (point) 'day)
4017 starting-day))
4018 (org-agenda-set-mode-name)
4019 (message "Switched to day view"))
4020
4021 (defun org-agenda-next-date-line (&optional arg)
4022 "Jump to the next line indicating a date in agenda buffer."
4023 (interactive "p")
4024 (beginning-of-line 1)
4025 (if (looking-at "^\\S-") (forward-char 1))
4026 (if (not (re-search-forward "^\\S-" nil t arg))
4027 (progn
4028 (backward-char 1)
4029 (error "No next date after this line in this buffer")))
4030 (goto-char (match-beginning 0)))
4031
4032 (defun org-agenda-previous-date-line (&optional arg)
4033 "Jump to the next line indicating a date in agenda buffer."
4034 (interactive "p")
4035 (beginning-of-line 1)
4036 (if (not (re-search-backward "^\\S-" nil t arg))
4037 (error "No previous date before this line in this buffer")))
4038
4039 ;; Initialize the highlight
4040 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4041 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4042 'face 'highlight)
4043
4044 (defun org-highlight (begin end &optional buffer)
4045 "Highlight a region with overlay."
4046 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4047 org-hl begin end (or buffer (current-buffer))))
4048
4049 (defun org-unhighlight ()
4050 "Detach overlay INDEX."
4051 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4052
4053
4054 (defun org-agenda-follow-mode ()
4055 "Toggle follow mode in an agenda buffer."
4056 (interactive)
4057 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4058 (org-agenda-set-mode-name)
4059 (message "Follow mode is %s"
4060 (if org-agenda-follow-mode "on" "off")))
4061
4062 (defun org-agenda-toggle-diary ()
4063 "Toggle follow mode in an agenda buffer."
4064 (interactive)
4065 (setq org-agenda-include-diary (not org-agenda-include-diary))
4066 (org-agenda-redo)
4067 (org-agenda-set-mode-name)
4068 (message "Diary inclusion turned %s"
4069 (if org-agenda-include-diary "on" "off")))
4070
4071 (defun org-agenda-toggle-time-grid ()
4072 "Toggle follow mode in an agenda buffer."
4073 (interactive)
4074 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4075 (org-agenda-redo)
4076 (org-agenda-set-mode-name)
4077 (message "Time-grid turned %s"
4078 (if org-agenda-use-time-grid "on" "off")))
4079
4080 (defun org-agenda-set-mode-name ()
4081 "Set the mode name to indicate all the small mode settings."
4082 (setq mode-name
4083 (concat "Org-Agenda"
4084 (if (equal org-agenda-ndays 1) " Day" "")
4085 (if (equal org-agenda-ndays 7) " Week" "")
4086 (if org-agenda-follow-mode " Follow" "")
4087 (if org-agenda-include-diary " Diary" "")
4088 (if org-agenda-use-time-grid " Grid" "")))
4089 (force-mode-line-update))
4090
4091 (defun org-agenda-post-command-hook ()
4092 (and (eolp) (not (bolp)) (backward-char 1))
4093 (if (and org-agenda-follow-mode
4094 (get-text-property (point) 'org-marker))
4095 (org-agenda-show)))
4096
4097 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4098
4099 (defun org-get-entries-from-diary (date)
4100 "Get the (Emacs Calendar) diary entries for DATE."
4101 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4102 (diary-display-hook '(fancy-diary-display))
4103 (list-diary-entries-hook
4104 (cons 'org-diary-default-entry list-diary-entries-hook))
4105 (diary-file-name-prefix-function nil) ; turn this feature off
4106 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4107 entries
4108 (org-disable-agenda-to-diary t))
4109 (save-excursion
4110 (save-window-excursion
4111 (list-diary-entries date 1)))
4112 (if (not (get-buffer fancy-diary-buffer))
4113 (setq entries nil)
4114 (with-current-buffer fancy-diary-buffer
4115 (setq buffer-read-only nil)
4116 (if (= (point-max) 1)
4117 ;; No entries
4118 (setq entries nil)
4119 ;; Omit the date and other unnecessary stuff
4120 (org-agenda-cleanup-fancy-diary)
4121 ;; Add prefix to each line and extend the text properties
4122 (if (= (point-max) 1)
4123 (setq entries nil)
4124 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4125 (set-buffer-modified-p nil)
4126 (kill-buffer fancy-diary-buffer)))
4127 (when entries
4128 (setq entries (org-split-string entries "\n"))
4129 (setq entries
4130 (mapcar
4131 (lambda (x)
4132 (setq x (org-format-agenda-item "" x "Diary" 'time))
4133 ;; Extend the text properties to the beginning of the line
4134 (add-text-properties
4135 0 (length x)
4136 (text-properties-at (1- (length x)) x)
4137 x)
4138 x)
4139 entries)))))
4140
4141 (defun org-agenda-cleanup-fancy-diary ()
4142 "Remove unwanted stuff in buffer created by fancy-diary-display.
4143 This gets rid of the date, the underline under the date, and
4144 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4145 date. Itt also removes lines that contain only whitespace."
4146 (goto-char (point-min))
4147 (if (looking-at ".*?:[ \t]*")
4148 (progn
4149 (replace-match "")
4150 (re-search-forward "\n=+$" nil t)
4151 (replace-match "")
4152 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4153 (re-search-forward "\n=+$" nil t)
4154 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4155 (goto-char (point-min))
4156 (while (re-search-forward "^ +\n" nil t)
4157 (replace-match ""))
4158 (goto-char (point-min))
4159 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4160 (replace-match "")))
4161
4162 ;; Make sure entries from the diary have the right text properties.
4163 (eval-after-load "diary-lib"
4164 '(if (boundp 'diary-modify-entry-list-string-function)
4165 ;; We can rely on the hook, nothing to do
4166 nil
4167 ;; Hook not avaiable, must use advice to make this work
4168 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4169 "Make the position visible."
4170 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4171 (stringp string)
4172 (buffer-file-name))
4173 (setq string (org-modify-diary-entry-string string))))))
4174
4175 (defun org-modify-diary-entry-string (string)
4176 "Add text properties to string, allowing org-mode to act on it."
4177 (add-text-properties
4178 0 (length string)
4179 (list 'mouse-face 'highlight
4180 'keymap org-agenda-keymap
4181 'help-echo
4182 (format
4183 "mouse-2 or RET jump to diary file %s"
4184 (abbreviate-file-name (buffer-file-name)))
4185 'org-agenda-diary-link t
4186 'org-marker (org-agenda-new-marker (point-at-bol)))
4187 string)
4188 string)
4189
4190 (defun org-diary-default-entry ()
4191 "Add a dummy entry to the diary.
4192 Needed to avoid empty dates which mess up holiday display."
4193 ;; Catch the error if dealing with the new add-to-diary-alist
4194 (when org-disable-agenda-to-diary
4195 (condition-case nil
4196 (add-to-diary-list original-date "Org-mode dummy" "")
4197 (error
4198 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4199
4200 (defun org-add-file (&optional file)
4201 "Add current file to the list of files in variable `org-agenda-files'.
4202 These are the files which are being checked for agenda entries.
4203 Optional argument FILE means, use this file instead of the current.
4204 It is possible (but not recommended) to add this function to the
4205 `org-mode-hook'."
4206 (interactive)
4207 (catch 'exit
4208 (let* ((file (or file (buffer-file-name)
4209 (if (interactive-p)
4210 (error "Buffer is not visiting a file")
4211 (throw 'exit nil))))
4212 (true-file (file-truename file))
4213 (afile (abbreviate-file-name file))
4214 (present (delq nil (mapcar
4215 (lambda (x)
4216 (equal true-file (file-truename x)))
4217 org-agenda-files))))
4218 (if (not present)
4219 (progn
4220 (setq org-agenda-files
4221 (cons afile org-agenda-files))
4222 ;; Make sure custom.el does not end up with Org-mode
4223 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4224 (customize-save-variable 'org-agenda-files org-agenda-files))
4225 (org-install-agenda-files-menu)
4226 (message "Added file: %s" afile))
4227 (message "File was already in list: %s" afile)))))
4228
4229 (defun org-remove-file (&optional file)
4230 "Remove current file from the list of files in variable `org-agenda-files'.
4231 These are the files which are being checked for agenda entries.
4232 Optional argument FILE means, use this file instead of the current."
4233 (interactive)
4234 (let* ((file (or file (buffer-file-name)))
4235 (true-file (file-truename file))
4236 (afile (abbreviate-file-name file))
4237 (files (delq nil (mapcar
4238 (lambda (x)
4239 (if (equal true-file
4240 (file-truename x))
4241 nil x))
4242 org-agenda-files))))
4243 (if (not (= (length files) (length org-agenda-files)))
4244 (progn
4245 (setq org-agenda-files files)
4246 (customize-save-variable 'org-agenda-files org-agenda-files)
4247 (org-install-agenda-files-menu)
4248 (message "Removed file: %s" afile))
4249 (message "File was not in list: %s" afile))))
4250
4251 (defun org-file-menu-entry (file)
4252 (vector file (list 'find-file file) t))
4253
4254 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4255 "Return a list of all relevant day numbers from BEG to END buffer positions.
4256 If NO-RANGES is non-nil, include only the start and end dates of a range,
4257 not every single day in the range. If FORCE-TODAY is non-nil, make
4258 sure that TODAY is included in the list."
4259 (let (dates date day day1 day2 ts1 ts2)
4260 (if force-today
4261 (setq dates (list (time-to-days (current-time)))))
4262 (save-excursion
4263 (goto-char beg)
4264 (while (re-search-forward org-ts-regexp end t)
4265 (setq day (time-to-days (org-time-string-to-time
4266 (substring (match-string 1) 0 10))))
4267 (or (memq day dates) (push day dates)))
4268 (unless no-ranges
4269 (goto-char beg)
4270 (while (re-search-forward org-tr-regexp end t)
4271 (setq ts1 (substring (match-string 1) 0 10)
4272 ts2 (substring (match-string 2) 0 10)
4273 day1 (time-to-days (org-time-string-to-time ts1))
4274 day2 (time-to-days (org-time-string-to-time ts2)))
4275 (while (< (setq day1 (1+ day1)) day2)
4276 (or (memq day1 dates) (push day1 dates)))))
4277 (sort dates '<))))
4278
4279 ;;;###autoload
4280 (defun org-diary (&rest args)
4281 "Return diary information from org-files.
4282 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4283 It accesses org files and extracts information from those files to be
4284 listed in the diary. The function accepts arguments specifying what
4285 items should be listed. The following arguments are allowed:
4286
4287 :timestamp List the headlines of items containing a date stamp or
4288 date range matching the selected date. Deadlines will
4289 also be listed, on the expiration day.
4290
4291 :deadline List any deadlines past due, or due within
4292 `org-deadline-warning-days'. The listing occurs only
4293 in the diary for *today*, not at any other date. If
4294 an entry is marked DONE, it is no longer listed.
4295
4296 :scheduled List all items which are scheduled for the given date.
4297 The diary for *today* also contains items which were
4298 scheduled earlier and are not yet marked DONE.
4299
4300 :todo List all TODO items from the org-file. This may be a
4301 long list - so this is not turned on by default.
4302 Like deadlines, these entries only show up in the
4303 diary for *today*, not at any other date.
4304
4305 The call in the diary file should look like this:
4306
4307 &%%(org-diary) ~/path/to/some/orgfile.org
4308
4309 Use a separate line for each org file to check. Or, if you omit the file name,
4310 all files listed in `org-agenda-files' will be checked automatically:
4311
4312 &%%(org-diary)
4313
4314 If you don't give any arguments (as in the example above), the default
4315 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4316 also be written as
4317
4318 &%%(org-diary :deadline :timestamp :scheduled)
4319
4320 The function expects the lisp variables `entry' and `date' to be provided
4321 by the caller, because this is how the calendar works. Don't use this
4322 function from a program - use `org-agenda-get-day-entries' instead."
4323 (org-agenda-maybe-reset-markers)
4324 (org-compile-prefix-format org-agenda-prefix-format)
4325 (setq args (or args '(:deadline :scheduled :timestamp)))
4326 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4327 (list entry)
4328 org-agenda-files))
4329 file rtn results)
4330 ;; If this is called during org-agenda, don't return any entries to
4331 ;; the calendar. Org Agenda will list these entries itself.
4332 (if org-disable-agenda-to-diary (setq files nil))
4333 (while (setq file (pop files))
4334 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4335 (setq results (append results rtn)))
4336 (if results
4337 (concat (org-finalize-agenda-entries results) "\n"))))
4338
4339 (defun org-agenda-get-day-entries (file date &rest args)
4340 "Does the work for `org-diary' and `org-agenda'.
4341 FILE is the path to a file to be checked for entries. DATE is date like
4342 the one returned by `calendar-current-date'. ARGS are symbols indicating
4343 which kind of entries should be extracted. For details about these, see
4344 the documentation of `org-diary'."
4345 (setq args (or args '(:deadline :scheduled :timestamp)))
4346 (let* ((org-startup-with-deadline-check nil)
4347 (org-startup-folded nil)
4348 (buffer (if (file-exists-p file)
4349 (org-get-agenda-file-buffer file)
4350 (error "No such file %s" file)))
4351 arg results rtn)
4352 (if (not buffer)
4353 ;; If file does not exist, make sure an error message ends up in diary
4354 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4355 (with-current-buffer buffer
4356 (unless (eq major-mode 'org-mode)
4357 (error "Agenda file %s is not in `org-mode'" file))
4358 (let ((case-fold-search nil))
4359 (save-excursion
4360 (save-restriction
4361 (if org-respect-restriction
4362 (if (org-region-active-p)
4363 ;; Respect a region to restrict search
4364 (narrow-to-region (region-beginning) (region-end)))
4365 ;; If we work for the calendar or many files,
4366 ;; get rid of any restriction
4367 (widen))
4368 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4369 (while (setq arg (pop args))
4370 (cond
4371 ((and (eq arg :todo)
4372 (equal date (calendar-current-date)))
4373 (setq rtn (org-agenda-get-todos))
4374 (setq results (append results rtn)))
4375 ((eq arg :timestamp)
4376 (setq rtn (org-agenda-get-blocks))
4377 (setq results (append results rtn))
4378 (setq rtn (org-agenda-get-timestamps))
4379 (setq results (append results rtn)))
4380 ((eq arg :scheduled)
4381 (setq rtn (org-agenda-get-scheduled))
4382 (setq results (append results rtn)))
4383 ((and (eq arg :deadline)
4384 (equal date (calendar-current-date)))
4385 (setq rtn (org-agenda-get-deadlines))
4386 (setq results (append results rtn))))))))
4387 results))))
4388
4389 (defun org-entry-is-done-p ()
4390 "Is the current entry marked DONE?"
4391 (save-excursion
4392 (and (re-search-backward "[\r\n]\\*" nil t)
4393 (looking-at org-nl-done-regexp))))
4394
4395 (defun org-at-date-range-p ()
4396 "Is the cursor inside a date range?"
4397 (interactive)
4398 (save-excursion
4399 (catch 'exit
4400 (let ((pos (point)))
4401 (skip-chars-backward "^<\r\n")
4402 (skip-chars-backward "<")
4403 (and (looking-at org-tr-regexp)
4404 (>= (match-end 0) pos)
4405 (throw 'exit t))
4406 (skip-chars-backward "^<\r\n")
4407 (skip-chars-backward "<")
4408 (and (looking-at org-tr-regexp)
4409 (>= (match-end 0) pos)
4410 (throw 'exit t)))
4411 nil)))
4412
4413 (defun org-agenda-get-todos ()
4414 "Return the TODO information for agenda display."
4415 (let* ((props (list 'face nil
4416 'done-face 'org-done
4417 'mouse-face 'highlight
4418 'keymap org-agenda-keymap
4419 'help-echo
4420 (format "mouse-2 or RET jump to org file %s"
4421 (abbreviate-file-name (buffer-file-name)))))
4422 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4423 "[^\n\r]*\\)"))
4424 marker priority
4425 ee txt)
4426 (goto-char (point-min))
4427 (while (re-search-forward regexp nil t)
4428 (goto-char (match-beginning 1))
4429 (setq marker (org-agenda-new-marker (point-at-bol))
4430 txt (org-format-agenda-item "" (match-string 1))
4431 priority
4432 (+ (org-get-priority txt)
4433 (if org-todo-kwd-priority-p
4434 (- org-todo-kwd-max-priority -2
4435 (length
4436 (member (match-string 2) org-todo-keywords)))
4437 1)))
4438 (add-text-properties
4439 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4440 'priority priority)
4441 props)
4442 txt)
4443 (push txt ee)
4444 (goto-char (match-end 1)))
4445 (nreverse ee)))
4446
4447 (defconst org-agenda-no-heading-message
4448 "No heading for this item in buffer or region")
4449
4450 (defun org-agenda-get-timestamps ()
4451 "Return the date stamp information for agenda display."
4452 (let* ((props (list 'face nil
4453 'mouse-face 'highlight
4454 'keymap org-agenda-keymap
4455 'help-echo
4456 (format "mouse-2 or RET jump to org file %s"
4457 (abbreviate-file-name (buffer-file-name)))))
4458 (regexp (regexp-quote
4459 (substring
4460 (format-time-string
4461 (car org-time-stamp-formats)
4462 (apply 'encode-time ; DATE bound by calendar
4463 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4464 0 11)))
4465 marker hdmarker deadlinep scheduledp donep tmp priority
4466 ee txt timestr)
4467 (goto-char (point-min))
4468 (while (re-search-forward regexp nil t)
4469 (if (not (save-match-data (org-at-date-range-p)))
4470 (progn
4471 (setq marker (org-agenda-new-marker (match-beginning 0))
4472 tmp (buffer-substring (max (point-min)
4473 (- (match-beginning 0)
4474 org-ds-keyword-length))
4475 (match-beginning 0))
4476 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4477 deadlinep (string-match org-deadline-regexp tmp)
4478 scheduledp (string-match org-scheduled-regexp tmp)
4479 donep (org-entry-is-done-p))
4480 (if (string-match ">" timestr)
4481 ;; substring should only run to end of time stamp
4482 (setq timestr (substring timestr 0 (match-end 0))))
4483 (save-excursion
4484 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4485 (progn
4486 (goto-char (match-end 1))
4487 (setq hdmarker (org-agenda-new-marker))
4488 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4489 (setq txt (org-format-agenda-item
4490 (format "%s%s"
4491 (if deadlinep "Deadline: " "")
4492 (if scheduledp "Scheduled: " ""))
4493 (match-string 1) nil timestr)))
4494 (setq txt org-agenda-no-heading-message))
4495 (setq priority (org-get-priority txt))
4496 (add-text-properties
4497 0 (length txt) (append (list 'org-marker marker
4498 'org-hd-marker hdmarker) props)
4499 txt)
4500 (if deadlinep
4501 (add-text-properties
4502 0 (length txt)
4503 (list 'face
4504 (if donep 'org-done 'org-warning)
4505 'undone-face 'org-warning
4506 'done-face 'org-done
4507 'priority (+ 100 priority))
4508 txt)
4509 (if scheduledp
4510 (add-text-properties
4511 0 (length txt)
4512 (list 'face 'org-scheduled-today
4513 'undone-face 'org-scheduled-today
4514 'done-face 'org-done
4515 priority (+ 99 priority))
4516 txt)
4517 (add-text-properties
4518 0 (length txt)
4519 (list 'priority priority) txt)))
4520 (push txt ee))
4521 (outline-next-heading))))
4522 (nreverse ee)))
4523
4524 (defun org-agenda-get-deadlines ()
4525 "Return the deadline information for agenda display."
4526 (let* ((wdays org-deadline-warning-days)
4527 (props (list 'mouse-face 'highlight
4528 'keymap org-agenda-keymap
4529 'help-echo
4530 (format "mouse-2 or RET jump to org file %s"
4531 (abbreviate-file-name (buffer-file-name)))))
4532 (regexp org-deadline-time-regexp)
4533 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4534 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4535 d2 diff pos pos1
4536 ee txt head)
4537 (goto-char (point-min))
4538 (while (re-search-forward regexp nil t)
4539 (setq pos (1- (match-beginning 1))
4540 d2 (time-to-days
4541 (org-time-string-to-time (match-string 1)))
4542 diff (- d2 d1))
4543 ;; When to show a deadline in the calendar:
4544 ;; If the expiration is within wdays warning time.
4545 ;; Past-due deadlines are only shown on the current date
4546 (if (and (< diff wdays) todayp (not (= diff 0)))
4547 (save-excursion
4548 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4549 (progn
4550 (goto-char (match-end 0))
4551 (setq pos1 (match-end 1))
4552 (setq head (buffer-substring-no-properties
4553 (point)
4554 (progn (skip-chars-forward "^\r\n")
4555 (point))))
4556 (if (string-match org-looking-at-done-regexp head)
4557 (setq txt nil)
4558 (setq txt (org-format-agenda-item
4559 (format "In %3d d.: " diff) head))))
4560 (setq txt org-agenda-no-heading-message))
4561 (when txt
4562 (add-text-properties
4563 0 (length txt)
4564 (append
4565 (list 'org-marker (org-agenda-new-marker pos)
4566 'org-hd-marker (org-agenda-new-marker pos1)
4567 'priority (+ (- 10 diff) (org-get-priority txt))
4568 'face (cond ((<= diff 0) 'org-warning)
4569 ((<= diff 5) 'org-scheduled-previously)
4570 (t nil))
4571 'undone-face (cond
4572 ((<= diff 0) 'org-warning)
4573 ((<= diff 5) 'org-scheduled-previously)
4574 (t nil))
4575 'done-face 'org-done)
4576 props)
4577 txt)
4578 (push txt ee)))))
4579 ee))
4580
4581 (defun org-agenda-get-scheduled ()
4582 "Return the scheduled information for agenda display."
4583 (let* ((props (list 'face 'org-scheduled-previously
4584 'undone-face 'org-scheduled-previously
4585 'done-face 'org-done
4586 'mouse-face 'highlight
4587 'keymap org-agenda-keymap
4588 'help-echo
4589 (format "mouse-2 or RET jump to org file %s"
4590 (abbreviate-file-name (buffer-file-name)))))
4591 (regexp org-scheduled-time-regexp)
4592 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4593 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4594 d2 diff pos pos1
4595 ee txt head)
4596 (goto-char (point-min))
4597 (while (re-search-forward regexp nil t)
4598 (setq pos (1- (match-beginning 1))
4599 d2 (time-to-days
4600 (org-time-string-to-time (match-string 1)))
4601 diff (- d2 d1))
4602 ;; When to show a scheduled item in the calendar:
4603 ;; If it is on or past the date.
4604 (if (and (< diff 0) todayp)
4605 (save-excursion
4606 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4607 (progn
4608 (goto-char (match-end 0))
4609 (setq pos1 (match-end 1))
4610 (setq head (buffer-substring-no-properties
4611 (point)
4612 (progn (skip-chars-forward "^\r\n") (point))))
4613 (if (string-match org-looking-at-done-regexp head)
4614 (setq txt nil)
4615 (setq txt (org-format-agenda-item
4616 (format "Sched.%2dx: " (- 1 diff)) head))))
4617 (setq txt org-agenda-no-heading-message))
4618 (when txt
4619 (add-text-properties
4620 0 (length txt)
4621 (append (list 'org-marker (org-agenda-new-marker pos)
4622 'org-hd-marker (org-agenda-new-marker pos1)
4623 'priority (+ (- 5 diff) (org-get-priority txt)))
4624 props) txt)
4625 (push txt ee)))))
4626 ee))
4627
4628 (defun org-agenda-get-blocks ()
4629 "Return the date-range information for agenda display."
4630 (let* ((props (list 'face nil
4631 'mouse-face 'highlight
4632 'keymap org-agenda-keymap
4633 'help-echo
4634 (format "mouse-2 or RET jump to org file %s"
4635 (abbreviate-file-name (buffer-file-name)))))
4636 (regexp org-tr-regexp)
4637 (d0 (calendar-absolute-from-gregorian date))
4638 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4639 (goto-char (point-min))
4640 (while (re-search-forward regexp nil t)
4641 (setq timestr (match-string 0)
4642 s1 (match-string 1)
4643 s2 (match-string 2)
4644 d1 (time-to-days (org-time-string-to-time s1))
4645 d2 (time-to-days (org-time-string-to-time s2)))
4646 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4647 ;; Only allow days between the limits, because the normal
4648 ;; date stamps will catch the limits.
4649 (save-excursion
4650 (setq marker (org-agenda-new-marker (point)))
4651 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4652 (progn
4653 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4654 (goto-char (match-end 1))
4655 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4656 (setq txt (org-format-agenda-item
4657 (format (if (= d1 d2) "" "(%d/%d): ")
4658 (1+ (- d0 d1)) (1+ (- d2 d1)))
4659 (match-string 1) nil (if (= d0 d1) timestr))))
4660 (setq txt org-agenda-no-heading-message))
4661 (add-text-properties
4662 0 (length txt) (append (list 'org-marker marker
4663 'org-hd-marker hdmarker
4664 'priority (org-get-priority txt))
4665 props)
4666 txt)
4667 (push txt ee)))
4668 (outline-next-heading))
4669 ;; Sort the entries by expiration date.
4670 (nreverse ee)))
4671
4672
4673
4674 (defconst org-plain-time-of-day-regexp
4675 (concat
4676 "\\(\\<[012]?[0-9]"
4677 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4678 "\\(--?"
4679 "\\(\\<[012]?[0-9]"
4680 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4681 "\\)?")
4682 "Regular expression to match a plain time or time range.
4683 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4684 groups carry important information:
4685 0 the full match
4686 1 the first time, range or not
4687 8 the second time, if it is a range.")
4688
4689 (defconst org-stamp-time-of-day-regexp
4690 (concat
4691 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4692 "\\([012][0-9]:[0-5][0-9]\\)>"
4693 "\\(--?"
4694 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4695 "Regular expression to match a timestamp time or time range.
4696 After a match, the following groups carry important information:
4697 0 the full match
4698 1 date plus weekday, for backreferencing to make sure both times on same day
4699 2 the first time, range or not
4700 4 the second time, if it is a range.")
4701
4702 (defvar org-prefix-has-time nil
4703 "A flag, set by `org-compile-prefix-format'.
4704 The flag is set if the currently compiled format contains a `%t'.")
4705
4706 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4707 "Format TXT to be inserted into the agenda buffer.
4708 In particular, it adds the prefix and corresponding text properties. EXTRA
4709 must be a string and replaces the `%s' specifier in the prefix format.
4710 CATEGORY (string, symbol or nil) may be used to overule the default
4711 category taken from local variable or file name. It will replace the `%c'
4712 specifier in the format. DOTIME, when non-nil, indicates that a
4713 time-of-day should be extracted from TXT for sorting of this entry, and for
4714 the `%t' specifier in the format. When DOTIME is a string, this string is
4715 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4716 only the correctly processes TXT should be returned - this is used by
4717 `org-agenda-change-all-lines'."
4718 (save-match-data
4719 ;; Diary entries sometimes have extra whitespace at the beginning
4720 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4721 (let* ((category (or category
4722 org-category
4723 (if (buffer-file-name)
4724 (file-name-sans-extension
4725 (file-name-nondirectory (buffer-file-name)))
4726 "")))
4727 time ;; needed for the eval of the prefix format
4728 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4729 (time-of-day (and dotime (org-get-time-of-day ts)))
4730 stamp plain s0 s1 s2 rtn)
4731 (when (and dotime time-of-day org-prefix-has-time)
4732 ;; Extract starting and ending time and move them to prefix
4733 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4734 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4735 (setq s0 (match-string 0 ts)
4736 s1 (match-string (if plain 1 2) ts)
4737 s2 (match-string (if plain 8 4) ts))
4738
4739 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4740 ;; them, we might want to remove them there to avoid duplication.
4741 ;; The user can turn this off with a variable.
4742 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4743 (string-match (concat (regexp-quote s0) " *") txt)
4744 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4745 (= (match-beginning 0) 0)
4746 t))
4747 (setq txt (replace-match "" nil nil txt))))
4748 ;; Normalize the time(s) to 24 hour
4749 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4750 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4751
4752 ;; Create the final string
4753 (if noprefix
4754 (setq rtn txt)
4755 ;; Prepare the variables needed in the eval of the compiled format
4756 (setq time (cond (s2 (concat s1 "-" s2))
4757 (s1 (concat s1 "......"))
4758 (t ""))
4759 extra (or extra "")
4760 category (if (symbolp category) (symbol-name category) category))
4761 ;; Evaluate the compiled format
4762 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4763
4764 ;; And finally add the text properties
4765 (add-text-properties
4766 0 (length rtn) (list 'category (downcase category)
4767 'prefix-length (- (length rtn) (length txt))
4768 'time-of-day time-of-day
4769 'dotime dotime)
4770 rtn)
4771 rtn)))
4772
4773 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4774 (catch 'exit
4775 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4776 ((and todayp (member 'today (car org-agenda-time-grid))))
4777 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4778 ((member 'weekly (car org-agenda-time-grid)))
4779 (t (throw 'exit list)))
4780 (let* ((have (delq nil (mapcar
4781 (lambda (x) (get-text-property 1 'time-of-day x))
4782 list)))
4783 (string (nth 1 org-agenda-time-grid))
4784 (gridtimes (nth 2 org-agenda-time-grid))
4785 (req (car org-agenda-time-grid))
4786 (remove (member 'remove-match req))
4787 new time)
4788 (if (and (member 'require-timed req) (not have))
4789 ;; don't show empty grid
4790 (throw 'exit list))
4791 (while (setq time (pop gridtimes))
4792 (unless (and remove (member time have))
4793 (setq time (int-to-string time))
4794 (push (org-format-agenda-item
4795 nil string "" ;; FIXME: put a category?
4796 (concat (substring time 0 -2) ":" (substring time -2)))
4797 new)
4798 (put-text-property
4799 1 (length (car new)) 'face 'org-time-grid (car new))))
4800 (if (member 'time-up org-agenda-sorting-strategy)
4801 (append new list)
4802 (append list new)))))
4803
4804 (defun org-compile-prefix-format (format)
4805 "Compile the prefix format into a Lisp form that can be evaluated.
4806 The resulting form is returned and stored in the variable
4807 `org-prefix-format-compiled'."
4808 (setq org-prefix-has-time nil)
4809 (let ((start 0) varform vars var (s format) c f opt)
4810 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4811 s start)
4812 (setq var (cdr (assoc (match-string 4 s)
4813 '(("c" . category) ("t" . time) ("s" . extra))))
4814 c (or (match-string 3 s) "")
4815 opt (match-beginning 1)
4816 start (1+ (match-beginning 0)))
4817 (if (equal var 'time) (setq org-prefix-has-time t))
4818 (setq f (concat "%" (match-string 2 s) "s"))
4819 (if opt
4820 (setq varform
4821 `(if (equal "" ,var)
4822 ""
4823 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4824 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4825 (setq s (replace-match "%s" t nil s))
4826 (push varform vars))
4827 (setq vars (nreverse vars))
4828 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4829
4830 (defun org-get-time-of-day (s &optional string)
4831 "Check string S for a time of day.
4832 If found, return it as a military time number between 0 and 2400.
4833 If not found, return nil.
4834 The optional STRING argument forces conversion into a 5 character wide string
4835 HH:MM."
4836 (save-match-data
4837 (when
4838 (or
4839 (string-match
4840 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4841 (string-match
4842 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4843 (let* ((t0 (+ (* 100
4844 (+ (string-to-number (match-string 1 s))
4845 (if (and (match-beginning 4)
4846 (equal (downcase (match-string 4 s)) "pm"))
4847 12 0)))
4848 (if (match-beginning 3)
4849 (string-to-number (match-string 3 s))
4850 0)))
4851 (t1 (concat " " (int-to-string t0))))
4852 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4853
4854 (defun org-finalize-agenda-entries (list)
4855 "Sort and concatenate the agenda items."
4856 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4857
4858 (defsubst org-cmp-priority (a b)
4859 "Compare the priorities of string a and b."
4860 (let ((pa (or (get-text-property 1 'priority a) 0))
4861 (pb (or (get-text-property 1 'priority b) 0)))
4862 (cond ((> pa pb) +1)
4863 ((< pa pb) -1)
4864 (t nil))))
4865
4866 (defsubst org-cmp-category (a b)
4867 "Compare the string values of categories of strings a and b."
4868 (let ((ca (or (get-text-property 1 'category a) ""))
4869 (cb (or (get-text-property 1 'category b) "")))
4870 (cond ((string-lessp ca cb) -1)
4871 ((string-lessp cb ca) +1)
4872 (t nil))))
4873
4874 (defsubst org-cmp-time (a b)
4875 "Compare the time-of-day values of strings a and b."
4876 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4877 (ta (or (get-text-property 1 'time-of-day a) def))
4878 (tb (or (get-text-property 1 'time-of-day b) def)))
4879 (cond ((< ta tb) -1)
4880 ((< tb ta) +1)
4881 (t nil))))
4882
4883 (defun org-entries-lessp (a b)
4884 "Predicate for sorting agenda entries."
4885 ;; The following variables will be used when the form is evaluated.
4886 (let* ((time-up (org-cmp-time a b))
4887 (time-down (if time-up (- time-up) nil))
4888 (priority-up (org-cmp-priority a b))
4889 (priority-down (if priority-up (- priority-up) nil))
4890 (category-up (org-cmp-category a b))
4891 (category-down (if category-up (- category-up) nil))
4892 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4893 (cdr (assoc
4894 (eval (cons 'or org-agenda-sorting-strategy))
4895 '((-1 . t) (1 . nil) (nil . nil))))))
4896
4897 (defun org-agenda-show-priority ()
4898 "Show the priority of the current item.
4899 This priority is composed of the main priority given with the [#A] cookies,
4900 and by additional input from the age of a schedules or deadline entry."
4901 (interactive)
4902 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4903 (message "Priority is %d" (if pri pri -1000))))
4904
4905 (defun org-agenda-goto (&optional highlight)
4906 "Go to the Org-mode file which contains the item at point."
4907 (interactive)
4908 (let* ((marker (or (get-text-property (point) 'org-marker)
4909 (org-agenda-error)))
4910 (buffer (marker-buffer marker))
4911 (pos (marker-position marker)))
4912 (switch-to-buffer-other-window buffer)
4913 (widen)
4914 (goto-char pos)
4915 (when (eq major-mode 'org-mode)
4916 (org-show-hidden-entry)
4917 (save-excursion
4918 (and (outline-next-heading)
4919 (org-flag-heading nil)))) ; show the next heading
4920 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4921
4922 (defun org-agenda-switch-to ()
4923 "Go to the Org-mode file which contains the item at point."
4924 (interactive)
4925 (let* ((marker (or (get-text-property (point) 'org-marker)
4926 (org-agenda-error)))
4927 (buffer (marker-buffer marker))
4928 (pos (marker-position marker)))
4929 (switch-to-buffer buffer)
4930 (delete-other-windows)
4931 (widen)
4932 (goto-char pos)
4933 (when (eq major-mode 'org-mode)
4934 (org-show-hidden-entry)
4935 (save-excursion
4936 (and (outline-next-heading)
4937 (org-flag-heading nil)))))) ; show the next heading
4938
4939 (defun org-agenda-goto-mouse (ev)
4940 "Go to the Org-mode file which contains the item at the mouse click."
4941 (interactive "e")
4942 (mouse-set-point ev)
4943 (org-agenda-goto))
4944
4945 (defun org-agenda-show ()
4946 "Display the Org-mode file which contains the item at point."
4947 (interactive)
4948 (let ((win (selected-window)))
4949 (org-agenda-goto t)
4950 (select-window win)))
4951
4952 (defun org-agenda-recenter (arg)
4953 "Display the Org-mode file which contains the item at point and recenter."
4954 (interactive "P")
4955 (let ((win (selected-window)))
4956 (org-agenda-goto t)
4957 (recenter arg)
4958 (select-window win)))
4959
4960 (defun org-agenda-show-mouse (ev)
4961 "Display the Org-mode file which contains the item at the mouse click."
4962 (interactive "e")
4963 (mouse-set-point ev)
4964 (org-agenda-show))
4965
4966 (defun org-agenda-check-no-diary ()
4967 "Check if the entry is a diary link and abort if yes."
4968 (if (get-text-property (point) 'org-agenda-diary-link)
4969 (org-agenda-error)))
4970
4971 (defun org-agenda-error ()
4972 (error "Command not allowed in this line"))
4973
4974 (defvar org-last-heading-marker (make-marker)
4975 "Marker pointing to the headline that last changed its TODO state
4976 by a remote command from the agenda.")
4977
4978 (defun org-agenda-todo ()
4979 "Cycle TODO state of line at point, also in Org-mode file.
4980 This changes the line at point, all other lines in the agenda referring to
4981 the same tree node, and the headline of the tree node in the Org-mode file."
4982 (interactive)
4983 (org-agenda-check-no-diary)
4984 (let* ((col (current-column))
4985 (marker (or (get-text-property (point) 'org-marker)
4986 (org-agenda-error)))
4987 (buffer (marker-buffer marker))
4988 (pos (marker-position marker))
4989 (hdmarker (get-text-property (point) 'org-hd-marker))
4990 (buffer-read-only nil)
4991 newhead)
4992 (with-current-buffer buffer
4993 (widen)
4994 (goto-char pos)
4995 (org-show-hidden-entry)
4996 (save-excursion
4997 (and (outline-next-heading)
4998 (org-flag-heading nil))) ; show the next heading
4999 (org-todo)
5000 (forward-char 1)
5001 (setq newhead (org-get-heading))
5002 (save-excursion
5003 (org-back-to-heading)
5004 (move-marker org-last-heading-marker (point))))
5005 (beginning-of-line 1)
5006 (save-excursion
5007 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5008 (move-to-column col)))
5009
5010 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5011 "Change all lines in the agenda buffer which match hdmarker.
5012 The new content of the line will be NEWHEAD (as modified by
5013 `org-format-agenda-item'). HDMARKER is checked with
5014 `equal' against all `org-hd-marker' text properties in the file.
5015 If FIXFACE is non-nil, the face of each item is modified acording to
5016 the new TODO state."
5017 (let* (props m pl undone-face done-face finish new dotime)
5018 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5019 (save-excursion
5020 (goto-char (point-max))
5021 (beginning-of-line 1)
5022 (while (not finish)
5023 (setq finish (bobp))
5024 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5025 (equal m hdmarker))
5026 (setq props (text-properties-at (point))
5027 dotime (get-text-property (point) 'dotime)
5028 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
5029 pl (get-text-property (point) 'prefix-length)
5030 undone-face (get-text-property (point) 'undone-face)
5031 done-face (get-text-property (point) 'done-face))
5032 (move-to-column pl)
5033 (if (looking-at ".*")
5034 (progn
5035 (replace-match new t t)
5036 (beginning-of-line 1)
5037 (add-text-properties (point-at-bol) (point-at-eol) props)
5038 (if fixface
5039 (add-text-properties
5040 (point-at-bol) (point-at-eol)
5041 (list 'face
5042 (if org-last-todo-state-is-todo
5043 undone-face done-face))))
5044 (beginning-of-line 1))
5045 (error "Line update did not work")))
5046 (beginning-of-line 0)))))
5047
5048 (defun org-agenda-priority-up ()
5049 "Increase the priority of line at point, also in Org-mode file."
5050 (interactive)
5051 (org-agenda-priority 'up))
5052
5053 (defun org-agenda-priority-down ()
5054 "Decrease the priority of line at point, also in Org-mode file."
5055 (interactive)
5056 (org-agenda-priority 'down))
5057
5058 (defun org-agenda-priority (&optional force-direction)
5059 "Set the priority of line at point, also in Org-mode file.
5060 This changes the line at point, all other lines in the agenda referring to
5061 the same tree node, and the headline of the tree node in the Org-mode file."
5062 (interactive)
5063 (org-agenda-check-no-diary)
5064 (let* ((marker (or (get-text-property (point) 'org-marker)
5065 (org-agenda-error)))
5066 (buffer (marker-buffer marker))
5067 (pos (marker-position marker))
5068 (hdmarker (get-text-property (point) 'org-hd-marker))
5069 (buffer-read-only nil)
5070 newhead)
5071 (with-current-buffer buffer
5072 (widen)
5073 (goto-char pos)
5074 (org-show-hidden-entry)
5075 (save-excursion
5076 (and (outline-next-heading)
5077 (org-flag-heading nil))) ; show the next heading
5078 (funcall 'org-priority force-direction)
5079 (end-of-line 1)
5080 (setq newhead (org-get-heading)))
5081 (org-agenda-change-all-lines newhead hdmarker)
5082 (beginning-of-line 1)))
5083
5084 (defun org-agenda-date-later (arg &optional what)
5085 "Change the date of this item to one day later."
5086 (interactive "p")
5087 (org-agenda-check-no-diary)
5088 (let* ((marker (or (get-text-property (point) 'org-marker)
5089 (org-agenda-error)))
5090 (buffer (marker-buffer marker))
5091 (pos (marker-position marker)))
5092 (with-current-buffer buffer
5093 (widen)
5094 (goto-char pos)
5095 (if (not (org-at-timestamp-p))
5096 (error "Cannot find time stamp"))
5097 (org-timestamp-change arg (or what 'day))
5098 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5099
5100 (defun org-agenda-date-earlier (arg &optional what)
5101 "Change the date of this item to one day earlier."
5102 (interactive "p")
5103 (org-agenda-date-later (- arg) what))
5104
5105 (defun org-agenda-date-prompt (arg)
5106 "Change the date of this item. Date is prompted for, with default today.
5107 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5108 be used to request time specification in the time stamp."
5109 (interactive "P")
5110 (org-agenda-check-no-diary)
5111 (let* ((marker (or (get-text-property (point) 'org-marker)
5112 (org-agenda-error)))
5113 (buffer (marker-buffer marker))
5114 (pos (marker-position marker)))
5115 (with-current-buffer buffer
5116 (widen)
5117 (goto-char pos)
5118 (if (not (org-at-timestamp-p))
5119 (error "Cannot find time stamp"))
5120 (org-time-stamp arg)
5121 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5122
5123 (defun org-get-heading ()
5124 "Return the heading of the current entry, without the stars."
5125 (save-excursion
5126 (if (and (re-search-backward "[\r\n]\\*" nil t)
5127 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5128 (match-string 1)
5129 "")))
5130
5131 (defun org-agenda-diary-entry ()
5132 "Make a diary entry, like the `i' command from the calendar.
5133 All the standard commands work: block, weekly etc"
5134 (interactive)
5135 (require 'diary-lib)
5136 (let* ((char (progn
5137 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5138 (read-char-exclusive)))
5139 (cmd (cdr (assoc char
5140 '((?d . insert-diary-entry)
5141 (?w . insert-weekly-diary-entry)
5142 (?m . insert-monthly-diary-entry)
5143 (?y . insert-yearly-diary-entry)
5144 (?a . insert-anniversary-diary-entry)
5145 (?b . insert-block-diary-entry)
5146 (?c . insert-cyclic-diary-entry)))))
5147 (oldf (symbol-function 'calendar-cursor-to-date))
5148 (point (point))
5149 (mark (or (mark t) (point))))
5150 (unless cmd
5151 (error "No command associated with <%c>" char))
5152 (unless (and (get-text-property point 'day)
5153 (or (not (equal ?b char))
5154 (get-text-property mark 'day)))
5155 (error "Don't know which date to use for diary entry"))
5156 ;; We implement this by hacking the `calendar-cursor-to-date' function
5157 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5158 (let ((calendar-mark-ring
5159 (list (calendar-gregorian-from-absolute
5160 (or (get-text-property mark 'day)
5161 (get-text-property point 'day))))))
5162 (unwind-protect
5163 (progn
5164 (fset 'calendar-cursor-to-date
5165 (lambda (&optional error)
5166 (calendar-gregorian-from-absolute
5167 (get-text-property point 'day))))
5168 (call-interactively cmd))
5169 (fset 'calendar-cursor-to-date oldf)))))
5170
5171
5172 (defun org-agenda-execute-calendar-command (cmd)
5173 "Execute a calendar command from the agenda, with the date associated to
5174 the cursor position."
5175 (require 'diary-lib)
5176 (unless (get-text-property (point) 'day)
5177 (error "Don't know which date to use for calendar command"))
5178 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5179 (point (point))
5180 (date (calendar-gregorian-from-absolute
5181 (get-text-property point 'day)))
5182 (displayed-day (extract-calendar-day date))
5183 (displayed-month (extract-calendar-month date))
5184 (displayed-year (extract-calendar-year date)))
5185 (unwind-protect
5186 (progn
5187 (fset 'calendar-cursor-to-date
5188 (lambda (&optional error)
5189 (calendar-gregorian-from-absolute
5190 (get-text-property point 'day))))
5191 (call-interactively cmd))
5192 (fset 'calendar-cursor-to-date oldf))))
5193
5194 (defun org-agenda-phases-of-moon ()
5195 "Display the phases of the moon for the 3 months around the cursor date."
5196 (interactive)
5197 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5198
5199 (defun org-agenda-holidays ()
5200 "Display the holidays for the 3 months around the cursor date."
5201 (interactive)
5202 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5203
5204 (defun org-agenda-sunrise-sunset (arg)
5205 "Display sunrise and sunset for the cursor date.
5206 Latitude and longitude can be specified with the variables
5207 `calendar-latitude' and `calendar-longitude'. When called with prefix
5208 argument, latitude and longitude will be prompted for."
5209 (interactive "P")
5210 (let ((calendar-longitude (if arg nil calendar-longitude))
5211 (calendar-latitude (if arg nil calendar-latitude))
5212 (calendar-location-name
5213 (if arg "the given coordinates" calendar-location-name)))
5214 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5215
5216 (defun org-agenda-goto-calendar ()
5217 "Open the Emacs calendar with the date at the cursor."
5218 (interactive)
5219 (let* ((day (or (get-text-property (point) 'day)
5220 (error "Don't know which date to open in calendar")))
5221 (date (calendar-gregorian-from-absolute day)))
5222 (calendar)
5223 (calendar-goto-date date)))
5224
5225 (defun org-calendar-goto-agenda ()
5226 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5227 This is a command that has to be installed in `calendar-mode-map'."
5228 (interactive)
5229 (org-agenda nil (calendar-absolute-from-gregorian
5230 (calendar-cursor-to-date))))
5231
5232 (defun org-agenda-convert-date ()
5233 (interactive)
5234 (let ((day (get-text-property (point) 'day))
5235 date s)
5236 (unless day
5237 (error "Don't know which date to convert"))
5238 (setq date (calendar-gregorian-from-absolute day))
5239 (setq s (concat
5240 "Gregorian: " (calendar-date-string date) "\n"
5241 "ISO: " (calendar-iso-date-string date) "\n"
5242 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5243 "Julian: " (calendar-julian-date-string date) "\n"
5244 "Astron. JD: " (calendar-astro-date-string date)
5245 " (Julian date number at noon UTC)\n"
5246 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5247 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5248 "French: " (calendar-french-date-string date) "\n"
5249 "Mayan: " (calendar-mayan-date-string date) "\n"
5250 "Coptic: " (calendar-coptic-date-string date) "\n"
5251 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5252 "Persian: " (calendar-persian-date-string date) "\n"
5253 "Chinese: " (calendar-chinese-date-string date) "\n"))
5254 (with-output-to-temp-buffer "*Dates*"
5255 (princ s))
5256 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5257
5258 ;;; Link Stuff
5259
5260 (defun org-find-file-at-mouse (ev)
5261 "Open file link or URL at mouse."
5262 (interactive "e")
5263 (mouse-set-point ev)
5264 (org-open-at-point 'in-emacs))
5265
5266 (defun org-open-at-mouse (ev)
5267 "Open file link or URL at mouse."
5268 (interactive "e")
5269 (mouse-set-point ev)
5270 (org-open-at-point))
5271
5272 (defun org-open-at-point (&optional in-emacs)
5273 "Open link at or after point.
5274 If there is no link at point, this function will search forward up to
5275 the end of the current subtree.
5276 Normally, files will be opened by an appropriate application. If the
5277 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5278 (interactive "P")
5279 (if (org-at-timestamp-p)
5280 (org-agenda nil (time-to-days (org-time-string-to-time
5281 (substring (match-string 1) 0 10)))
5282 1)
5283 (let (type path line (pos (point)))
5284 (save-excursion
5285 (skip-chars-backward
5286 (concat (if org-allow-space-in-links "^" "^ ")
5287 org-non-link-chars))
5288 (if (re-search-forward
5289 org-link-regexp
5290 (save-excursion
5291 (condition-case nil
5292 (progn (outline-end-of-subtree) (max pos (point)))
5293 (error (end-of-line 1) (point))))
5294 t)
5295 (setq type (match-string 1)
5296 path (match-string 2)))
5297 (unless path
5298 (error "No link found"))
5299 ;; Remove any trailing spaces in path
5300 (if (string-match " +\\'" path)
5301 (setq path (replace-match "" t t path)))
5302
5303 (cond
5304
5305 ((string= type "file")
5306 (if (string-match ":\\([0-9]+\\)\\'" path)
5307 (setq line (string-to-number (match-string 1 path))
5308 path (substring path 0 (match-beginning 0))))
5309 (org-open-file path in-emacs line))
5310
5311 ((string= type "news")
5312 (org-follow-gnus-link path))
5313
5314 ((string= type "bbdb")
5315 (org-follow-bbdb-link path))
5316
5317 ((string= type "gnus")
5318 (let (group article)
5319 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5320 (error "Error in Gnus link"))
5321 (setq group (match-string 1 path)
5322 article (match-string 3 path))
5323 (org-follow-gnus-link group article)))
5324
5325 ((string= type "vm")
5326 (let (folder article)
5327 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5328 (error "Error in VM link"))
5329 (setq folder (match-string 1 path)
5330 article (match-string 3 path))
5331 ;; in-emacs is the prefix arg, will be interpreted as read-only
5332 (org-follow-vm-link folder article in-emacs)))
5333
5334 ((string= type "wl")
5335 (let (folder article)
5336 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5337 (error "Error in Wanderlust link"))
5338 (setq folder (match-string 1 path)
5339 article (match-string 3 path))
5340 (org-follow-wl-link folder article)))
5341
5342 ((string= type "rmail")
5343 (let (folder article)
5344 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5345 (error "Error in RMAIL link"))
5346 (setq folder (match-string 1 path)
5347 article (match-string 3 path))
5348 (org-follow-rmail-link folder article)))
5349
5350 ((string= type "shell")
5351 (let ((cmd path))
5352 (while (string-match "@{" cmd)
5353 (setq cmd (replace-match "<" t t cmd)))
5354 (while (string-match "@}" cmd)
5355 (setq cmd (replace-match ">" t t cmd)))
5356 (if (or (not org-confirm-shell-links)
5357 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5358 (shell-command cmd)
5359 (error "Abort"))))
5360
5361 (t
5362 (browse-url-at-point)))))))
5363
5364 (defun org-follow-bbdb-link (name)
5365 "Follow a BBDB link to NAME."
5366 (require 'bbdb)
5367 (let ((inhibit-redisplay t))
5368 (catch 'exit
5369 ;; Exact match on name
5370 (bbdb-name (concat "\\`" name "\\'") nil)
5371 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5372 ;; Exact match on name
5373 (bbdb-company (concat "\\`" name "\\'") nil)
5374 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5375 ;; Partial match on name
5376 (bbdb-name name nil)
5377 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5378 ;; Partial match on company
5379 (bbdb-company name nil)
5380 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5381 ;; General match including network address and notes
5382 (bbdb name nil)
5383 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5384 (delete-window (get-buffer-window "*BBDB*"))
5385 (error "No matching BBDB record")))))
5386
5387 (defun org-follow-gnus-link (&optional group article)
5388 "Follow a Gnus link to GROUP and ARTICLE."
5389 (require 'gnus)
5390 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5391 (if group (gnus-fetch-group group))
5392 (if article
5393 (or (gnus-summary-goto-article article nil 'force)
5394 (if (fboundp 'gnus-summary-insert-cached-articles)
5395 (progn
5396 (gnus-summary-insert-cached-articles)
5397 (gnus-summary-goto-article article nil 'force))
5398 (message "Message could not be found.")))))
5399
5400 (defun org-follow-vm-link (&optional folder article readonly)
5401 "Follow a VM link to FOLDER and ARTICLE."
5402 (require 'vm)
5403 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5404 ;; ange-ftp or efs or tramp access
5405 (let ((user (or (match-string 1 folder) (user-login-name)))
5406 (host (match-string 2 folder))
5407 (file (match-string 3 folder)))
5408 (cond
5409 ((featurep 'tramp)
5410 ;; use tramp to access the file
5411 (if org-xemacs-p
5412 (setq folder (format "[%s@%s]%s" user host file))
5413 (setq folder (format "/%s@%s:%s" user host file))))
5414 (t
5415 ;; use ange-ftp or efs
5416 (require (if org-xemacs-p 'efs 'ange-ftp))
5417 (setq folder (format "/%s@%s:%s" user host file))))))
5418 (when folder
5419 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5420 (sit-for 0.1)
5421 (when article
5422 (vm-select-folder-buffer)
5423 (widen)
5424 (let ((case-fold-search t))
5425 (goto-char (point-min))
5426 (if (not (re-search-forward
5427 (concat "^" "message-id: *" (regexp-quote article))))
5428 (error "Could not find the specified message in this folder"))
5429 (vm-isearch-update)
5430 (vm-isearch-narrow)
5431 (vm-beginning-of-message)
5432 (vm-summarize)))))
5433
5434 (defun org-follow-wl-link (folder article)
5435 "Follow a Wanderlust link to FOLDER and ARTICLE."
5436 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5437 (if article (wl-summary-jump-to-msg-by-message-id article))
5438 (wl-summary-redisplay))
5439
5440 (defun org-follow-rmail-link (folder article)
5441 "Follow an RMAIL link to FOLDER and ARTICLE."
5442 (let (message-number)
5443 (save-excursion
5444 (save-window-excursion
5445 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5446 (setq message-number
5447 (save-restriction
5448 (widen)
5449 (goto-char (point-max))
5450 (if (re-search-backward
5451 (concat "^Message-ID:\\s-+" (regexp-quote
5452 (or article "")))
5453 nil t)
5454 (rmail-what-message))))))
5455 (if message-number
5456 (progn
5457 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5458 (rmail-show-message message-number)
5459 message-number)
5460 (error "Message not found"))))
5461
5462 (defun org-open-file (path &optional in-emacs line)
5463 "Open the file at PATH.
5464 First, this expands any special file name abbreviations. Then the
5465 configuration variable `org-file-apps' is checked if it contains an
5466 entry for this file type, and if yes, the corresponding command is launched.
5467 If no application is found, Emacs simply visits the file.
5468 With optional argument IN-EMACS, Emacs will visit the file.
5469 If the file does not exist, an error is thrown."
5470 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5471 (dfile (downcase file))
5472 ext cmd apps)
5473 (if (and (not (file-exists-p file))
5474 (not org-open-non-existing-files))
5475 (error "No such file: %s" file))
5476 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5477 (setq ext (match-string 1 dfile))
5478 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5479 (setq ext (match-string 1 dfile))))
5480 (setq apps (append org-file-apps (org-default-apps)))
5481 (if in-emacs
5482 (setq cmd 'emacs)
5483 (setq cmd (or (cdr (assoc ext apps))
5484 (cdr (assoc t apps)))))
5485 (cond
5486 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5487 (setq cmd (format cmd (concat "\"" file "\"")))
5488 (save-window-excursion
5489 (shell-command (concat cmd " & &"))))
5490 ((or (stringp cmd)
5491 (eq cmd 'emacs))
5492 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5493 (if line (goto-line line)))
5494 ((consp cmd)
5495 (eval cmd))
5496 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5497
5498 (defun org-default-apps ()
5499 "Return the default applications for this operating system."
5500 (cond
5501 ((eq system-type 'darwin)
5502 org-file-apps-defaults-macosx)
5503 ((eq system-type 'windows-nt)
5504 org-file-apps-defaults-windowsnt)
5505 (t org-file-apps-defaults-gnu)))
5506
5507 (defun org-expand-file-name (path)
5508 "Replace special path abbreviations and expand the file name."
5509 (expand-file-name path))
5510
5511
5512 (defvar org-insert-link-history nil
5513 "Minibuffer history for links inserted with `org-insert-link'.")
5514
5515 (defvar org-stored-links nil
5516 "Contains the links stored with `org-store-link'.")
5517
5518 ;;;###autoload
5519 (defun org-store-link (arg)
5520 "\\<org-mode-map>Store an org-link to the current location.
5521 This link can later be inserted into an org-buffer with
5522 \\[org-insert-link].
5523 For some link types, a prefix arg is interpreted:
5524 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5525 For file links, arg negates `org-line-numbers-in-file-links'."
5526 (interactive "P")
5527 (let (link cpltxt)
5528 (cond
5529
5530 ((eq major-mode 'bbdb-mode)
5531 (setq cpltxt (concat
5532 "bbdb:"
5533 (or (bbdb-record-name (bbdb-current-record))
5534 (bbdb-record-company (bbdb-current-record))))
5535 link (org-make-link cpltxt)))
5536
5537 ((eq major-mode 'calendar-mode)
5538 (let ((cd (calendar-cursor-to-date)))
5539 (setq link
5540 (format-time-string
5541 (car org-time-stamp-formats)
5542 (apply 'encode-time
5543 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5544 nil nil nil))))))
5545
5546 ((or (eq major-mode 'vm-summary-mode)
5547 (eq major-mode 'vm-presentation-mode))
5548 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5549 (vm-follow-summary-cursor)
5550 (save-excursion
5551 (vm-select-folder-buffer)
5552 (let* ((message (car vm-message-pointer))
5553 (folder (buffer-file-name))
5554 (subject (vm-su-subject message))
5555 (author (vm-su-full-name message))
5556 (message-id (vm-su-message-id message)))
5557 (setq folder (abbreviate-file-name folder))
5558 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5559 folder)
5560 (setq folder (replace-match "" t t folder)))
5561 (setq cpltxt (concat author " on: " subject))
5562 (setq link (concat cpltxt "\n "
5563 (org-make-link
5564 "vm:" folder "#" message-id))))))
5565
5566 ((eq major-mode 'wl-summary-mode)
5567 (let* ((msgnum (wl-summary-message-number))
5568 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5569 msgnum 'message-id))
5570 (wl-message-entity (elmo-msgdb-overview-get-entity
5571 msgnum (wl-summary-buffer-msgdb)))
5572 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5573 (subject "???")) ; FIXME: How to get subject of email?
5574 (setq cpltxt (concat author " on: " subject))
5575 (setq link (concat cpltxt "\n "
5576 (org-make-link
5577 "wl:" wl-summary-buffer-folder-name
5578 "#" message-id)))))
5579
5580 ((eq major-mode 'rmail-mode)
5581 (save-excursion
5582 (save-restriction
5583 (rmail-narrow-to-non-pruned-header)
5584 (let ((folder (buffer-file-name))
5585 (message-id (mail-fetch-field "message-id"))
5586 (author (mail-fetch-field "from"))
5587 (subject (mail-fetch-field "subject")))
5588 (setq cpltxt (concat author " on: " subject))
5589 (setq link (concat cpltxt "\n "
5590 (org-make-link
5591 "rmail:" folder "#" message-id)))))))
5592
5593 ((eq major-mode 'gnus-group-mode)
5594 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5595 (gnus-group-group-name)) ; version
5596 ((fboundp 'gnus-group-name)
5597 (gnus-group-name))
5598 (t "???"))))
5599 (setq cpltxt (concat
5600 (if (org-xor arg org-usenet-links-prefer-google)
5601 "http://groups.google.com/groups?group="
5602 "gnus:")
5603 group)
5604 link (org-make-link cpltxt))))
5605
5606 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5607 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5608 (gnus-summary-beginning-of-article)
5609 (let* ((group (car gnus-article-current))
5610 (article (cdr gnus-article-current))
5611 (header (gnus-summary-article-header article))
5612 (author (mail-header-from header))
5613 (message-id (mail-header-id header))
5614 (date (mail-header-date header))
5615 (subject (gnus-summary-subject-string)))
5616 (setq cpltxt (concat author " on: " subject))
5617 (if (org-xor arg org-usenet-links-prefer-google)
5618 (setq link
5619 (concat
5620 cpltxt "\n "
5621 (format "http://groups.google.com/groups?as_umsgid=%s"
5622 (org-fixup-message-id-for-http message-id))))
5623 (setq link (concat cpltxt "\n"
5624 (org-make-link
5625 "gnus:" group
5626 "#" (number-to-string article)))))))
5627
5628 ((eq major-mode 'w3-mode)
5629 (setq cpltxt (url-view-url t)
5630 link (org-make-link cpltxt)))
5631 ((eq major-mode 'w3m-mode)
5632 (setq cpltxt w3m-current-url
5633 link (org-make-link cpltxt)))
5634
5635 ((buffer-file-name)
5636 ;; Just link to this file here.
5637 (setq cpltxt (concat "file:"
5638 (abbreviate-file-name (buffer-file-name))))
5639 ;; Add the line number?
5640 (if (org-xor org-line-numbers-in-file-links arg)
5641 (setq cpltxt
5642 (concat cpltxt
5643 ":" (int-to-string
5644 (+ (if (bolp) 1 0) (count-lines
5645 (point-min) (point)))))))
5646 (setq link (org-make-link cpltxt)))
5647
5648 ((interactive-p)
5649 (error "Cannot link to a buffer which is not visiting a file"))
5650
5651 (t (setq link nil)))
5652
5653 (if (and (interactive-p) link)
5654 (progn
5655 (setq org-stored-links
5656 (cons (cons (or cpltxt link) link) org-stored-links))
5657 (message "Stored: %s" (or cpltxt link)))
5658 link)))
5659
5660 (defun org-make-link (&rest strings)
5661 "Concatenate STRINGS, format resulting string with `org-link-format'."
5662 (format org-link-format (apply 'concat strings)))
5663
5664 (defun org-xor (a b)
5665 "Exclusive or."
5666 (if a (not b) b))
5667
5668 (defun org-get-header (header)
5669 "Find a header field in the current buffer."
5670 (save-excursion
5671 (goto-char (point-min))
5672 (let ((case-fold-search t) s)
5673 (cond
5674 ((eq header 'from)
5675 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5676 (setq s (match-string 1)))
5677 (while (string-match "\"" s)
5678 (setq s (replace-match "" t t s)))
5679 (if (string-match "[<(].*" s)
5680 (setq s (replace-match "" t t s))))
5681 ((eq header 'message-id)
5682 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5683 (setq s (match-string 1))))
5684 ((eq header 'subject)
5685 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5686 (setq s (match-string 1)))))
5687 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5688 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5689 s)))
5690
5691
5692 (defun org-fixup-message-id-for-http (s)
5693 "Replace special characters in a message id, so it can be used in an http query."
5694 (while (string-match "<" s)
5695 (setq s (replace-match "%3C" t t s)))
5696 (while (string-match ">" s)
5697 (setq s (replace-match "%3E" t t s)))
5698 (while (string-match "@" s)
5699 (setq s (replace-match "%40" t t s)))
5700 s)
5701
5702 (defun org-insert-link (&optional complete-file)
5703 "Insert a link. At the prompt, enter the link.
5704
5705 Completion can be used to select a link previously stored with
5706 `org-store-link'. When the empty string is entered (i.e. if you just
5707 press RET at the prompt), the link defaults to the most recently
5708 stored link. As SPC triggers completion in the minibuffer, you need to
5709 use M-SPC or C-q SPC to force the insertion of a space character.
5710
5711 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5712 selected using completion. The path to the file will be relative to
5713 the current directory if the file is in the current directory or a
5714 subdirectory. Otherwise, the link will be the absolute path as
5715 completed in the minibuffer (i.e. normally ~/path/to/file).
5716
5717 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5718 is in the current directory or below."
5719 (interactive "P")
5720 (let ((link (if complete-file
5721 (read-file-name "File: ")
5722 (completing-read
5723 "Link: " org-stored-links nil nil nil
5724 org-insert-link-history
5725 (or (car (car org-stored-links))))))
5726 linktxt matched)
5727 (if (or (not link) (equal link ""))
5728 (error "No links available"))
5729 (if complete-file
5730 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5731 (cond
5732 ((equal complete-file '(16))
5733 (insert
5734 (org-make-link
5735 "file:" (abbreviate-file-name (expand-file-name link)))))
5736 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5737 (expand-file-name link))
5738 (insert
5739 (org-make-link
5740 "file:" (match-string 1 (expand-file-name link)))))
5741 (t (insert (org-make-link "file:" link)))))
5742 (setq linktxt (cdr (assoc link org-stored-links)))
5743 (if (not org-keep-stored-link-after-insertion)
5744 (setq org-stored-links (delq (assoc link org-stored-links)
5745 org-stored-links)))
5746 (if (not linktxt) (setq link (org-make-link link)))
5747 (let ((lines (org-split-string (or linktxt link) "\n")))
5748 (insert (car lines))
5749 (setq matched (string-match org-link-regexp (car lines)))
5750 (setq lines (cdr lines))
5751 (while lines
5752 (insert "\n")
5753 (if (save-excursion
5754 (beginning-of-line 0)
5755 (looking-at "[ \t]+\\S-"))
5756 (indent-relative))
5757 (setq matched (or matched
5758 (string-match org-link-regexp (car lines))))
5759 (insert (car lines))
5760 (setq lines (cdr lines))))
5761 (unless matched
5762 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5763
5764 ;;; Hooks for remember.el
5765 ;;;###autoload
5766 (defun org-remember-annotation ()
5767 "Return a link to the current location as an annotation for remember.el.
5768 If you are using Org-mode files as target for data storage with
5769 remember.el, then the annotations should include a link compatible with the
5770 conventions in Org-mode. This function returns such a link."
5771 (org-store-link nil))
5772
5773 (defconst org-remember-help
5774 "Select a destination location for the note.
5775 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5776 RET at beg-of-buf -> Append to file as level 2 headline
5777 RET on headline -> Store as sublevel entry to current headline
5778 <left>/<right> -> before/after current headline, same headings level")
5779
5780 ;;;###autoload
5781 (defun org-remember-handler ()
5782 "Store stuff from remember.el into an org file.
5783 First prompts for an org file. If the user just presses return, the value
5784 of `org-default-notes-file' is used.
5785 Then the command offers the headings tree of the selected file in order to
5786 file the text at a specific location.
5787 You can either immediately press RET to get the note appended to the
5788 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5789 find a better place. Then press RET or <left> or <right> in insert the note.
5790
5791 Key Cursor position Note gets inserted
5792 -----------------------------------------------------------------------------
5793 RET buffer-start as level 2 heading at end of file
5794 RET on headline as sublevel of the heading at cursor
5795 RET no heading at cursor position, level taken from context.
5796 Or use prefix arg to specify level manually.
5797 <left> on headline as same level, before current heading
5798 <right> on headline as same level, after current heading
5799
5800 So the fastest way to store the note is to press RET RET to append it to
5801 the default file. This way your current train of thought is not
5802 interrupted, in accordance with the principles of remember.el. But with
5803 little extra effort, you can push it directly to the correct location.
5804
5805 Before being stored away, the function ensures that the text has a
5806 headline, i.e. a first line that starts with a \"*\". If not, a headline
5807 is constructed from the current date and some additional data.
5808
5809 If the variable `org-adapt-indentation' is non-nil, the entire text is
5810 also indented so that it starts in the same column as the headline
5811 \(i.e. after the stars).
5812
5813 See also the variable `org-reverse-note-order'."
5814 (catch 'quit
5815 (let* ((txt (buffer-substring (point-min) (point-max)))
5816 (fastp current-prefix-arg)
5817 (file (if fastp org-default-notes-file (org-get-org-file)))
5818 (visiting (find-buffer-visiting file))
5819 (org-startup-with-deadline-check nil)
5820 (org-startup-folded nil)
5821 spos level indent reversed)
5822 ;; Modify text so that it becomes a nice subtree which can be inserted
5823 ;; into an org tree.
5824 (let* ((lines (split-string txt "\n"))
5825 (first (car lines))
5826 (lines (cdr lines)))
5827 (if (string-match "^\\*+" first)
5828 ;; Is already a headline
5829 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5830 -1) ?\ ))
5831 ;; We need to add a headline: Use time and first buffer line
5832 (setq lines (cons first lines)
5833 first (concat "* " (current-time-string)
5834 " (" (remember-buffer-desc) ")")
5835 indent " "))
5836 (if org-adapt-indentation
5837 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5838 (setq txt (concat first "\n"
5839 (mapconcat 'identity lines "\n"))))
5840 ;; Find the file
5841 (if (not visiting)
5842 (find-file-noselect file))
5843 (with-current-buffer (get-file-buffer file)
5844 (setq reversed (org-notes-order-reversed-p))
5845 (save-excursion
5846 (save-restriction
5847 (widen)
5848 ;; Ask the User for a location
5849 (setq spos (if fastp 1 (org-get-location
5850 (current-buffer)
5851 org-remember-help)))
5852 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5853 ; not handle this note
5854 (goto-char spos)
5855 (cond ((bobp)
5856 ;; Put it at the start or end, as level 2
5857 (save-restriction
5858 (widen)
5859 (goto-char (if reversed (point-min) (point-max)))
5860 (if (not (bolp)) (newline))
5861 (org-paste-subtree (or current-prefix-arg 2) txt)))
5862 ((and (org-on-heading-p nil) (not current-prefix-arg))
5863 ;; Put it below this entry, at the beg/end of the subtree
5864 (org-back-to-heading)
5865 (setq level (outline-level))
5866 (if reversed
5867 (outline-end-of-heading)
5868 (outline-end-of-subtree))
5869 (if (not (bolp)) (newline))
5870 (beginning-of-line 1)
5871 (org-paste-subtree (1+ level) txt))
5872 (t
5873 ;; Put it right there, with automatic level determined by
5874 ;; org-paste-subtree or from prefix arg
5875 (org-paste-subtree current-prefix-arg txt)))
5876 (when remember-save-after-remembering
5877 (save-buffer)
5878 (if (not visiting) (kill-buffer (current-buffer)))))))))
5879 t) ;; return t to indicate that we took care of this note.
5880
5881 (defun org-get-org-file ()
5882 "Read a filename, with default directory `org-directory'."
5883 (let ((default (or org-default-notes-file remember-data-file)))
5884 (read-file-name (format "File name [%s]: " default)
5885 (file-name-as-directory org-directory)
5886 default)))
5887
5888 (defun org-notes-order-reversed-p ()
5889 "Check if the current file should receive notes in reversed order."
5890 (cond
5891 ((not org-reverse-note-order) nil)
5892 ((eq t org-reverse-note-order) t)
5893 ((not (listp org-reverse-note-order)) nil)
5894 (t (catch 'exit
5895 (let ((all org-reverse-note-order)
5896 entry)
5897 (while (setq entry (pop all))
5898 (if (string-match (car entry) (buffer-file-name))
5899 (throw 'exit (cdr entry))))
5900 nil)))))
5901
5902 ;;; Tables
5903
5904 ;; Watch out: Here we are talking about two different kind of tables.
5905 ;; Most of the code is for the tables created with the Org-mode table editor.
5906 ;; Sometimes, we talk about tables created and edited with the table.el
5907 ;; Emacs package. We call the former org-type tables, and the latter
5908 ;; table.el-type tables.
5909
5910
5911 (defun org-before-change-function (beg end)
5912 "Every change indicates that a table might need an update."
5913 (setq org-table-may-need-update t))
5914
5915 (defconst org-table-line-regexp "^[ \t]*|"
5916 "Detects an org-type table line.")
5917 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5918 "Detects an org-type table line.")
5919 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5920 "Detects a table line marked for automatic recalculation.")
5921 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5922 "Detects a table line marked for automatic recalculation.")
5923 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5924 "Detects a table line marked for automatic recalculation.")
5925 (defconst org-table-hline-regexp "^[ \t]*|-"
5926 "Detects an org-type table hline.")
5927 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5928 "Detects a table-type table hline.")
5929 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5930 "Detects an org-type or table-type table.")
5931 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5932 "Searching from within a table (any type) this finds the first line
5933 outside the table.")
5934 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5935 "Searching from within a table (any type) this finds the first line
5936 outside the table.")
5937
5938 (defun org-table-create-with-table.el ()
5939 "Use the table.el package to insert a new table.
5940 If there is already a table at point, convert between Org-mode tables
5941 and table.el tables."
5942 (interactive)
5943 (require 'table)
5944 (cond
5945 ((org-at-table.el-p)
5946 (if (y-or-n-p "Convert table to Org-mode table? ")
5947 (org-table-convert)))
5948 ((org-at-table-p)
5949 (if (y-or-n-p "Convert table to table.el table? ")
5950 (org-table-convert)))
5951 (t (call-interactively 'table-insert))))
5952
5953 (defun org-table-create (&optional size)
5954 "Query for a size and insert a table skeleton.
5955 SIZE is a string Columns x Rows like for example \"3x2\"."
5956 (interactive "P")
5957 (unless size
5958 (setq size (read-string
5959 (concat "Table size Columns x Rows [e.g. "
5960 org-table-default-size "]: ")
5961 "" nil org-table-default-size)))
5962
5963 (let* ((pos (point))
5964 (indent (make-string (current-column) ?\ ))
5965 (split (org-split-string size " *x *"))
5966 (rows (string-to-number (nth 1 split)))
5967 (columns (string-to-number (car split)))
5968 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5969 "\n")))
5970 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5971 (point-at-bol) (point)))
5972 (beginning-of-line 1)
5973 (newline))
5974 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5975 (dotimes (i rows) (insert line))
5976 (goto-char pos)
5977 (if (> rows 1)
5978 ;; Insert a hline after the first row.
5979 (progn
5980 (end-of-line 1)
5981 (insert "\n|-")
5982 (goto-char pos)))
5983 (org-table-align)))
5984
5985 (defun org-table-convert-region (beg0 end0 nspace)
5986 "Convert region to a table.
5987 The region goes from BEG0 to END0, but these borders will be moved
5988 slightly, to make sure a beginning of line in the first line is included.
5989 When NSPACE is non-nil, it indicates the minimum number of spaces that
5990 separate columns (default: just one space)"
5991 (let* ((beg (min beg0 end0))
5992 (end (max beg0 end0))
5993 (tabsep t)
5994 re)
5995 (goto-char beg)
5996 (beginning-of-line 1)
5997 (setq beg (move-marker (make-marker) (point)))
5998 (goto-char end)
5999 (if (bolp) (backward-char 1) (end-of-line 1))
6000 (setq end (move-marker (make-marker) (point)))
6001 ;; Lets see if this is tab-separated material. If every nonempty line
6002 ;; contains a tab, we will assume that it is tab-separated material
6003 (if nspace
6004 (setq tabsep nil)
6005 (goto-char beg)
6006 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6007 (if nspace (setq tabsep nil))
6008 (if tabsep
6009 (setq re "^\\|\t")
6010 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6011 (max 1 (prefix-numeric-value nspace)))))
6012 (goto-char beg)
6013 (while (re-search-forward re end t)
6014 (replace-match "|" t t))
6015 (goto-char beg)
6016 (insert " ")
6017 (org-table-align)))
6018
6019 (defun org-table-import (file arg)
6020 "Import FILE as a table.
6021 The file is assumed to be tab-separated. Such files can be produced by most
6022 spreadsheet and database applications. If no tabs (at least one per line)
6023 are found, lines will be split on whitespace into fields."
6024 (interactive "f\nP")
6025 (or (bolp) (newline))
6026 (let ((beg (point))
6027 (pm (point-max)))
6028 (insert-file-contents file)
6029 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6030
6031 (defun org-table-export ()
6032 "Export table as a tab-separated file.
6033 Such a file can be imported into a spreadsheet program like Excel."
6034 (interactive)
6035 (let* ((beg (org-table-begin))
6036 (end (org-table-end))
6037 (table (buffer-substring beg end))
6038 (file (read-file-name "Export table to: "))
6039 buf)
6040 (unless (or (not (file-exists-p file))
6041 (y-or-n-p (format "Overwrite file %s? " file)))
6042 (error "Abort"))
6043 (with-current-buffer (find-file-noselect file)
6044 (setq buf (current-buffer))
6045 (erase-buffer)
6046 (fundamental-mode)
6047 (insert table)
6048 (goto-char (point-min))
6049 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6050 (replace-match "" t t)
6051 (end-of-line 1))
6052 (goto-char (point-min))
6053 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6054 (replace-match "" t t)
6055 (goto-char (min (1+ (point)) (point-max))))
6056 (goto-char (point-min))
6057 (while (re-search-forward "^-[-+]*$" nil t)
6058 (replace-match "")
6059 (if (looking-at "\n")
6060 (delete-char 1)))
6061 (goto-char (point-min))
6062 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6063 (replace-match "\t" t t))
6064 (save-buffer))
6065 (kill-buffer buf)))
6066
6067 (defvar org-table-aligned-begin-marker (make-marker)
6068 "Marker at the beginning of the table last aligned.
6069 Used to check if cursor still is in that table, to minimize realignment.")
6070 (defvar org-table-aligned-end-marker (make-marker)
6071 "Marker at the end of the table last aligned.
6072 Used to check if cursor still is in that table, to minimize realignment.")
6073 (defvar org-table-last-alignment nil
6074 "List of flags for flushright alignment, from the last re-alignment.
6075 This is being used to correctly align a single field after TAB or RET.")
6076 ;; FIXME: The following is currently not used.
6077 (defvar org-table-last-column-widths nil
6078 "List of max width of fields in each column.
6079 This is being used to correctly align a single field after TAB or RET.")
6080
6081 (defvar org-last-recalc-line nil)
6082
6083 (defun org-table-align ()
6084 "Align the table at point by aligning all vertical bars."
6085 (interactive)
6086 ;; (message "align") (sit-for 2)
6087 (let* (
6088 ;; Limits of table
6089 (beg (org-table-begin))
6090 (end (org-table-end))
6091 ;; Current cursor position
6092 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6093 (colpos (org-table-current-column))
6094 (winstart (window-start))
6095 text lines (new "") lengths l typenums ty fields maxfields i
6096 column
6097 (indent "") cnt frac
6098 rfmt hfmt
6099 (spaces (if (org-in-invisibility-spec-p '(org-table))
6100 org-table-spaces-around-invisible-separators
6101 org-table-spaces-around-separators))
6102 (sp1 (car spaces))
6103 (sp2 (cdr spaces))
6104 (rfmt1 (concat
6105 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6106 (hfmt1 (concat
6107 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6108 emptystrings)
6109 (untabify beg end)
6110 ;; (message "Aligning table...")
6111 ;; Get the rows
6112 (setq lines (org-split-string
6113 (buffer-substring-no-properties beg end) "\n"))
6114 ;; Store the indentation of the first line
6115 (if (string-match "^ *" (car lines))
6116 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6117 ;; Mark the hlines
6118 (setq lines (mapcar (lambda (l)
6119 (if (string-match "^ *|-" l)
6120 nil
6121 (if (string-match "[ \t]+$" l)
6122 (substring l 0 (match-beginning 0))
6123 l)))
6124 lines))
6125 ;; Get the data fields
6126 (setq fields (mapcar
6127 (lambda (l)
6128 (org-split-string l " *| *"))
6129 (delq nil (copy-sequence lines))))
6130 ;; How many fields in the longest line?
6131 (condition-case nil
6132 (setq maxfields (apply 'max (mapcar 'length fields)))
6133 (error
6134 (kill-region beg end)
6135 (org-table-create org-table-default-size)
6136 (error "Empty table - created default table")))
6137 ;; A list of empty string to fill any short rows on output
6138 (setq emptystrings (make-list maxfields ""))
6139 ;; Get the maximum length of a field and the most common datatype
6140 ;; for each column
6141 (setq i -1)
6142 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6143 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6144 ;; maximum length
6145 (push (apply 'max 1 (mapcar 'length column)) lengths)
6146 ;; compute the fraction stepwise, ignoring empty fields
6147 (setq cnt 0 frac 0.0)
6148 (mapcar
6149 (lambda (x)
6150 (if (equal x "")
6151 nil
6152 (setq frac ( / (+ (* frac cnt)
6153 (if (string-match org-table-number-regexp x) 1 0))
6154 (setq cnt (1+ cnt))))))
6155 column)
6156 (push (>= frac org-table-number-fraction) typenums))
6157 (setq lengths (nreverse lengths)
6158 typenums (nreverse typenums))
6159 (setq org-table-last-alignment typenums
6160 org-table-last-column-widths lengths)
6161 ;; Compute the formats needed for output of the table
6162 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6163 (while (setq l (pop lengths))
6164 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6165 (setq rfmt (concat rfmt (format rfmt1 ty l))
6166 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6167 (setq rfmt (concat rfmt "\n")
6168 hfmt (concat (substring hfmt 0 -1) "|\n"))
6169 ;; Produce the new table
6170 ;;(while lines
6171 ;; (setq l (pop lines))
6172 ;; (if l
6173 ;; (setq new (concat new (apply 'format rfmt
6174 ;; (append (pop fields) emptystrings))))
6175 ;; (setq new (concat new hfmt))))
6176 (setq new (mapconcat
6177 (lambda (l)
6178 (if l (apply 'format rfmt
6179 (append (pop fields) emptystrings))
6180 hfmt))
6181 lines ""))
6182 ;; Replace the old one
6183 (delete-region beg end)
6184 (move-marker end nil)
6185 (move-marker org-table-aligned-begin-marker (point))
6186 (insert new)
6187 (move-marker org-table-aligned-end-marker (point))
6188 ;; Try to move to the old location (approximately)
6189 (goto-line linepos)
6190 (set-window-start (selected-window) winstart 'noforce)
6191 (org-table-goto-column colpos)
6192 (setq org-table-may-need-update nil)
6193 (if (org-in-invisibility-spec-p '(org-table))
6194 (org-table-add-invisible-to-vertical-lines))
6195 ))
6196
6197 (defun org-table-begin (&optional table-type)
6198 "Find the beginning of the table and return its position.
6199 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6200 (save-excursion
6201 (if (not (re-search-backward
6202 (if table-type org-table-any-border-regexp
6203 org-table-border-regexp)
6204 nil t))
6205 (error "Can't find beginning of table")
6206 (goto-char (match-beginning 0))
6207 (beginning-of-line 2)
6208 (point))))
6209
6210 (defun org-table-end (&optional table-type)
6211 "Find the end of the table and return its position.
6212 With argument TABLE-TYPE, go to the end of a table.el-type table."
6213 (save-excursion
6214 (if (not (re-search-forward
6215 (if table-type org-table-any-border-regexp
6216 org-table-border-regexp)
6217 nil t))
6218 (goto-char (point-max))
6219 (goto-char (match-beginning 0)))
6220 (point-marker)))
6221
6222 (defun org-table-justify-field-maybe (&optional new)
6223 "Justify the current field, text to left, number to right.
6224 Optional argument NEW may specify text to replace the current field content."
6225 (cond
6226 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6227 ((org-at-table-hline-p)
6228 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6229 ;; (setq org-table-may-need-update t)
6230 )
6231 ((and (not new)
6232 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6233 (current-buffer)))
6234 (< (point) org-table-aligned-begin-marker)
6235 (>= (point) org-table-aligned-end-marker)))
6236 ;; This is not the same table, force a full re-align
6237 (setq org-table-may-need-update t))
6238 (t ;; realign the current field, based on previous full realign
6239 (let* ((pos (point)) s
6240 (col (org-table-current-column))
6241 (num (nth (1- col) org-table-last-alignment))
6242 l f n o e)
6243 (when (> col 0)
6244 (skip-chars-backward "^|\n")
6245 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6246 (progn
6247 (setq s (match-string 1)
6248 o (match-string 0)
6249 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6250 e (not (= (match-beginning 2) (match-end 2))))
6251 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6252 l (if e "|" (setq org-table-may-need-update t) ""))
6253 n (format f s t t))
6254 (if new
6255 (if (<= (length new) l)
6256 (setq n (format f new t t)) ;; FIXME: why t t?????
6257 (setq n (concat new "|") org-table-may-need-update t)))
6258 (or (equal n o)
6259 (let (org-table-may-need-update)
6260 (replace-match n))))
6261 (setq org-table-may-need-update t))
6262 (goto-char pos))))))
6263
6264 (defun org-table-next-field ()
6265 "Go to the next field in the current table.
6266 Before doing so, re-align the table if necessary."
6267 (interactive)
6268 (org-table-maybe-eval-formula)
6269 (org-table-maybe-recalculate-line)
6270 (if (and org-table-automatic-realign
6271 org-table-may-need-update)
6272 (org-table-align))
6273 (if (org-at-table-hline-p)
6274 (end-of-line 1))
6275 (condition-case nil
6276 (progn
6277 (re-search-forward "|" (org-table-end))
6278 (if (looking-at "[ \t]*$")
6279 (re-search-forward "|" (org-table-end)))
6280 (if (looking-at "-")
6281 (progn
6282 (beginning-of-line 0)
6283 (org-table-insert-row 'below))
6284 (if (looking-at " ") (forward-char 1))))
6285 (error
6286 (org-table-insert-row 'below))))
6287
6288 (defun org-table-previous-field ()
6289 "Go to the previous field in the table.
6290 Before doing so, re-align the table if necessary."
6291 (interactive)
6292 (org-table-justify-field-maybe)
6293 (org-table-maybe-recalculate-line)
6294 (if (and org-table-automatic-realign
6295 org-table-may-need-update)
6296 (org-table-align))
6297 (if (org-at-table-hline-p)
6298 (end-of-line 1))
6299 (re-search-backward "|" (org-table-begin))
6300 (re-search-backward "|" (org-table-begin))
6301 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6302 (re-search-backward "|" (org-table-begin)))
6303 (if (looking-at "| ?")
6304 (goto-char (match-end 0))))
6305
6306 (defun org-table-next-row ()
6307 "Go to the next row (same column) in the current table.
6308 Before doing so, re-align the table if necessary."
6309 (interactive)
6310 (org-table-maybe-eval-formula)
6311 (org-table-maybe-recalculate-line)
6312 (if (or (looking-at "[ \t]*$")
6313 (save-excursion (skip-chars-backward " \t") (bolp)))
6314 (newline)
6315 (if (and org-table-automatic-realign
6316 org-table-may-need-update)
6317 (org-table-align))
6318 (let ((col (org-table-current-column)))
6319 (beginning-of-line 2)
6320 (if (or (not (org-at-table-p))
6321 (org-at-table-hline-p))
6322 (progn
6323 (beginning-of-line 0)
6324 (org-table-insert-row 'below)))
6325 (org-table-goto-column col)
6326 (skip-chars-backward "^|\n\r")
6327 (if (looking-at " ") (forward-char 1)))))
6328
6329 (defun org-table-copy-down (n)
6330 "Copy a field down in the current column.
6331 If the field at the cursor is empty, copy into it the content of the nearest
6332 non-empty field above. With argument N, use the Nth non-empty field.
6333 If the current field is not empty, it is copied down to the next row, and
6334 the cursor is moved with it. Therefore, repeating this command causes the
6335 column to be filled row-by-row.
6336 If the variable `org-table-copy-increment' is non-nil and the field is an
6337 integer, it will be incremented while copying."
6338 (interactive "p")
6339 (let* ((colpos (org-table-current-column))
6340 (field (org-table-get-field))
6341 (non-empty (string-match "[^ \t]" field))
6342 (beg (org-table-begin))
6343 txt)
6344 (org-table-check-inside-data-field)
6345 (if non-empty
6346 (progn
6347 (setq txt (org-trim field))
6348 (org-table-next-row)
6349 (org-table-blank-field))
6350 (save-excursion
6351 (setq txt
6352 (catch 'exit
6353 (while (progn (beginning-of-line 1)
6354 (re-search-backward org-table-dataline-regexp
6355 beg t))
6356 (org-table-goto-column colpos t)
6357 (if (and (looking-at
6358 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6359 (= (setq n (1- n)) 0))
6360 (throw 'exit (match-string 1))))))))
6361 (if txt
6362 (progn
6363 (if (and org-table-copy-increment
6364 (string-match "^[0-9]+$" txt))
6365 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6366 (insert txt)
6367 (org-table-maybe-recalculate-line)
6368 (org-table-align))
6369 (error "No non-empty field found"))))
6370
6371 (defun org-table-check-inside-data-field ()
6372 "Is point inside a table data field?
6373 I.e. not on a hline or before the first or after the last column?
6374 This actually throws an error, so it aborts the current command."
6375 (if (or (not (org-at-table-p))
6376 (= (org-table-current-column) 0)
6377 (org-at-table-hline-p)
6378 (looking-at "[ \t]*$"))
6379 (error "Not in table data field")))
6380
6381 (defvar org-table-clip nil
6382 "Clipboard for table regions.")
6383
6384 (defun org-table-blank-field ()
6385 "Blank the current table field or active region."
6386 (interactive)
6387 (org-table-check-inside-data-field)
6388 (if (and (interactive-p) (org-region-active-p))
6389 (let (org-table-clip)
6390 (org-table-cut-region (region-beginning) (region-end)))
6391 (skip-chars-backward "^|")
6392 (backward-char 1)
6393 (if (looking-at "|[^|\n]+")
6394 (let* ((pos (match-beginning 0))
6395 (match (match-string 0))
6396 (len (length match)))
6397 (replace-match (concat "|" (make-string (1- len) ?\ )))
6398 (goto-char (+ 2 pos))
6399 (substring match 1)))))
6400
6401 (defun org-table-get-field (&optional n replace)
6402 "Return the value of the field in column N of current row.
6403 N defaults to current field.
6404 If REPLACE is a string, replace field with this value. The return value
6405 is always the old value."
6406 (and n (org-table-goto-column n))
6407 (skip-chars-backward "^|\n")
6408 (backward-char 1)
6409 (if (looking-at "|[^|\r\n]*")
6410 (let* ((pos (match-beginning 0))
6411 (val (buffer-substring (1+ pos) (match-end 0))))
6412 (if replace
6413 (replace-match (concat "|" replace)))
6414 (goto-char (min (point-at-eol) (+ 2 pos)))
6415 val)
6416 (forward-char 1) ""))
6417
6418 (defun org-table-current-column ()
6419 "Find out which column we are in.
6420 When called interactively, column is also displayed in echo area."
6421 (interactive)
6422 (if (interactive-p) (org-table-check-inside-data-field))
6423 (save-excursion
6424 (let ((cnt 0) (pos (point)))
6425 (beginning-of-line 1)
6426 (while (search-forward "|" pos t)
6427 (setq cnt (1+ cnt)))
6428 (if (interactive-p) (message "This is table column %d" cnt))
6429 cnt)))
6430
6431 (defun org-table-goto-column (n &optional on-delim force)
6432 "Move the cursor to the Nth column in the current table line.
6433 With optional argument ON-DELIM, stop with point before the left delimiter
6434 of the field.
6435 If there are less than N fields, just go to after the last delimiter.
6436 However, when FORCE is non-nil, create new columns if necessary."
6437 (let ((pos (point-at-eol)))
6438 (beginning-of-line 1)
6439 (when (> n 0)
6440 (while (and (> (setq n (1- n)) -1)
6441 (or (search-forward "|" pos t)
6442 (and force
6443 (progn (end-of-line 1)
6444 (skip-chars-backward "^|")
6445 (insert " | "))))))
6446 ; (backward-char 2) t)))))
6447 (when (and force (not (looking-at ".*|")))
6448 (save-excursion (end-of-line 1) (insert " | ")))
6449 (if on-delim
6450 (backward-char 1)
6451 (if (looking-at " ") (forward-char 1))))))
6452
6453 (defun org-at-table-p (&optional table-type)
6454 "Return t if the cursor is inside an org-type table.
6455 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6456 (if org-enable-table-editor
6457 (save-excursion
6458 (beginning-of-line 1)
6459 (looking-at (if table-type org-table-any-line-regexp
6460 org-table-line-regexp)))
6461 nil))
6462
6463 (defun org-table-recognize-table.el ()
6464 "If there is a table.el table nearby, recognize it and move into it."
6465 (if org-table-tab-recognizes-table.el
6466 (if (org-at-table.el-p)
6467 (progn
6468 (beginning-of-line 1)
6469 (if (looking-at org-table-dataline-regexp)
6470 nil
6471 (if (looking-at org-table1-hline-regexp)
6472 (progn
6473 (beginning-of-line 2)
6474 (if (looking-at org-table-any-border-regexp)
6475 (beginning-of-line -1)))))
6476 (if (re-search-forward "|" (org-table-end t) t)
6477 (progn
6478 (require 'table)
6479 (if (table--at-cell-p (point))
6480 t
6481 (message "recognizing table.el table...")
6482 (table-recognize-table)
6483 (message "recognizing table.el table...done")))
6484 (error "This should not happen..."))
6485 t)
6486 nil)
6487 nil))
6488
6489 (defun org-at-table.el-p ()
6490 "Return t if the cursor is inside a table.el-type table."
6491 (save-excursion
6492 (if (org-at-table-p 'any)
6493 (progn
6494 (goto-char (org-table-begin 'any))
6495 (looking-at org-table1-hline-regexp))
6496 nil)))
6497
6498 (defun org-at-table-hline-p ()
6499 "Return t if the cursor is inside a hline in a table."
6500 (if org-enable-table-editor
6501 (save-excursion
6502 (beginning-of-line 1)
6503 (looking-at org-table-hline-regexp))
6504 nil))
6505
6506 (defun org-table-insert-column ()
6507 "Insert a new column into the table."
6508 (interactive)
6509 (if (not (org-at-table-p))
6510 (error "Not at a table"))
6511 (org-table-find-dataline)
6512 (let* ((col (max 1 (org-table-current-column)))
6513 (beg (org-table-begin))
6514 (end (org-table-end))
6515 ;; Current cursor position
6516 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6517 (colpos col))
6518 (goto-char beg)
6519 (while (< (point) end)
6520 (if (org-at-table-hline-p)
6521 nil
6522 (org-table-goto-column col t)
6523 (insert "| "))
6524 (beginning-of-line 2))
6525 (move-marker end nil)
6526 (goto-line linepos)
6527 (org-table-goto-column colpos)
6528 (org-table-align)
6529 (org-table-modify-formulas 'insert col)))
6530
6531 (defun org-table-find-dataline ()
6532 "Find a dataline in the current table, which is needed for column commands."
6533 (if (and (org-at-table-p)
6534 (not (org-at-table-hline-p)))
6535 t
6536 (let ((col (current-column))
6537 (end (org-table-end)))
6538 (move-to-column col)
6539 (while (and (< (point) end)
6540 (or (not (= (current-column) col))
6541 (org-at-table-hline-p)))
6542 (beginning-of-line 2)
6543 (move-to-column col))
6544 (if (and (org-at-table-p)
6545 (not (org-at-table-hline-p)))
6546 t
6547 (error
6548 "Please position cursor in a data line for column operations")))))
6549
6550 (defun org-table-delete-column ()
6551 "Delete a column into the table."
6552 (interactive)
6553 (if (not (org-at-table-p))
6554 (error "Not at a table"))
6555 (org-table-find-dataline)
6556 (org-table-check-inside-data-field)
6557 (let* ((col (org-table-current-column))
6558 (beg (org-table-begin))
6559 (end (org-table-end))
6560 ;; Current cursor position
6561 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6562 (colpos col))
6563 (goto-char beg)
6564 (while (< (point) end)
6565 (if (org-at-table-hline-p)
6566 nil
6567 (org-table-goto-column col t)
6568 (and (looking-at "|[^|\n]+|")
6569 (replace-match "|")))
6570 (beginning-of-line 2))
6571 (move-marker end nil)
6572 (goto-line linepos)
6573 (org-table-goto-column colpos)
6574 (org-table-align)
6575 (org-table-modify-formulas 'remove col)))
6576
6577 (defun org-table-move-column-right ()
6578 "Move column to the right."
6579 (interactive)
6580 (org-table-move-column nil))
6581 (defun org-table-move-column-left ()
6582 "Move column to the left."
6583 (interactive)
6584 (org-table-move-column 'left))
6585
6586 (defun org-table-move-column (&optional left)
6587 "Move the current column to the right. With arg LEFT, move to the left."
6588 (interactive "P")
6589 (if (not (org-at-table-p))
6590 (error "Not at a table"))
6591 (org-table-find-dataline)
6592 (org-table-check-inside-data-field)
6593 (let* ((col (org-table-current-column))
6594 (col1 (if left (1- col) col))
6595 (beg (org-table-begin))
6596 (end (org-table-end))
6597 ;; Current cursor position
6598 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6599 (colpos (if left (1- col) (1+ col))))
6600 (if (and left (= col 1))
6601 (error "Cannot move column further left"))
6602 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6603 (error "Cannot move column further right"))
6604 (goto-char beg)
6605 (while (< (point) end)
6606 (if (org-at-table-hline-p)
6607 nil
6608 (org-table-goto-column col1 t)
6609 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6610 (replace-match "|\\2|\\1|")))
6611 (beginning-of-line 2))
6612 (move-marker end nil)
6613 (goto-line linepos)
6614 (org-table-goto-column colpos)
6615 (org-table-align)
6616 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6617
6618 (defun org-table-move-row-down ()
6619 "move table row down."
6620 (interactive)
6621 (org-table-move-row nil))
6622 (defun org-table-move-row-up ()
6623 "move table row up."
6624 (interactive)
6625 (org-table-move-row 'up))
6626
6627 (defun org-table-move-row (&optional up)
6628 "Move the current table line down. With arg UP, move it up."
6629 (interactive "P")
6630 (let ((col (current-column))
6631 (pos (point))
6632 (tonew (if up 0 2))
6633 txt)
6634 (beginning-of-line tonew)
6635 (if (not (org-at-table-p))
6636 (progn
6637 (goto-char pos)
6638 (error "Cannot move row further")))
6639 (goto-char pos)
6640 (beginning-of-line 1)
6641 (setq pos (point))
6642 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6643 (delete-region (point) (1+ (point-at-eol)))
6644 (beginning-of-line tonew)
6645 (insert txt)
6646 (beginning-of-line 0)
6647 (move-to-column col)))
6648
6649 (defun org-table-insert-row (&optional arg)
6650 "Insert a new row above the current line into the table.
6651 With prefix ARG, insert below the current line."
6652 (interactive "P")
6653 (if (not (org-at-table-p))
6654 (error "Not at a table"))
6655 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6656 new)
6657 (if (string-match "^[ \t]*|-" line)
6658 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6659 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6660 ;; Fix the first field if necessary
6661 (setq new (concat new))
6662 (if (string-match "^[ \t]*| *[#$] *|" line)
6663 (setq new (replace-match (match-string 0 line) t t new)))
6664 (beginning-of-line (if arg 2 1))
6665 (let (org-table-may-need-update)
6666 (insert-before-markers new)
6667 (insert-before-markers "\n"))
6668 (beginning-of-line 0)
6669 (re-search-forward "| ?" (point-at-eol) t)
6670 (and org-table-may-need-update (org-table-align))))
6671
6672 (defun org-table-insert-hline (&optional arg)
6673 "Insert a horizontal-line below the current line into the table.
6674 With prefix ARG, insert above the current line."
6675 (interactive "P")
6676 (if (not (org-at-table-p))
6677 (error "Not at a table"))
6678 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6679 (col (current-column))
6680 start)
6681 (if (string-match "^[ \t]*|-" line)
6682 (setq line
6683 (mapcar (lambda (x) (if (member x '(?| ?+))
6684 (prog1 (if start ?+ ?|) (setq start t))
6685 (if start ?- ?\ )))
6686 line))
6687 (setq line
6688 (mapcar (lambda (x) (if (equal x ?|)
6689 (prog1 (if start ?+ ?|) (setq start t))
6690 (if start ?- ?\ )))
6691 line)))
6692 (beginning-of-line (if arg 1 2))
6693 (apply 'insert line)
6694 (if (equal (char-before (point)) ?+)
6695 (progn (backward-delete-char 1) (insert "|")))
6696 (insert "\n")
6697 (beginning-of-line 0)
6698 (move-to-column col)))
6699
6700 (defun org-table-kill-row ()
6701 "Delete the current row or horizontal line from the table."
6702 (interactive)
6703 (if (not (org-at-table-p))
6704 (error "Not at a table"))
6705 (let ((col (current-column)))
6706 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6707 (if (not (org-at-table-p)) (beginning-of-line 0))
6708 (move-to-column col)))
6709
6710
6711 (defun org-table-cut-region (beg end)
6712 "Copy region in table to the clipboard and blank all relevant fields."
6713 (interactive "r")
6714 (org-table-copy-region beg end 'cut))
6715
6716 (defun org-table-copy-region (beg end &optional cut)
6717 "Copy rectangular region in table to clipboard.
6718 A special clipboard is used which can only be accessed
6719 with `org-table-paste-rectangle'"
6720 (interactive "rP")
6721 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6722 region cols
6723 (rpl (if cut " " nil)))
6724 (goto-char beg)
6725 (org-table-check-inside-data-field)
6726 (setq l01 (count-lines (point-min) (point))
6727 c01 (org-table-current-column))
6728 (goto-char end)
6729 (org-table-check-inside-data-field)
6730 (setq l02 (count-lines (point-min) (point))
6731 c02 (org-table-current-column))
6732 (setq l1 (min l01 l02) l2 (max l01 l02)
6733 c1 (min c01 c02) c2 (max c01 c02))
6734 (catch 'exit
6735 (while t
6736 (catch 'nextline
6737 (if (> l1 l2) (throw 'exit t))
6738 (goto-line l1)
6739 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6740 (setq cols nil ic1 c1 ic2 c2)
6741 (while (< ic1 (1+ ic2))
6742 (push (org-table-get-field ic1 rpl) cols)
6743 (setq ic1 (1+ ic1)))
6744 (push (nreverse cols) region)
6745 (setq l1 (1+ l1)))))
6746 (setq org-table-clip (nreverse region))
6747 (if cut (org-table-align))
6748 org-table-clip))
6749
6750 (defun org-table-paste-rectangle ()
6751 "Paste a rectangular region into a table.
6752 The upper right corner ends up in the current field. All involved fields
6753 will be overwritten. If the rectangle does not fit into the present table,
6754 the table is enlarged as needed. The process ignores horizontal separator
6755 lines."
6756 (interactive)
6757 (unless (and org-table-clip (listp org-table-clip))
6758 (error "First cut/copy a region to paste!"))
6759 (org-table-check-inside-data-field)
6760 (let* ((clip org-table-clip)
6761 (line (count-lines (point-min) (point)))
6762 (col (org-table-current-column))
6763 (org-enable-table-editor t)
6764 (org-table-automatic-realign nil)
6765 c cols field)
6766 (while (setq cols (pop clip))
6767 (while (org-at-table-hline-p) (beginning-of-line 2))
6768 (if (not (org-at-table-p))
6769 (progn (end-of-line 0) (org-table-next-field)))
6770 (setq c col)
6771 (while (setq field (pop cols))
6772 (org-table-goto-column c nil 'force)
6773 (org-table-get-field nil field)
6774 (setq c (1+ c)))
6775 (beginning-of-line 2))
6776 (goto-line line)
6777 (org-table-goto-column col)
6778 (org-table-align)))
6779
6780 (defun org-table-convert ()
6781 "Convert from `org-mode' table to table.el and back.
6782 Obviously, this only works within limits. When an Org-mode table is
6783 converted to table.el, all horizontal separator lines get lost, because
6784 table.el uses these as cell boundaries and has no notion of horizontal lines.
6785 A table.el table can be converted to an Org-mode table only if it does not
6786 do row or column spanning. Multiline cells will become multiple cells.
6787 Beware, Org-mode does not test if the table can be successfully converted - it
6788 blindly applies a recipe that works for simple tables."
6789 (interactive)
6790 (require 'table)
6791 (if (org-at-table.el-p)
6792 ;; convert to Org-mode table
6793 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6794 (end (move-marker (make-marker) (org-table-end t))))
6795 (table-unrecognize-region beg end)
6796 (goto-char beg)
6797 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6798 (replace-match ""))
6799 (goto-char beg))
6800 (if (org-at-table-p)
6801 ;; convert to table.el table
6802 (let ((beg (move-marker (make-marker) (org-table-begin)))
6803 (end (move-marker (make-marker) (org-table-end))))
6804 ;; first, get rid of all horizontal lines
6805 (goto-char beg)
6806 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6807 (replace-match ""))
6808 ;; insert a hline before first
6809 (goto-char beg)
6810 (org-table-insert-hline 'above)
6811 ;; insert a hline after each line
6812 (while (progn (beginning-of-line 2) (< (point) end))
6813 (org-table-insert-hline))
6814 (goto-char beg)
6815 (setq end (move-marker end (org-table-end)))
6816 ;; replace "+" at beginning and ending of hlines
6817 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6818 (replace-match "\\1+-"))
6819 (goto-char beg)
6820 (while (re-search-forward "-|[ \t]*$" end t)
6821 (replace-match "-+"))
6822 (goto-char beg)))))
6823
6824 (defun org-table-wrap-region (arg)
6825 "Wrap several fields in a column like a paragraph.
6826 This is useful if you'd like to spread the contents of a field over several
6827 lines, in order to keep the table compact.
6828
6829 If there is an active region, and both point and mark are in the same column,
6830 the text in the column is wrapped to minimum width for the given number of
6831 lines. Generally, this makes the table more compact. A prefix ARG may be
6832 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6833 formats the selected text to two lines. If the region was longer than 2
6834 lines, the remaining lines remain empty. A negative prefix argument reduces
6835 the current number of lines by that amount. The wrapped text is pasted back
6836 into the table. If you formatted it to more lines than it was before, fields
6837 further down in the table get overwritten - so you might need to make space in
6838 the table first.
6839
6840 If there is no region, the current field is split at the cursor position and
6841 the text fragment to the right of the cursor is prepended to the field one
6842 line down.
6843
6844 If there is no region, but you specify a prefix ARG, the current field gets
6845 blank, and the content is appended to the field above."
6846 (interactive "P")
6847 (org-table-check-inside-data-field)
6848 (if (org-region-active-p)
6849 ;; There is a region: fill as a paragraph
6850 (let ((beg (region-beginning))
6851 nlines)
6852 (org-table-cut-region (region-beginning) (region-end))
6853 (if (> (length (car org-table-clip)) 1)
6854 (error "Region must be limited to single column"))
6855 (setq nlines (if arg
6856 (if (< arg 1)
6857 (+ (length org-table-clip) arg)
6858 arg)
6859 (length org-table-clip)))
6860 (setq org-table-clip
6861 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6862 nil nlines)))
6863 (goto-char beg)
6864 (org-table-paste-rectangle))
6865 ;; No region, split the current field at point
6866 (if arg
6867 ;; combine with field above
6868 (let ((s (org-table-blank-field))
6869 (col (org-table-current-column)))
6870 (beginning-of-line 0)
6871 (while (org-at-table-hline-p) (beginning-of-line 0))
6872 (org-table-goto-column col)
6873 (skip-chars-forward "^|")
6874 (skip-chars-backward " ")
6875 (insert " " (org-trim s))
6876 (org-table-align))
6877 ;; split field
6878 (when (looking-at "\\([^|]+\\)+|")
6879 (let ((s (match-string 1)))
6880 (replace-match " |")
6881 (goto-char (match-beginning 0))
6882 (org-table-next-row)
6883 (insert (org-trim s) " ")
6884 (org-table-align))))))
6885
6886 (defun org-trim (s)
6887 "Remove whitespace at beginning and end of string."
6888 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6889 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6890 s)
6891
6892 (defun org-wrap (string &optional width lines)
6893 "Wrap string to either a number of lines, or a width in characters.
6894 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6895 that costs. If there is a word longer than WIDTH, the text is actually
6896 wrapped to the length of that word.
6897 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6898 many lines, whatever width that takes.
6899 The return value is a list of lines, without newlines at the end."
6900 (let* ((words (org-split-string string "[ \t\n]+"))
6901 (maxword (apply 'max (mapcar 'length words)))
6902 w ll)
6903 (cond (width
6904 (org-do-wrap words (max maxword width)))
6905 (lines
6906 (setq w maxword)
6907 (setq ll (org-do-wrap words maxword))
6908 (if (<= (length ll) lines)
6909 ll
6910 (setq ll words)
6911 (while (> (length ll) lines)
6912 (setq w (1+ w))
6913 (setq ll (org-do-wrap words w)))
6914 ll))
6915 (t (error "Cannot wrap this")))))
6916
6917
6918 (defun org-do-wrap (words width)
6919 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6920 (let (lines line)
6921 (while words
6922 (setq line (pop words))
6923 (while (and words (< (+ (length line) (length (car words))) width))
6924 (setq line (concat line " " (pop words))))
6925 (setq lines (push line lines)))
6926 (nreverse lines)))
6927
6928 ;; FIXME: I think I can make this more efficient
6929 (defun org-split-string (string &optional separators)
6930 "Splits STRING into substrings at SEPARATORS.
6931 No empty strings are returned if there are matches at the beginning
6932 and end of string."
6933 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6934 (start 0)
6935 notfirst
6936 (list nil))
6937 (while (and (string-match rexp string
6938 (if (and notfirst
6939 (= start (match-beginning 0))
6940 (< start (length string)))
6941 (1+ start) start))
6942 (< (match-beginning 0) (length string)))
6943 (setq notfirst t)
6944 (or (eq (match-beginning 0) 0)
6945 (and (eq (match-beginning 0) (match-end 0))
6946 (eq (match-beginning 0) start))
6947 (setq list
6948 (cons (substring string start (match-beginning 0))
6949 list)))
6950 (setq start (match-end 0)))
6951 (or (eq start (length string))
6952 (setq list
6953 (cons (substring string start)
6954 list)))
6955 (nreverse list)))
6956
6957 (defun org-table-add-invisible-to-vertical-lines ()
6958 "Add an `invisible' property to vertical lines of current table."
6959 (interactive)
6960 (let* ((beg (org-table-begin))
6961 (end (org-table-end))
6962 (end1))
6963 (save-excursion
6964 (goto-char beg)
6965 (while (< (point) end)
6966 (setq end1 (point-at-eol))
6967 (if (looking-at org-table-dataline-regexp)
6968 (while (re-search-forward "|" end1 t)
6969 (add-text-properties (1- (point)) (point)
6970 '(invisible org-table)))
6971 (while (re-search-forward "[+|]" end1 t)
6972 (add-text-properties (1- (point)) (point)
6973 '(invisible org-table))))
6974 (beginning-of-line 2)))))
6975
6976 (defun org-table-toggle-vline-visibility (&optional arg)
6977 "Toggle the visibility of table vertical lines.
6978 The effect is immediate and on all tables in the file.
6979 With prefix ARG, make lines invisible when ARG is positive, make lines
6980 visible when ARG is not positive"
6981 (interactive "P")
6982 (let ((action (cond
6983 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6984 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6985 (t (if (org-in-invisibility-spec-p '(org-table))
6986 'off
6987 'on)))))
6988 (if (eq action 'off)
6989 (progn
6990 (org-remove-from-invisibility-spec '(org-table))
6991 (org-table-map-tables 'org-table-align)
6992 (message "Vertical table lines visible")
6993 (if (org-at-table-p)
6994 (org-table-align)))
6995 (org-add-to-invisibility-spec '(org-table))
6996 (org-table-map-tables 'org-table-align)
6997 (message "Vertical table lines invisible"))
6998 (redraw-frame (selected-frame))))
6999
7000 (defun org-table-map-tables (function)
7001 "Apply FUNCTION to the start of all tables in the buffer."
7002 (save-excursion
7003 (save-restriction
7004 (widen)
7005 (goto-char (point-min))
7006 (while (re-search-forward org-table-any-line-regexp nil t)
7007 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7008 (beginning-of-line 1)
7009 (if (looking-at org-table-line-regexp)
7010 (save-excursion (funcall function)))
7011 (re-search-forward org-table-any-border-regexp nil 1)))))
7012
7013 (defun org-table-sum (&optional beg end nlast)
7014 "Sum numbers in region of current table column.
7015 The result will be displayed in the echo area, and will be available
7016 as kill to be inserted with \\[yank].
7017
7018 If there is an active region, it is interpreted as a rectangle and all
7019 numbers in that rectangle will be summed. If there is no active
7020 region and point is located in a table column, sum all numbers in that
7021 column.
7022
7023 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7024 numbers are assumed to be times as well (in decimal hours) and the
7025 numbers are added as such.
7026
7027 If NLAST is a number, only the NLAST fields will actually be summed."
7028 (interactive)
7029 (save-excursion
7030 (let (col (timecnt 0) diff h m s org-table-clip)
7031 (cond
7032 ((and beg end)) ; beg and end given explicitly
7033 ((org-region-active-p)
7034 (setq beg (region-beginning) end (region-end)))
7035 (t
7036 (setq col (org-table-current-column))
7037 (goto-char (org-table-begin))
7038 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7039 (error "No table data"))
7040 (org-table-goto-column col)
7041 ;not needed? (skip-chars-backward "^|")
7042 (setq beg (point))
7043 (goto-char (org-table-end))
7044 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7045 (error "No table data"))
7046 (org-table-goto-column col)
7047 ;not needed? (skip-chars-forward "^|")
7048 (setq end (point))))
7049 (let* ((items (apply 'append (org-table-copy-region beg end)))
7050 (items1 (cond ((not nlast) items)
7051 ((>= nlast (length items)) items)
7052 (t (setq items (reverse items))
7053 (setcdr (nthcdr (1- nlast) items) nil)
7054 (nreverse items))))
7055 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7056 items1)))
7057 (res (apply '+ numbers))
7058 (sres (if (= timecnt 0)
7059 (format "%g" res)
7060 (setq diff (* 3600 res)
7061 h (floor (/ diff 3600)) diff (mod diff 3600)
7062 m (floor (/ diff 60)) diff (mod diff 60)
7063 s diff)
7064 (format "%d:%02d:%02d" h m s))))
7065 (kill-new sres)
7066 (if (interactive-p)
7067 (message "%s"
7068 (substitute-command-keys
7069 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7070 (length numbers) sres))))
7071 sres))))
7072
7073 (defun org-table-get-number-for-summing (s)
7074 (let (n)
7075 (if (string-match "^ *|? *" s)
7076 (setq s (replace-match "" nil nil s)))
7077 (if (string-match " *|? *$" s)
7078 (setq s (replace-match "" nil nil s)))
7079 (setq n (string-to-number s))
7080 (cond
7081 ((and (string-match "0" s)
7082 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7083 ((string-match "\\`[ \t]+\\'" s) nil)
7084 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7085 (let ((h (string-to-number (or (match-string 1 s) "0")))
7086 (m (string-to-number (or (match-string 2 s) "0")))
7087 (s (string-to-number (or (match-string 4 s) "0"))))
7088 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7089 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7090 ((equal n 0) nil)
7091 (t n))))
7092
7093 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7094 "Get a calc vector from a column, accorting to desctiptor DESC.
7095 Optional arguments TBEG and COL can give the beginning of the table and
7096 the current column, to avoid unnecessary parsing."
7097 (save-excursion
7098 (or tbeg (setq tbeg (org-table-begin)))
7099 (or col (setq col (org-table-current-column)))
7100 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7101 (cond
7102 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7103 (setq n1 (- (match-end 1) (match-beginning 1)))
7104 (if (match-beginning 3)
7105 (setq n2 (- (match-end 2) (match-beginning 3))))
7106 (setq n (if n2 (max n1 n2) n1))
7107 (setq n1 (if n2 (min n1 n2)))
7108 (setq nn n)
7109 (while (and (> nn 0)
7110 (re-search-backward org-table-hline-regexp tbeg t))
7111 (push (org-current-line) hline-list)
7112 (setq nn (1- nn)))
7113 (setq hline-list (nreverse hline-list))
7114 (goto-line (nth (1- n) hline-list))
7115 (when (re-search-forward org-table-dataline-regexp)
7116 (org-table-goto-column col)
7117 (setq beg (point)))
7118 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7119 (when (re-search-backward org-table-dataline-regexp)
7120 (org-table-goto-column col)
7121 (setq end (point)))
7122 (setq l (apply 'append (org-table-copy-region beg end)))
7123 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7124 (if (equal x "") "0" x))
7125 l ",") "]"))
7126 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7127 (setq n1 (string-to-number (match-string 1 desc))
7128 n2 (string-to-number (match-string 2 desc)))
7129 (beginning-of-line 1)
7130 (save-excursion
7131 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7132 (org-table-goto-column col)
7133 (setq beg (point))))
7134 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7135 (org-table-goto-column col)
7136 (setq end (point)))
7137 (setq l (apply 'append (org-table-copy-region beg end)))
7138 (concat "[" (mapconcat
7139 (lambda (x) (setq x (org-trim x))
7140 (if (equal x "") "0" x))
7141 l ",") "]"))
7142 ((string-match "\\([0-9]+\\)" desc)
7143 (beginning-of-line 1)
7144 (when (re-search-backward org-table-dataline-regexp tbeg t
7145 (string-to-number (match-string 0 desc)))
7146 (org-table-goto-column col)
7147 (org-trim (org-table-get-field))))))))
7148
7149 (defvar org-table-formula-history nil)
7150
7151 (defvar org-table-column-names nil
7152 "Alist with column names, derived from the `!' line.")
7153 (defvar org-table-column-name-regexp nil
7154 "Regular expression matching the current column names.")
7155 (defvar org-table-local-parameters nil
7156 "Alist with parameter names, derived from the `$' line.")
7157 (defvar org-table-named-field-locations nil
7158 "Alist with locations of named fields.")
7159
7160 (defun org-table-get-formula (&optional equation named)
7161 "Read a formula from the minibuffer, offer stored formula as default."
7162 (let* ((name (car (rassoc (list (org-current-line)
7163 (org-table-current-column))
7164 org-table-named-field-locations)))
7165 (scol (if named
7166 (if name name
7167 (error "Not in a named field"))
7168 (int-to-string (org-table-current-column))))
7169 (dummy (and name (not named)
7170 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7171 (error "Abort")))
7172 (org-table-may-need-update nil)
7173 (stored-list (org-table-get-stored-formulas))
7174 (stored (cdr (assoc scol stored-list)))
7175 (eq (cond
7176 ((and stored equation (string-match "^ *=? *$" equation))
7177 stored)
7178 ((stringp equation)
7179 equation)
7180 (t (read-string
7181 (format "%s formula $%s=" (if named "Field" "Column") scol)
7182 (or stored "") 'org-table-formula-history
7183 ;stored
7184 ))))
7185 mustsave)
7186 (when (not (string-match "\\S-" eq))
7187 ;; remove formula
7188 (setq stored-list (delq (assoc scol stored-list) stored-list))
7189 (org-table-store-formulas stored-list)
7190 (error "Formula removed"))
7191 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7192 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7193 (if (and name (not named))
7194 ;; We set the column equation, delete the named one.
7195 (setq stored-list (delq (assoc name stored-list) stored-list)
7196 mustsave t))
7197 (if stored
7198 (setcdr (assoc scol stored-list) eq)
7199 (setq stored-list (cons (cons scol eq) stored-list)))
7200 (if (or mustsave (not (equal stored eq)))
7201 (org-table-store-formulas stored-list))
7202 eq))
7203
7204 (defun org-table-store-formulas (alist)
7205 "Store the list of formulas below the current table."
7206 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7207 (save-excursion
7208 (goto-char (org-table-end))
7209 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7210 (delete-region (point) (match-end 0)))
7211 (insert "#+TBLFM: "
7212 (mapconcat (lambda (x)
7213 (concat "$" (car x) "=" (cdr x)))
7214 alist "::")
7215 "\n")))
7216
7217 (defun org-table-get-stored-formulas ()
7218 "Return an alist with the t=stored formulas directly after current table."
7219 (interactive)
7220 (let (scol eq eq-alist strings string seen)
7221 (save-excursion
7222 (goto-char (org-table-end))
7223 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7224 (setq strings (org-split-string (match-string 2) " *:: *"))
7225 (while (setq string (pop strings))
7226 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7227 (setq scol (match-string 1 string)
7228 eq (match-string 2 string)
7229 eq-alist (cons (cons scol eq) eq-alist))
7230 (if (member scol seen)
7231 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7232 (push scol seen))))))
7233 (nreverse eq-alist)))
7234
7235 (defun org-table-modify-formulas (action &rest columns)
7236 "Modify the formulas stored below the current table.
7237 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7238 expected, for the other action only a single column number is needed."
7239 (let ((list (org-table-get-stored-formulas))
7240 (nmax (length (org-split-string
7241 (buffer-substring (point-at-bol) (point-at-eol))
7242 "|")))
7243 col col1 col2 scol si sc1 sc2)
7244 (cond
7245 ((null list)) ; No action needed if there are no stored formulas
7246 ((eq action 'remove)
7247 (setq col (car columns)
7248 scol (int-to-string col))
7249 (org-table-replace-in-formulas list scol "INVALID")
7250 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7251 (loop for i from (1+ col) upto nmax by 1 do
7252 (setq si (int-to-string i))
7253 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7254 (if (assoc si list) (setcar (assoc si list)
7255 (int-to-string (1- i))))))
7256 ((eq action 'insert)
7257 (setq col (car columns))
7258 (loop for i from nmax downto col by 1 do
7259 (setq si (int-to-string i))
7260 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7261 (if (assoc si list) (setcar (assoc si list)
7262 (int-to-string (1+ i))))))
7263 ((eq action 'swap)
7264 (setq col1 (car columns) col2 (nth 1 columns)
7265 sc1 (int-to-string col1) sc2 (int-to-string col2))
7266 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7267 (org-table-replace-in-formulas list sc1 "ZqZ")
7268 (org-table-replace-in-formulas list sc2 sc1)
7269 (org-table-replace-in-formulas list "ZqZ" sc2)
7270 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7271 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7272 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7273 (t (error "Invalid action in `org-table-modify-formulas'")))
7274 (if list (org-table-store-formulas list))))
7275
7276 (defun org-table-replace-in-formulas (list s1 s2)
7277 (let (elt re s)
7278 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7279 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7280 re (concat (regexp-quote s1) "\\>"))
7281 (while (setq elt (pop list))
7282 (setq s (cdr elt))
7283 (while (string-match re s)
7284 (setq s (replace-match s2 t t s)))
7285 (setcdr elt s))))
7286
7287 (defun org-table-get-specials ()
7288 "Get the column nmaes and local parameters for this table."
7289 (save-excursion
7290 (let ((beg (org-table-begin)) (end (org-table-end))
7291 names name fields fields1 field cnt c v line col)
7292 (setq org-table-column-names nil
7293 org-table-local-parameters nil
7294 org-table-named-field-locations nil)
7295 (goto-char beg)
7296 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7297 (setq names (org-split-string (match-string 1) " *| *")
7298 cnt 1)
7299 (while (setq name (pop names))
7300 (setq cnt (1+ cnt))
7301 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7302 (push (cons name (int-to-string cnt)) org-table-column-names))))
7303 (setq org-table-column-names (nreverse org-table-column-names))
7304 (setq org-table-column-name-regexp
7305 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7306 (goto-char beg)
7307 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7308 (setq fields (org-split-string (match-string 1) " *| *"))
7309 (while (setq field (pop fields))
7310 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7311 (push (cons (match-string 1 field) (match-string 2 field))
7312 org-table-local-parameters))))
7313 (goto-char beg)
7314 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7315 (setq c (match-string 1)
7316 fields (org-split-string (match-string 2) " *| *"))
7317 (save-excursion
7318 (beginning-of-line (if (equal c "_") 2 0))
7319 (setq line (org-current-line) col 1)
7320 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7321 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7322 (while (and fields1 (setq field (pop fields)))
7323 (setq v (pop fields1) col (1+ col))
7324 (when (and (stringp field) (stringp v)
7325 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7326 (push (cons field v) org-table-local-parameters)
7327 (push (list field line col) org-table-named-field-locations)))))))
7328
7329 (defun org-this-word ()
7330 ;; Get the current word
7331 (save-excursion
7332 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7333 (end (progn (skip-chars-forward "^ \t\n") (point))))
7334 (buffer-substring-no-properties beg end))))
7335
7336 (defun org-table-maybe-eval-formula ()
7337 "Check if the current field starts with \"=\" or \":=\".
7338 If yes, store the formula and apply it."
7339 ;; We already know we are in a table. Get field will only return a formula
7340 ;; when appropriate. It might return a separator line, but no problem.
7341 (when org-table-formula-evaluate-inline
7342 (let* ((field (org-trim (or (org-table-get-field) "")))
7343 named eq)
7344 (when (string-match "^:?=\\(.*\\)" field)
7345 (setq named (equal (string-to-char field) ?:)
7346 eq (match-string 1 field))
7347 (if (fboundp 'calc-eval)
7348 (org-table-eval-formula (if named '(4) nil) eq))))))
7349
7350 (defvar org-recalc-commands nil
7351 "List of commands triggering the reccalculation of a line.
7352 Will be filled automatically during use.")
7353
7354 (defvar org-recalc-marks
7355 '((" " . "Unmarked: no special line, no automatic recalculation")
7356 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7357 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7358 ("!" . "Column name definition line. Reference in formula as $name.")
7359 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7360 ("_" . "Names for values in row below this one.")
7361 ("^" . "Names for values in row above this one.")))
7362
7363 (defun org-table-rotate-recalc-marks (&optional newchar)
7364 "Rotate the recalculation mark in the first column.
7365 If in any row, the first field is not consistent with a mark,
7366 insert a new column for the makers.
7367 When there is an active region, change all the lines in the region,
7368 after prompting for the marking character.
7369 After each change, a message will be displayed indication the meaning
7370 of the new mark."
7371 (interactive)
7372 (unless (org-at-table-p) (error "Not at a table"))
7373 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7374 (beg (org-table-begin))
7375 (end (org-table-end))
7376 (l (org-current-line))
7377 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7378 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7379 (have-col
7380 (save-excursion
7381 (goto-char beg)
7382 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7383 (col (org-table-current-column))
7384 (forcenew (car (assoc newchar org-recalc-marks)))
7385 epos new)
7386 (when l1
7387 (message "Change region to what mark? Type # * ! $ or SPC: ")
7388 (setq newchar (char-to-string (read-char-exclusive))
7389 forcenew (car (assoc newchar org-recalc-marks))))
7390 (if (and newchar (not forcenew))
7391 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7392 newchar))
7393 (if l1 (goto-line l1))
7394 (save-excursion
7395 (beginning-of-line 1)
7396 (unless (looking-at org-table-dataline-regexp)
7397 (error "Not at a table data line")))
7398 (unless have-col
7399 (org-table-goto-column 1)
7400 (org-table-insert-column)
7401 (org-table-goto-column (1+ col)))
7402 (setq epos (point-at-eol))
7403 (save-excursion
7404 (beginning-of-line 1)
7405 (org-table-get-field
7406 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7407 (concat " "
7408 (setq new (or forcenew
7409 (cadr (member (match-string 1) marks))))
7410 " ")
7411 " # ")))
7412 (if (and l1 l2)
7413 (progn
7414 (goto-line l1)
7415 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7416 (and (looking-at org-table-dataline-regexp)
7417 (org-table-get-field 1 (concat " " new " "))))
7418 (goto-line l1)))
7419 (if (not (= epos (point-at-eol))) (org-table-align))
7420 (goto-line l)
7421 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7422
7423 (defun org-table-maybe-recalculate-line ()
7424 "Recompute the current line if marked for it, and if we haven't just done it."
7425 (interactive)
7426 (and org-table-allow-automatic-line-recalculation
7427 (not (and (memq last-command org-recalc-commands)
7428 (equal org-last-recalc-line (org-current-line))))
7429 (save-excursion (beginning-of-line 1)
7430 (looking-at org-table-auto-recalculate-regexp))
7431 (fboundp 'calc-eval)
7432 (org-table-recalculate) t))
7433
7434 (defvar org-table-formula-debug nil
7435 "Non-nil means, debug table formulas.
7436 When nil, simply write \"#ERROR\" in corrupted fields.")
7437
7438 (defvar modes)
7439 (defsubst org-set-calc-mode (var &optional value)
7440 (if (stringp var)
7441 (setq var (assoc var '(("D" calc-angle-mode deg)
7442 ("R" calc-angle-mode rad)
7443 ("F" calc-prefer-frac t)
7444 ("S" calc-symbolic-mode t)))
7445 value (nth 2 var) var (nth 1 var)))
7446 (if (memq var modes)
7447 (setcar (cdr (memq var modes)) value)
7448 (cons var (cons value modes)))
7449 modes)
7450
7451 (defun org-table-eval-formula (&optional arg equation
7452 suppress-align suppress-const
7453 suppress-store)
7454 "Replace the table field value at the cursor by the result of a calculation.
7455
7456 This function makes use of Dave Gillespie's calc package, in my view the
7457 most exciting program ever written for GNU Emacs. So you need to have calc
7458 installed in order to use this function.
7459
7460 In a table, this command replaces the value in the current field with the
7461 result of a formula. It also installes the formula as the \"current\" column
7462 formula, by storing it in a special line below the table. When called
7463 with a `C-u' prefix, the current field must ba a named field, and the
7464 formula is installed as valid in only this specific field.
7465
7466 When called, the command first prompts for a formula, which is read in
7467 the minibuffer. Previously entered formulas are available through the
7468 history list, and the last used formula is offered as a default.
7469 These stored formulas are adapted correctly when moving, inserting, or
7470 deleting columns with the corresponding commands.
7471
7472 The formula can be any algebraic expression understood by the calc package.
7473 For details, see the Org-mode manual.
7474
7475 This function can also be called from Lisp programs and offers
7476 additional Arguments: EQUATION can be the formula to apply. If this
7477 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7478 used to speed-up recursive calls by by-passing unnecessary aligns.
7479 SUPPRESS-CONST suppresses the interpretation of constants in the
7480 formula, assuming that this has been done already outside the fuction.
7481 SUPPRESS-STORE means the formula should not be stored, either because
7482 it is already stored, or because it is a modified equation that should
7483 not overwrite the stored one."
7484 (interactive "P")
7485 (require 'calc)
7486 (org-table-check-inside-data-field)
7487 (org-table-get-specials)
7488 (let* (fields
7489 (ndown (if (integerp arg) arg 1))
7490 (org-table-automatic-realign nil)
7491 (case-fold-search nil)
7492 (down (> ndown 1))
7493 (formula (if (and equation suppress-store)
7494 equation
7495 (org-table-get-formula equation (equal arg '(4)))))
7496 (n0 (org-table-current-column))
7497 (modes (copy-sequence org-calc-default-modes))
7498 n form fmt x ev orig c)
7499 ;; Parse the format string. Since we have a lot of modes, this is
7500 ;; a lot of work. However, I think calc still uses most of the time.
7501 (if (string-match ";" formula)
7502 (let ((tmp (org-split-string formula ";")))
7503 (setq formula (car tmp)
7504 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7505 (nth 1 tmp)))
7506 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7507 (setq c (string-to-char (match-string 1 fmt))
7508 n (string-to-number (or (match-string 1 fmt) "")))
7509 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7510 (setq modes (org-set-calc-mode
7511 'calc-float-format
7512 (list (cdr (assoc c '((?n. float) (?f. fix)
7513 (?s. sci) (?e. eng))))
7514 n))))
7515 (setq fmt (replace-match "" t t fmt)))
7516 (while (string-match "[DRFS]" fmt)
7517 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7518 (setq fmt (replace-match "" t t fmt)))
7519 (unless (string-match "\\S-" fmt)
7520 (setq fmt nil))))
7521 (if (and (not suppress-const) org-table-formula-use-constants)
7522 (setq formula (org-table-formula-substitute-names formula)))
7523 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7524 (while (> ndown 0)
7525 (setq fields (org-split-string
7526 (buffer-substring
7527 (point-at-bol) (point-at-eol)) " *| *"))
7528 (if org-table-formula-numbers-only
7529 (setq fields (mapcar
7530 (lambda (x) (number-to-string (string-to-number x)))
7531 fields)))
7532 (setq ndown (1- ndown))
7533 (setq form (copy-sequence formula))
7534 ;; Insert the references to fields in same row
7535 (while (string-match "\\$\\([0-9]+\\)?" form)
7536 (setq n (if (match-beginning 1)
7537 (string-to-number (match-string 1 form))
7538 n0)
7539 x (nth (1- n) fields))
7540 (unless x (error "Invalid field specifier \"%s\""
7541 (match-string 0 form)))
7542 (if (equal x "") (setq x "0"))
7543 (setq form (replace-match (concat "(" x ")") t t form)))
7544 ;; Insert ranges in current column
7545 (while (string-match "\\&[-I0-9]+" form)
7546 (setq form (replace-match
7547 (save-match-data
7548 (org-table-get-vertical-vector (match-string 0 form)
7549 nil n0))
7550 t t form)))
7551 (setq ev (calc-eval (cons form modes)
7552 (if org-table-formula-numbers-only 'num)))
7553
7554 (when org-table-formula-debug
7555 (with-output-to-temp-buffer "*Help*"
7556 (princ (format "Substitution history of formula
7557 Orig: %s
7558 $xyz-> %s
7559 $1-> %s\n" orig formula form))
7560 (if (listp ev)
7561 (princ (format " %s^\nError: %s"
7562 (make-string (car ev) ?\-) (nth 1 ev)))
7563 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7564 ev (or fmt "NONE")
7565 (if fmt (format fmt (string-to-number ev)) ev)))))
7566 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7567 (unless (and (interactive-p) (not ndown))
7568 (unless (let (inhibit-redisplay)
7569 (y-or-n-p "Debugging Formula. Continue to next? "))
7570 (org-table-align)
7571 (error "Abort"))
7572 (delete-window (get-buffer-window "*Help*"))
7573 (message "")))
7574 (if (listp ev) (setq fmt nil ev "#ERROR"))
7575 (org-table-justify-field-maybe
7576 (if fmt (format fmt (string-to-number ev)) ev))
7577 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7578 (call-interactively 'org-return)
7579 (setq ndown 0)))
7580 (and down (org-table-maybe-recalculate-line))
7581 (or suppress-align (and org-table-may-need-update
7582 (org-table-align)))))
7583
7584 (defun org-table-recalculate (&optional all noalign)
7585 "Recalculate the current table line by applying all stored formulas."
7586 (interactive "P")
7587 (or (memq this-command org-recalc-commands)
7588 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7589 (unless (org-at-table-p) (error "Not at a table"))
7590 (org-table-get-specials)
7591 (let* ((eqlist (sort (org-table-get-stored-formulas)
7592 (lambda (a b) (string< (car a) (car b)))))
7593 (inhibit-redisplay t)
7594 (line-re org-table-dataline-regexp)
7595 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7596 (thiscol (org-table-current-column))
7597 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7598 ;; Insert constants in all formulas
7599 (setq eqlist
7600 (mapcar (lambda (x)
7601 (setcdr x (org-table-formula-substitute-names (cdr x)))
7602 x)
7603 eqlist))
7604 ;; Split the equation list
7605 (while (setq eq (pop eqlist))
7606 (if (<= (string-to-char (car eq)) ?9)
7607 (push eq eqlnum)
7608 (push eq eqlname)))
7609 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7610 (if all
7611 (progn
7612 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7613 (goto-char (setq beg (org-table-begin)))
7614 (if (re-search-forward org-table-calculate-mark-regexp end t)
7615 ;; This is a table with marked lines, only compute selected lines
7616 (setq line-re org-table-recalculate-regexp)
7617 ;; Move forward to the first non-header line
7618 (if (and (re-search-forward org-table-dataline-regexp end t)
7619 (re-search-forward org-table-hline-regexp end t)
7620 (re-search-forward org-table-dataline-regexp end t))
7621 (setq beg (match-beginning 0))
7622 nil))) ;; just leave beg where it is
7623 (setq beg (point-at-bol)
7624 end (move-marker (make-marker) (1+ (point-at-eol)))))
7625 (goto-char beg)
7626 (and all (message "Re-applying formulas to full table..."))
7627 (while (re-search-forward line-re end t)
7628 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7629 ;; Unprotected line, recalculate
7630 (and all (message "Re-applying formulas to full table...(line %d)"
7631 (setq cnt (1+ cnt))))
7632 (setq org-last-recalc-line (org-current-line))
7633 (setq eql eqlnum)
7634 (while (setq entry (pop eql))
7635 (goto-line org-last-recalc-line)
7636 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7637 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7638 (goto-line thisline)
7639 (org-table-goto-column thiscol)
7640 (or noalign (and org-table-may-need-update (org-table-align))
7641 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7642 ;; Now do the names fields
7643 (while (setq eq (pop eqlname))
7644 (setq name (car eq)
7645 a (assoc name org-table-named-field-locations))
7646 (when a
7647 (message "Re-applying formula to named field: %s" name)
7648 (goto-line (nth 1 a))
7649 (org-table-goto-column (nth 2 a))
7650 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7651 ;; back to initial position
7652 (goto-line thisline)
7653 (org-table-goto-column thiscol)
7654 (or noalign (and org-table-may-need-update (org-table-align))
7655 (and all (message "Re-applying formulas...done")))))
7656
7657 (defun org-table-formula-substitute-names (f)
7658 "Replace $const with values in string F."
7659 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7660 ;; First, check for column names
7661 (while (setq start (string-match org-table-column-name-regexp f start))
7662 (setq start (1+ start))
7663 (setq a (assoc (match-string 1 f) org-table-column-names))
7664 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7665 ;; Expand ranges to vectors
7666 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7667 (setq n1 (string-to-number (match-string 1 f))
7668 n2 (string-to-number (match-string 2 f))
7669 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7670 s (concat "[($" (number-to-string (1- nn1)) ")"))
7671 (loop for i from nn1 upto nn2 do
7672 (setq s (concat s ",($" (int-to-string i) ")")))
7673 (setq s (concat s "]"))
7674 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7675 (setq f (replace-match s t t f)))
7676 ;; Parameters and constants
7677 (setq start 0)
7678 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7679 (setq start (1+ start))
7680 (if (setq a (save-match-data
7681 (org-table-get-constant (match-string 1 f))))
7682 (setq f (replace-match (concat "(" a ")") t t f))))
7683 (if org-table-formula-debug
7684 (put-text-property 0 (length f) :orig-formula f1 f))
7685 f))
7686
7687 (defun org-table-get-constant (const)
7688 "Find the value for a parameter or constant in a formula.
7689 Parameters get priority."
7690 (or (cdr (assoc const org-table-local-parameters))
7691 (cdr (assoc const org-table-formula-constants))
7692 (and (fboundp 'constants-get) (constants-get const))
7693 "#UNDEFINED_NAME"))
7694
7695 (defvar org-edit-formulas-map (make-sparse-keymap))
7696 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7697 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7698 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7699
7700 (defvar org-pos)
7701 (defvar org-window-configuration)
7702
7703 (defun org-table-edit-formulas ()
7704 "Edit the formulas of the current table in a separate buffer."
7705 (interactive)
7706 (unless (org-at-table-p)
7707 (error "Not at a table"))
7708 (org-table-get-specials)
7709 (let ((eql (org-table-get-stored-formulas))
7710 (pos (move-marker (make-marker) (point)))
7711 (wc (current-window-configuration))
7712 entry loc s)
7713 (switch-to-buffer-other-window "*Edit Formulas*")
7714 (erase-buffer)
7715 (fundamental-mode)
7716 (set (make-local-variable 'org-pos) pos)
7717 (set (make-local-variable 'org-window-configuration) wc)
7718 (use-local-map org-edit-formulas-map)
7719 (setq s "# Edit formulas and finish with `C-c C-c'.
7720 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7721 # Use `C-c ?' to get information about $name at point.
7722 # To cancel editing, press `C-c C-q'.\n")
7723 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7724 (insert s)
7725 (while (setq entry (pop eql))
7726 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7727 (setq s (format "# Named formula, referring to column %d in line %d\n"
7728 (nth 2 loc) (nth 1 loc)))
7729 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7730 (insert s))
7731 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7732 (remove-text-properties 0 (length s) '(face nil) s)
7733 (insert s))
7734 (goto-char (point-min))
7735 (message "Edit formulas and finish with `C-c C-c'.")))
7736
7737 (defun org-show-variable ()
7738 "Show the location/value of the $ expression at point."
7739 (interactive)
7740 (let (var (pos org-pos) (win (selected-window)) e)
7741 (save-excursion
7742 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7743 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7744 (setq var (match-string 1))
7745 (error "No variable at point")))
7746 (cond
7747 ((setq e (assoc var org-table-named-field-locations))
7748 (switch-to-buffer-other-window (marker-buffer pos))
7749 (goto-line (nth 1 e))
7750 (org-table-goto-column (nth 2 e))
7751 (select-window win)
7752 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7753 ((setq e (assoc var org-table-column-names))
7754 (switch-to-buffer-other-window (marker-buffer pos))
7755 (goto-char pos)
7756 (goto-char (org-table-begin))
7757 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7758 (org-table-end) t)
7759 (progn
7760 (goto-char (match-beginning 1))
7761 (message "Named column (column %s)" (cdr e)))
7762 (error "Column name not found"))
7763 (select-window win))
7764 ((string-match "^[0-9]$" var)
7765 ;; column number
7766 (switch-to-buffer-other-window (marker-buffer pos))
7767 (goto-char pos)
7768 (goto-char (org-table-begin))
7769 (recenter 1)
7770 (if (re-search-forward org-table-dataline-regexp
7771 (org-table-end) t)
7772 (progn
7773 (goto-char (match-beginning 0))
7774 (org-table-goto-column (string-to-number var))
7775 (message "Column %s" var))
7776 (error "Column name not found"))
7777 (select-window win))
7778 ((setq e (assoc var org-table-local-parameters))
7779 (switch-to-buffer-other-window (marker-buffer pos))
7780 (goto-char pos)
7781 (goto-char (org-table-begin))
7782 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7783 (progn
7784 (goto-char (match-beginning 1))
7785 (message "Local parameter."))
7786 (error "Parameter not found"))
7787 (select-window win))
7788 (t
7789 (cond
7790 ((setq e (assoc var org-table-formula-constants))
7791 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7792 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7793 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7794 (t (error "Undefined name $%s" var)))))))
7795
7796 (defun org-finish-edit-formulas (&optional arg)
7797 "Parse the buffer for formula definitions and install them.
7798 With prefix ARG, apply the new formulas to the table."
7799 (interactive "P")
7800 (let ((pos org-pos) eql)
7801 (goto-char (point-min))
7802 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7803 (push (cons (match-string 1) (match-string 2)) eql))
7804 (set-window-configuration org-window-configuration)
7805 (select-window (get-buffer-window (marker-buffer pos)))
7806 (goto-char pos)
7807 (unless (org-at-table-p)
7808 (error "Lost table position - cannot install formulae"))
7809 (org-table-store-formulas eql)
7810 (move-marker pos nil)
7811 (kill-buffer "*Edit Formulas*")
7812 (if arg
7813 (org-table-recalculate 'all)
7814 (message "New formulas installed - press C-u C-c C-c to apply."))))
7815
7816 (defun org-abort-edit-formulas ()
7817 "Abort editing formulas, without installing the changes."
7818 (interactive)
7819 (let ((pos org-pos))
7820 (set-window-configuration org-window-configuration)
7821 (select-window (get-buffer-window (marker-buffer pos)))
7822 (goto-char pos)
7823 (message "Formula editing aborted without installing changes")))
7824
7825 ;;; The orgtbl minor mode
7826
7827 ;; Define a minor mode which can be used in other modes in order to
7828 ;; integrate the org-mode table editor.
7829
7830 ;; This is really a hack, because the org-mode table editor uses several
7831 ;; keys which normally belong to the major mode, for example the TAB and
7832 ;; RET keys. Here is how it works: The minor mode defines all the keys
7833 ;; necessary to operate the table editor, but wraps the commands into a
7834 ;; function which tests if the cursor is currently inside a table. If that
7835 ;; is the case, the table editor command is executed. However, when any of
7836 ;; those keys is used outside a table, the function uses `key-binding' to
7837 ;; look up if the key has an associated command in another currently active
7838 ;; keymap (minor modes, major mode, global), and executes that command.
7839 ;; There might be problems if any of the keys used by the table editor is
7840 ;; otherwise used as a prefix key.
7841
7842 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7843 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7844 ;; addresses this by checking explicitly for both bindings.
7845
7846 ;; The optimized version (see variable `orgtbl-optimized') takes over
7847 ;; all keys which are bound to `self-insert-command' in the *global map*.
7848 ;; Some modes bind other commands to simple characters, for example
7849 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7850 ;; active, this binding is ignored inside tables and replaced with a
7851 ;; modified self-insert.
7852
7853 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7854 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7855 In the optimized version, the table editor takes over all simple keys that
7856 normally just insert a character. In tables, the characters are inserted
7857 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7858 for empty fields). Outside tables, the correct binding of the keys is
7859 restored.
7860
7861 The default for this option is t if the optimized version is also used in
7862 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7863 this variable requires a restart of Emacs to become effective."
7864 :group 'org-table
7865 :type 'boolean)
7866
7867 (defvar orgtbl-mode nil
7868 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7869 table editor in arbitrary modes.")
7870 (make-variable-buffer-local 'orgtbl-mode)
7871
7872 (defvar orgtbl-mode-map (make-sparse-keymap)
7873 "Keymap for `orgtbl-mode'.")
7874
7875 ;;;###autoload
7876 (defun turn-on-orgtbl ()
7877 "Unconditionally turn on `orgtbl-mode'."
7878 (orgtbl-mode 1))
7879
7880 ;;;###autoload
7881 (defun orgtbl-mode (&optional arg)
7882 "The `org-mode' table editor as a minor mode for use in other modes."
7883 (interactive)
7884 (if (eq major-mode 'org-mode)
7885 ;; Exit without error, in case some hook functions calls this
7886 ;; by accident in org-mode.
7887 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7888 (setq orgtbl-mode
7889 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7890 (if orgtbl-mode
7891 (progn
7892 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7893 ;; Make sure we are first in minor-mode-map-alist
7894 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7895 (and c (setq minor-mode-map-alist
7896 (cons c (delq c minor-mode-map-alist)))))
7897 (set (make-local-variable (quote org-table-may-need-update)) t)
7898 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
7899 (add-hook 'before-change-functions 'org-before-change-function
7900 nil 'local)
7901 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7902 auto-fill-inhibit-regexp)
7903 (set (make-local-variable 'auto-fill-inhibit-regexp)
7904 (if auto-fill-inhibit-regexp
7905 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7906 "[ \t]*|"))
7907 (easy-menu-add orgtbl-mode-menu)
7908 (run-hooks 'orgtbl-mode-hook))
7909 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7910 (remove-hook 'before-change-functions 'org-before-change-function t)
7911 (easy-menu-remove orgtbl-mode-menu)
7912 (force-mode-line-update 'all))))
7913
7914 ;; Install it as a minor mode.
7915 (put 'orgtbl-mode :included t)
7916 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7917 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7918
7919 (defun orgtbl-make-binding (fun n &rest keys)
7920 "Create a function for binding in the table minor mode.
7921 FUN is the command to call inside a table. N is used to create a unique
7922 command name. KEYS are keys that should be checked in for a command
7923 to execute outside of tables."
7924 (eval
7925 (list 'defun
7926 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7927 '(arg)
7928 (concat "In tables, run `" (symbol-name fun) "'.\n"
7929 "Outside of tables, run the binding of `"
7930 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7931 "'.")
7932 '(interactive "p")
7933 (list 'if
7934 '(org-at-table-p)
7935 (list 'call-interactively (list 'quote fun))
7936 (list 'let '(orgtbl-mode)
7937 (list 'call-interactively
7938 (append '(or)
7939 (mapcar (lambda (k)
7940 (list 'key-binding k))
7941 keys)
7942 '('orgtbl-error))))))))
7943
7944 (defun orgtbl-error ()
7945 "Error when there is no default binding for a table key."
7946 (interactive)
7947 (error "This key is has no function outside tables"))
7948
7949 (defun orgtbl-setup ()
7950 "Setup orgtbl keymaps."
7951 (let ((nfunc 0)
7952 (bindings
7953 (list
7954 '([(meta shift left)] org-table-delete-column)
7955 '([(meta left)] org-table-move-column-left)
7956 '([(meta right)] org-table-move-column-right)
7957 '([(meta shift right)] org-table-insert-column)
7958 '([(meta shift up)] org-table-kill-row)
7959 '([(meta shift down)] org-table-insert-row)
7960 '([(meta up)] org-table-move-row-up)
7961 '([(meta down)] org-table-move-row-down)
7962 '("\C-c\C-w" org-table-cut-region)
7963 '("\C-c\M-w" org-table-copy-region)
7964 '("\C-c\C-y" org-table-paste-rectangle)
7965 '("\C-c-" org-table-insert-hline)
7966 ; '([(shift tab)] org-table-previous-field)
7967 '("\C-m" org-table-next-row)
7968 (list (org-key 'S-return) 'org-table-copy-down)
7969 '([(meta return)] org-table-wrap-region)
7970 '("\C-c\C-q" org-table-wrap-region)
7971 '("\C-c?" org-table-current-column)
7972 '("\C-c " org-table-blank-field)
7973 '("\C-c+" org-table-sum)
7974 '("\C-c|" org-table-toggle-vline-visibility)
7975 '("\C-c=" org-table-eval-formula)
7976 '("\C-c'" org-table-edit-formulas)
7977 '("\C-c*" org-table-recalculate)
7978 '([(control ?#)] org-table-rotate-recalc-marks)))
7979 elt key fun cmd)
7980 (while (setq elt (pop bindings))
7981 (setq nfunc (1+ nfunc))
7982 (setq key (car elt)
7983 fun (nth 1 elt)
7984 cmd (orgtbl-make-binding fun nfunc key))
7985 (define-key orgtbl-mode-map key cmd))
7986 ;; Special treatment needed for TAB and RET
7987 (define-key orgtbl-mode-map [(return)]
7988 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7989 (define-key orgtbl-mode-map "\C-m"
7990 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7991 (define-key orgtbl-mode-map [(tab)]
7992 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7993 (define-key orgtbl-mode-map "\C-i"
7994 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7995 (define-key orgtbl-mode-map "\C-i"
7996 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
7997 (define-key orgtbl-mode-map "\C-c\C-c"
7998 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
7999 (when orgtbl-optimized
8000 ;; If the user wants maximum table support, we need to hijack
8001 ;; some standard editing functions
8002 (org-remap orgtbl-mode-map
8003 'self-insert-command 'orgtbl-self-insert-command
8004 'delete-char 'orgtbl-delete-char
8005 'delete-backward-char 'orgtbl-delete-backward-char)
8006 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8007 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8008 '("OrgTbl"
8009 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8010 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8011 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8012 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8013 "--"
8014 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8015 ["Copy Field from Above"
8016 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8017 "--"
8018 ("Column"
8019 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8020 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8021 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8022 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8023 ("Row"
8024 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8025 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8026 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8027 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8028 "--"
8029 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8030 ("Rectangle"
8031 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c C-x M-w"]
8032 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-x C-w"]
8033 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-x C-y"]
8034 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
8035 "--"
8036 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8037 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8038 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8039 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8040 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8041 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8042 ["Sum Column/Rectangle" org-table-sum
8043 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8044 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8045 ["Debug Formulas"
8046 (setq org-table-formula-debug (not org-table-formula-debug))
8047 :style toggle :selected org-table-formula-debug]
8048 ))
8049 t)
8050
8051 (defun orgtbl-tab ()
8052 "Justification and field motion for `orgtbl-mode'."
8053 (interactive)
8054 (org-table-justify-field-maybe)
8055 (org-table-next-field))
8056
8057 (defun orgtbl-ret ()
8058 "Justification and field motion for `orgtbl-mode'."
8059 (interactive)
8060 (org-table-justify-field-maybe)
8061 (org-table-next-row))
8062
8063 (defun orgtbl-self-insert-command (N)
8064 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8065 If the cursor is in a table looking at whitespace, the whitespace is
8066 overwritten, and the table is not marked as requiring realignment."
8067 (interactive "p")
8068 (if (and (org-at-table-p)
8069 (or
8070 (and org-table-auto-blank-field
8071 (member last-command
8072 '(orgtbl-hijacker-command-100
8073 orgtbl-hijacker-command-101
8074 orgtbl-hijacker-command-102
8075 orgtbl-hijacker-command-103
8076 orgtbl-hijacker-command-104
8077 orgtbl-hijacker-command-105))
8078 (org-table-blank-field))
8079 t)
8080 (eq N 1)
8081 (looking-at "[^|\n]* +|"))
8082 (let (org-table-may-need-update)
8083 (goto-char (1- (match-end 0)))
8084 (delete-backward-char 1)
8085 (goto-char (match-beginning 0))
8086 (self-insert-command N))
8087 (setq org-table-may-need-update t)
8088 (let (orgtbl-mode)
8089 (call-interactively (key-binding (vector last-input-event))))))
8090
8091 (defun org-force-self-insert (N)
8092 "Needed to enforce self-insert under remapping."
8093 (interactive "p")
8094 (self-insert-command N))
8095
8096 (defun orgtbl-delete-backward-char (N)
8097 "Like `delete-backward-char', insert whitespace at field end in tables.
8098 When deleting backwards, in tables this function will insert whitespace in
8099 front of the next \"|\" separator, to keep the table aligned. The table will
8100 still be marked for re-alignment, because a narrow field may lead to a
8101 reduced column width."
8102 (interactive "p")
8103 (if (and (org-at-table-p)
8104 (eq N 1)
8105 (string-match "|" (buffer-substring (point-at-bol) (point)))
8106 (looking-at ".*?|"))
8107 (let ((pos (point)))
8108 (backward-delete-char N)
8109 (skip-chars-forward "^|")
8110 (insert " ")
8111 (goto-char (1- pos)))
8112 (delete-backward-char N)))
8113
8114 (defun orgtbl-delete-char (N)
8115 "Like `delete-char', but insert whitespace at field end in tables.
8116 When deleting characters, in tables this function will insert whitespace in
8117 front of the next \"|\" separator, to keep the table aligned. The table
8118 will still be marked for re-alignment, because a narrow field may lead to
8119 a reduced column width."
8120 (interactive "p")
8121 (if (and (org-at-table-p)
8122 (not (bolp))
8123 (not (= (char-after) ?|))
8124 (eq N 1))
8125 (if (looking-at ".*?|")
8126 (let ((pos (point)))
8127 (replace-match (concat
8128 (substring (match-string 0) 1 -1)
8129 " |"))
8130 (goto-char pos)))
8131 (delete-char N)))
8132
8133 ;;; Exporting
8134
8135 (defconst org-level-max 20)
8136
8137 (defun org-export-find-first-heading-line (list)
8138 "Remove all lines from LIST which are before the first headline."
8139 (let ((orig-list list)
8140 (re (concat "^" outline-regexp)))
8141 (while (and list
8142 (not (string-match re (car list))))
8143 (pop list))
8144 (or list orig-list)))
8145
8146 (defun org-skip-comments (lines)
8147 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8148 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8149 (re2 "^\\(\\*+\\)[ \t\n\r]")
8150 rtn line level)
8151 (while (setq line (pop lines))
8152 (cond
8153 ((and (string-match re1 line)
8154 (setq level (- (match-end 1) (match-beginning 1))))
8155 ;; Beginning of a COMMENT subtree. Skip it.
8156 (while (and (setq line (pop lines))
8157 (or (not (string-match re2 line))
8158 (> (- (match-end 1) (match-beginning 1)) level))))
8159 (setq lines (cons line lines)))
8160 ((string-match "^#" line)
8161 ;; an ordinary comment line
8162 )
8163 (t (setq rtn (cons line rtn)))))
8164 (nreverse rtn)))
8165
8166 ;; ASCII
8167
8168 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8169 "Characters for underlining headings in ASCII export.")
8170
8171 (defconst org-html-entities
8172 '(("nbsp")
8173 ("iexcl")
8174 ("cent")
8175 ("pound")
8176 ("curren")
8177 ("yen")
8178 ("brvbar")
8179 ("sect")
8180 ("uml")
8181 ("copy")
8182 ("ordf")
8183 ("laquo")
8184 ("not")
8185 ("shy")
8186 ("reg")
8187 ("macr")
8188 ("deg")
8189 ("plusmn")
8190 ("sup2")
8191 ("sup3")
8192 ("acute")
8193 ("micro")
8194 ("para")
8195 ("middot")
8196 ("odot"."o")
8197 ("star"."*")
8198 ("cedil")
8199 ("sup1")
8200 ("ordm")
8201 ("raquo")
8202 ("frac14")
8203 ("frac12")
8204 ("frac34")
8205 ("iquest")
8206 ("Agrave")
8207 ("Aacute")
8208 ("Acirc")
8209 ("Atilde")
8210 ("Auml")
8211 ("Aring") ("AA"."&Aring;")
8212 ("AElig")
8213 ("Ccedil")
8214 ("Egrave")
8215 ("Eacute")
8216 ("Ecirc")
8217 ("Euml")
8218 ("Igrave")
8219 ("Iacute")
8220 ("Icirc")
8221 ("Iuml")
8222 ("ETH")
8223 ("Ntilde")
8224 ("Ograve")
8225 ("Oacute")
8226 ("Ocirc")
8227 ("Otilde")
8228 ("Ouml")
8229 ("times")
8230 ("Oslash")
8231 ("Ugrave")
8232 ("Uacute")
8233 ("Ucirc")
8234 ("Uuml")
8235 ("Yacute")
8236 ("THORN")
8237 ("szlig")
8238 ("agrave")
8239 ("aacute")
8240 ("acirc")
8241 ("atilde")
8242 ("auml")
8243 ("aring")
8244 ("aelig")
8245 ("ccedil")
8246 ("egrave")
8247 ("eacute")
8248 ("ecirc")
8249 ("euml")
8250 ("igrave")
8251 ("iacute")
8252 ("icirc")
8253 ("iuml")
8254 ("eth")
8255 ("ntilde")
8256 ("ograve")
8257 ("oacute")
8258 ("ocirc")
8259 ("otilde")
8260 ("ouml")
8261 ("divide")
8262 ("oslash")
8263 ("ugrave")
8264 ("uacute")
8265 ("ucirc")
8266 ("uuml")
8267 ("yacute")
8268 ("thorn")
8269 ("yuml")
8270 ("fnof")
8271 ("Alpha")
8272 ("Beta")
8273 ("Gamma")
8274 ("Delta")
8275 ("Epsilon")
8276 ("Zeta")
8277 ("Eta")
8278 ("Theta")
8279 ("Iota")
8280 ("Kappa")
8281 ("Lambda")
8282 ("Mu")
8283 ("Nu")
8284 ("Xi")
8285 ("Omicron")
8286 ("Pi")
8287 ("Rho")
8288 ("Sigma")
8289 ("Tau")
8290 ("Upsilon")
8291 ("Phi")
8292 ("Chi")
8293 ("Psi")
8294 ("Omega")
8295 ("alpha")
8296 ("beta")
8297 ("gamma")
8298 ("delta")
8299 ("epsilon")
8300 ("varepsilon"."&epsilon;")
8301 ("zeta")
8302 ("eta")
8303 ("theta")
8304 ("iota")
8305 ("kappa")
8306 ("lambda")
8307 ("mu")
8308 ("nu")
8309 ("xi")
8310 ("omicron")
8311 ("pi")
8312 ("rho")
8313 ("sigmaf") ("varsigma"."&sigmaf;")
8314 ("sigma")
8315 ("tau")
8316 ("upsilon")
8317 ("phi")
8318 ("chi")
8319 ("psi")
8320 ("omega")
8321 ("thetasym") ("vartheta"."&thetasym;")
8322 ("upsih")
8323 ("piv")
8324 ("bull") ("bullet"."&bull;")
8325 ("hellip") ("dots"."&hellip;")
8326 ("prime")
8327 ("Prime")
8328 ("oline")
8329 ("frasl")
8330 ("weierp")
8331 ("image")
8332 ("real")
8333 ("trade")
8334 ("alefsym")
8335 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
8336 ("uarr") ("uparrow"."&uarr;")
8337 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
8338 ("darr")("downarrow"."&darr;")
8339 ("harr") ("leftrightarrow"."&harr;")
8340 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
8341 ("lArr") ("Leftarrow"."&lArr;")
8342 ("uArr") ("Uparrow"."&uArr;")
8343 ("rArr") ("Rightarrow"."&rArr;")
8344 ("dArr") ("Downarrow"."&dArr;")
8345 ("hArr") ("Leftrightarrow"."&hArr;")
8346 ("forall")
8347 ("part") ("partial"."&part;")
8348 ("exist") ("exists"."&exist;")
8349 ("empty") ("emptyset"."&empty;")
8350 ("nabla")
8351 ("isin") ("in"."&isin;")
8352 ("notin")
8353 ("ni")
8354 ("prod")
8355 ("sum")
8356 ("minus")
8357 ("lowast") ("ast"."&lowast;")
8358 ("radic")
8359 ("prop") ("proptp"."&prop;")
8360 ("infin") ("infty"."&infin;")
8361 ("ang") ("angle"."&ang;")
8362 ("and") ("vee"."&and;")
8363 ("or") ("wedge"."&or;")
8364 ("cap")
8365 ("cup")
8366 ("int")
8367 ("there4")
8368 ("sim")
8369 ("cong") ("simeq"."&cong;")
8370 ("asymp")("approx"."&asymp;")
8371 ("ne") ("neq"."&ne;")
8372 ("equiv")
8373 ("le")
8374 ("ge")
8375 ("sub") ("subset"."&sub;")
8376 ("sup") ("supset"."&sup;")
8377 ("nsub")
8378 ("sube")
8379 ("supe")
8380 ("oplus")
8381 ("otimes")
8382 ("perp")
8383 ("sdot") ("cdot"."&sdot;")
8384 ("lceil")
8385 ("rceil")
8386 ("lfloor")
8387 ("rfloor")
8388 ("lang")
8389 ("rang")
8390 ("loz") ("Diamond"."&loz;")
8391 ("spades") ("spadesuit"."&spades;")
8392 ("clubs") ("clubsuit"."&clubs;")
8393 ("hearts") ("diamondsuit"."&hearts;")
8394 ("diams") ("diamondsuit"."&diams;")
8395 ("quot")
8396 ("amp")
8397 ("lt")
8398 ("gt")
8399 ("OElig")
8400 ("oelig")
8401 ("Scaron")
8402 ("scaron")
8403 ("Yuml")
8404 ("circ")
8405 ("tilde")
8406 ("ensp")
8407 ("emsp")
8408 ("thinsp")
8409 ("zwnj")
8410 ("zwj")
8411 ("lrm")
8412 ("rlm")
8413 ("ndash")
8414 ("mdash")
8415 ("lsquo")
8416 ("rsquo")
8417 ("sbquo")
8418 ("ldquo")
8419 ("rdquo")
8420 ("bdquo")
8421 ("dagger")
8422 ("Dagger")
8423 ("permil")
8424 ("lsaquo")
8425 ("rsaquo")
8426 ("euro")
8427
8428 ("arccos"."arccos")
8429 ("arcsin"."arcsin")
8430 ("arctan"."arctan")
8431 ("arg"."arg")
8432 ("cos"."cos")
8433 ("cosh"."cosh")
8434 ("cot"."cot")
8435 ("coth"."coth")
8436 ("csc"."csc")
8437 ("deg"."deg")
8438 ("det"."det")
8439 ("dim"."dim")
8440 ("exp"."exp")
8441 ("gcd"."gcd")
8442 ("hom"."hom")
8443 ("inf"."inf")
8444 ("ker"."ker")
8445 ("lg"."lg")
8446 ("lim"."lim")
8447 ("liminf"."liminf")
8448 ("limsup"."limsup")
8449 ("ln"."ln")
8450 ("log"."log")
8451 ("max"."max")
8452 ("min"."min")
8453 ("Pr"."Pr")
8454 ("sec"."sec")
8455 ("sin"."sin")
8456 ("sinh"."sinh")
8457 ("sup"."sup")
8458 ("tan"."tan")
8459 ("tanh"."tanh")
8460 )
8461 "Entities for TeX->HTML translation.
8462 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8463 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8464 In that case, \"\\ent\" will be translated to \"&other;\".
8465 The list contains HTML entities for Latin-1, Greek and other symbols.
8466 It is supplemented by a number of commonly used TeX macros with appropriate
8467 translations. There is currently no way for users to extend this.")
8468
8469 (defvar org-last-level nil) ; dynamically scoped variable
8470
8471 (defun org-export-as-ascii (arg)
8472 "Export the outline as a pretty ASCII file.
8473 If there is an active region, export only the region.
8474 The prefix ARG specifies how many levels of the outline should become
8475 underlined headlines. The default is 3."
8476 (interactive "P")
8477 (setq-default org-todo-line-regexp org-todo-line-regexp)
8478 (let* ((region
8479 (buffer-substring
8480 (if (org-region-active-p) (region-beginning) (point-min))
8481 (if (org-region-active-p) (region-end) (point-max))))
8482 (lines (org-export-find-first-heading-line
8483 (org-skip-comments (org-split-string region "[\r\n]"))))
8484 (org-startup-with-deadline-check nil)
8485 (level 0) line txt
8486 (umax nil)
8487 (case-fold-search nil)
8488 (filename (concat (file-name-sans-extension (buffer-file-name))
8489 ".txt"))
8490 (buffer (find-file-noselect filename))
8491 (levels-open (make-vector org-level-max nil))
8492 (date (format-time-string "%Y/%m/%d" (current-time)))
8493 (time (format-time-string "%X" (current-time)))
8494 (author user-full-name)
8495 (title (buffer-name))
8496 (options nil)
8497 (email user-mail-address)
8498 (language org-export-default-language)
8499 (text nil)
8500 (todo nil)
8501 (lang-words nil))
8502
8503 (setq org-last-level 1)
8504 (org-init-section-numbers)
8505
8506 (find-file-noselect filename)
8507
8508 ;; Search for the export key lines
8509 (org-parse-key-lines)
8510
8511 (setq lang-words (or (assoc language org-export-language-setup)
8512 (assoc "en" org-export-language-setup)))
8513 (if org-export-ascii-show-new-buffer
8514 (switch-to-buffer-other-window buffer)
8515 (set-buffer buffer))
8516 (erase-buffer)
8517 (fundamental-mode)
8518 (if options (org-parse-export-options options))
8519 (setq umax (if arg (prefix-numeric-value arg)
8520 org-export-headline-levels))
8521
8522 ;; File header
8523 (if title (org-insert-centered title ?=))
8524 (insert "\n")
8525 (if (or author email)
8526 (insert (concat (nth 1 lang-words) ": " (or author "")
8527 (if email (concat " <" email ">") "")
8528 "\n")))
8529 (if (and date time)
8530 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8531 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8532
8533 (insert "\n\n")
8534
8535 (if org-export-with-toc
8536 (progn
8537 (insert (nth 3 lang-words) "\n"
8538 (make-string (length (nth 3 lang-words)) ?=) "\n")
8539 (mapcar '(lambda (line)
8540 (if (string-match org-todo-line-regexp
8541 line)
8542 ;; This is a headline
8543 (progn
8544 (setq level (- (match-end 1) (match-beginning 1))
8545 txt (match-string 3 line)
8546 todo
8547 (or (and (match-beginning 2)
8548 (not (equal (match-string 2 line)
8549 org-done-string)))
8550 ; TODO, not DONE
8551 (and (= level umax)
8552 (org-search-todo-below
8553 line lines level))))
8554 (setq txt (org-html-expand-for-ascii txt))
8555
8556 (if org-export-with-section-numbers
8557 (setq txt (concat (org-section-number level)
8558 " " txt)))
8559 (if (<= level umax)
8560 (progn
8561 (insert
8562 (make-string (* (1- level) 4) ?\ )
8563 (format (if todo "%s (*)\n" "%s\n") txt))
8564 (setq org-last-level level))
8565 ))))
8566 lines)))
8567
8568 (org-init-section-numbers)
8569 (while (setq line (pop lines))
8570 ;; Remove the quoted HTML tags.
8571 (setq line (org-html-expand-for-ascii line))
8572 (cond
8573 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8574 ;; a Headline
8575 (setq level (- (match-end 1) (match-beginning 1))
8576 txt (match-string 2 line))
8577 (org-ascii-level-start level txt umax))
8578 (t (insert line "\n"))))
8579 (normal-mode)
8580 (save-buffer)
8581 (goto-char (point-min))))
8582
8583 (defun org-search-todo-below (line lines level)
8584 "Search the subtree below LINE for any TODO entries."
8585 (let ((rest (cdr (memq line lines)))
8586 (re org-todo-line-regexp)
8587 line lv todo)
8588 (catch 'exit
8589 (while (setq line (pop rest))
8590 (if (string-match re line)
8591 (progn
8592 (setq lv (- (match-end 1) (match-beginning 1))
8593 todo (and (match-beginning 2)
8594 (not (equal (match-string 2 line)
8595 org-done-string))))
8596 ; TODO, not DONE
8597 (if (<= lv level) (throw 'exit nil))
8598 (if todo (throw 'exit t))))))))
8599
8600 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8601 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8602 (defun org-html-expand-for-ascii (line)
8603 "Handle quoted HTML for ASCII export."
8604 (if org-export-html-expand
8605 (while (string-match "@<[^<>\n]*>" line)
8606 ;; We just remove the tags for now.
8607 (setq line (replace-match "" nil nil line))))
8608 line)
8609
8610 (defun org-insert-centered (s &optional underline)
8611 "Insert the string S centered and underline it with character UNDERLINE."
8612 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8613 (insert (make-string ind ?\ ) s "\n")
8614 (if underline
8615 (insert (make-string ind ?\ )
8616 (make-string (length s) underline)
8617 "\n"))))
8618
8619 (defun org-ascii-level-start (level title umax)
8620 "Insert a new level in ASCII export."
8621 (let (char)
8622 (if (> level umax)
8623 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8624 (if (or (not (equal (char-before) ?\n))
8625 (not (equal (char-before (1- (point))) ?\n)))
8626 (insert "\n"))
8627 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8628 (if org-export-with-section-numbers
8629 (setq title (concat (org-section-number level) " " title)))
8630 (insert title "\n" (make-string (string-width title) char) "\n"))))
8631
8632 (defun org-export-copy-visible ()
8633 "Copy the visible part of the buffer to another buffer, for printing.
8634 Also removes the first line of the buffer if it specifies a mode,
8635 and all options lines."
8636 (interactive)
8637 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8638 ".txt"))
8639 (buffer (find-file-noselect filename))
8640 (ore (concat
8641 (org-make-options-regexp
8642 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8643 "STARTUP" "ARCHIVE"
8644 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8645 (if org-noutline-p "\\(\n\\|$\\)" "")))
8646 s e)
8647 (with-current-buffer buffer
8648 (erase-buffer)
8649 (text-mode))
8650 (save-excursion
8651 (setq s (goto-char (point-min)))
8652 (while (not (= (point) (point-max)))
8653 (goto-char (org-find-invisible))
8654 (append-to-buffer buffer s (point))
8655 (setq s (goto-char (org-find-visible)))))
8656 (switch-to-buffer-other-window buffer)
8657 (newline)
8658 (goto-char (point-min))
8659 (if (looking-at ".*-\\*- mode:.*\n")
8660 (replace-match ""))
8661 (while (re-search-forward ore nil t)
8662 (replace-match ""))
8663 (goto-char (point-min))))
8664
8665 (defun org-find-visible ()
8666 (if (featurep 'noutline)
8667 (let ((s (point)))
8668 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8669 (get-char-property s 'invisible)))
8670 s)
8671 (skip-chars-forward "^\n")
8672 (point)))
8673 (defun org-find-invisible ()
8674 (if (featurep 'noutline)
8675 (let ((s (point)))
8676 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8677 (not (get-char-property s 'invisible))))
8678 s)
8679 (skip-chars-forward "^\r")
8680 (point)))
8681
8682 ;; HTML
8683
8684 (defun org-get-current-options ()
8685 "Return a string with current options as keyword options.
8686 Does include HTML export options as well as TODO and CATEGORY stuff."
8687 (format
8688 "#+TITLE: %s
8689 #+AUTHOR: %s
8690 #+EMAIL: %s
8691 #+LANGUAGE: %s
8692 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8693 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8694 #+CATEGORY: %s
8695 #+SEQ_TODO: %s
8696 #+TYP_TODO: %s
8697 #+STARTUP: %s %s
8698 #+ARCHIVE: %s
8699 "
8700 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8701 org-export-headline-levels
8702 org-export-with-section-numbers
8703 org-export-with-toc
8704 org-export-preserve-breaks
8705 org-export-html-expand
8706 org-export-with-fixed-width
8707 org-export-with-tables
8708 org-export-with-sub-superscripts
8709 org-export-with-emphasize
8710 org-export-with-TeX-macros
8711 (file-name-nondirectory (buffer-file-name))
8712 (if (equal org-todo-interpretation 'sequence)
8713 (mapconcat 'identity org-todo-keywords " ")
8714 "TODO FEEDBACK VERIFY DONE")
8715 (if (equal org-todo-interpretation 'type)
8716 (mapconcat 'identity org-todo-keywords " ")
8717 "Me Jason Marie DONE")
8718 (cdr (assoc org-startup-folded
8719 '((nil . "nofold")(t . "fold")(content . "content"))))
8720 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8721 org-archive-location
8722 ))
8723
8724 (defun org-insert-export-options-template ()
8725 "Insert into the buffer a template with information for exporting."
8726 (interactive)
8727 (if (not (bolp)) (newline))
8728 (let ((s (org-get-current-options)))
8729 (and (string-match "#\\+CATEGORY" s)
8730 (setq s (substring s 0 (match-beginning 0))))
8731 (insert s)))
8732
8733 (defun org-toggle-fixed-width-section (arg)
8734 "Toggle the fixed-width export.
8735 If there is no active region, the QUOTE keyword at the current headline is
8736 inserted or removed. When present, it causes the text between this headline
8737 and the next to be exported as fixed-width text, and unmodified.
8738 If there is an active region, this command adds or removes a colon as the
8739 first character of this line. If the first character of a line is a colon,
8740 this line is also exported in fixed-width font."
8741 (interactive "P")
8742 (let* ((cc 0)
8743 (regionp (org-region-active-p))
8744 (beg (if regionp (region-beginning) (point)))
8745 (end (if regionp (region-end)))
8746 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8747 (re "[ \t]*\\(:\\)")
8748 off)
8749 (if regionp
8750 (save-excursion
8751 (goto-char beg)
8752 (setq cc (current-column))
8753 (beginning-of-line 1)
8754 (setq off (looking-at re))
8755 (while (> nlines 0)
8756 (setq nlines (1- nlines))
8757 (beginning-of-line 1)
8758 (cond
8759 (arg
8760 (move-to-column cc t)
8761 (insert ":\n")
8762 (forward-line -1))
8763 ((and off (looking-at re))
8764 (replace-match "" t t nil 1))
8765 ((not off) (move-to-column cc t) (insert ":")))
8766 (forward-line 1)))
8767 (save-excursion
8768 (org-back-to-heading)
8769 (if (looking-at (concat outline-regexp
8770 "\\( +\\<" org-quote-string "\\>\\)"))
8771 (replace-match "" t t nil 1)
8772 (if (looking-at outline-regexp)
8773 (progn
8774 (goto-char (match-end 0))
8775 (insert " " org-quote-string))))))))
8776
8777 (defun org-export-as-html-and-open (arg)
8778 "Export the outline as HTML and immediately open it with a browser.
8779 If there is an active region, export only the region.
8780 The prefix ARG specifies how many levels of the outline should become
8781 headlines. The default is 3. Lower levels will become bulleted lists."
8782 (interactive "P")
8783 (org-export-as-html arg 'hidden)
8784 (org-open-file (buffer-file-name)))
8785
8786 (defun org-export-as-html-batch ()
8787 "Call `org-export-as-html', may be used in batch processing as
8788 emacs --batch
8789 --load=$HOME/lib/emacs/org.el
8790 --eval \"(setq org-export-headline-levels 2)\"
8791 --visit=MyFile --funcall org-export-as-html-batch"
8792 (org-export-as-html org-export-headline-levels 'hidden))
8793
8794 (defun org-export-as-html (arg &optional hidden)
8795 "Export the outline as a pretty HTML file.
8796 If there is an active region, export only the region.
8797 The prefix ARG specifies how many levels of the outline should become
8798 headlines. The default is 3. Lower levels will become bulleted lists."
8799 (interactive "P")
8800 (setq-default org-todo-line-regexp org-todo-line-regexp)
8801 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8802 (setq-default org-done-string org-done-string)
8803 (let* ((region-p (org-region-active-p))
8804 (region
8805 (buffer-substring
8806 (if region-p (region-beginning) (point-min))
8807 (if region-p (region-end) (point-max))))
8808 (all_lines
8809 (org-skip-comments (org-split-string region "[\r\n]")))
8810 (lines (org-export-find-first-heading-line all_lines))
8811 (level 0) (line "") (origline "") txt todo
8812 (umax nil)
8813 (filename (concat (file-name-sans-extension (buffer-file-name))
8814 ".html"))
8815 (buffer (find-file-noselect filename))
8816 (levels-open (make-vector org-level-max nil))
8817 (date (format-time-string "%Y/%m/%d" (current-time)))
8818 (time (format-time-string "%X" (current-time)))
8819 (author user-full-name)
8820 (title (buffer-name))
8821 (options nil)
8822 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
8823 (inquote nil)
8824 (email user-mail-address)
8825 (language org-export-default-language)
8826 (text nil)
8827 (lang-words nil)
8828 (head-count 0) cnt
8829 (start 0)
8830 table-open type
8831 table-buffer table-orig-buffer
8832 )
8833 (message "Exporting...")
8834
8835 (setq org-last-level 1)
8836 (org-init-section-numbers)
8837
8838 ;; Search for the export key lines
8839 (org-parse-key-lines)
8840 (setq lang-words (or (assoc language org-export-language-setup)
8841 (assoc "en" org-export-language-setup)))
8842
8843 ;; Switch to the output buffer
8844 (if (or hidden (not org-export-html-show-new-buffer))
8845 (set-buffer buffer)
8846 (switch-to-buffer-other-window buffer))
8847 (erase-buffer)
8848 (fundamental-mode)
8849 (let ((case-fold-search nil))
8850 (if options (org-parse-export-options options))
8851 (setq umax (if arg (prefix-numeric-value arg)
8852 org-export-headline-levels))
8853
8854 ;; File header
8855 (insert (format
8856 "<html lang=\"%s\"><head>
8857 <title>%s</title>
8858 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8859 <meta name=generator content=\"Org-mode\">
8860 <meta name=generated content=\"%s %s\">
8861 <meta name=author content=\"%s\">
8862 </head><body>
8863 "
8864 language (org-html-expand title) date time author))
8865 (if title (insert (concat "<H1 align=\"center\">"
8866 (org-html-expand title) "</H1>\n")))
8867 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8868 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8869 email "&gt;</a>\n")))
8870 (if (or author email) (insert "<br>\n"))
8871 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8872 date " " time "<br>\n")))
8873 (if text (insert (concat "<p>\n" (org-html-expand text))))
8874 (if org-export-with-toc
8875 (progn
8876 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8877 (insert "<ul>\n")
8878 (mapcar '(lambda (line)
8879 (if (string-match org-todo-line-regexp line)
8880 ;; This is a headline
8881 (progn
8882 (setq level (- (match-end 1) (match-beginning 1))
8883 txt (save-match-data
8884 (org-html-expand
8885 (match-string 3 line)))
8886 todo
8887 (or (and (match-beginning 2)
8888 (not (equal (match-string 2 line)
8889 org-done-string)))
8890 ; TODO, not DONE
8891 (and (= level umax)
8892 (org-search-todo-below
8893 line lines level))))
8894 (if org-export-with-section-numbers
8895 (setq txt (concat (org-section-number level)
8896 " " txt)))
8897 (if (<= level umax)
8898 (progn
8899 (setq head-count (+ head-count 1))
8900 (if (> level org-last-level)
8901 (progn
8902 (setq cnt (- level org-last-level))
8903 (while (>= (setq cnt (1- cnt)) 0)
8904 (insert "<ul>"))
8905 (insert "\n")))
8906 (if (< level org-last-level)
8907 (progn
8908 (setq cnt (- org-last-level level))
8909 (while (>= (setq cnt (1- cnt)) 0)
8910 (insert "</ul>"))
8911 (insert "\n")))
8912 (insert
8913 (format
8914 (if todo
8915 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8916 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8917 head-count txt))
8918 (setq org-last-level level))
8919 ))))
8920 lines)
8921 (while (> org-last-level 0)
8922 (setq org-last-level (1- org-last-level))
8923 (insert "</ul>\n"))
8924 ))
8925 (setq head-count 0)
8926 (org-init-section-numbers)
8927
8928 (while (setq line (pop lines) origline line)
8929 ;; end of quote?
8930 (when (and inquote (string-match "^\\*+" line))
8931 (insert "</pre>\n")
8932 (setq inquote nil))
8933 ;; inquote
8934 (if inquote
8935 (progn
8936 (insert line "\n")
8937 (setq line (org-html-expand line))) ;;????? FIXME: not needed?
8938
8939 ;; Protect the links
8940 (setq start 0)
8941 (while (string-match org-link-maybe-angles-regexp line start)
8942 (setq start (match-end 0))
8943 (setq line (replace-match
8944 (concat "\000" (match-string 1 line) "\000")
8945 t t line)))
8946
8947 ;; replace "<" and ">" by "&lt;" and "&gt;"
8948 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8949 (setq line (org-html-expand line))
8950
8951 ;; Verbatim lines
8952 (if (and org-export-with-fixed-width
8953 (string-match "^[ \t]*:\\(.*\\)" line))
8954 (progn
8955 (let ((l (match-string 1 line)))
8956 (while (string-match " " l)
8957 (setq l (replace-match "&nbsp;" t t l)))
8958 (insert "\n<span style='font-family:Courier'>"
8959 l "</span>"
8960 (if (and lines
8961 (not (string-match "^[ \t]+\\(:.*\\)"
8962 (car lines))))
8963 "<br>\n" "\n"))))
8964
8965 (setq start 0)
8966 (while (string-match org-protected-link-regexp line start)
8967 (setq start (- (match-end 0) 2))
8968 (setq type (match-string 1 line))
8969 (cond
8970 ((member type '("http" "https" "ftp" "mailto" "news"))
8971 ;; standard URL
8972 (setq line (replace-match
8973 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8974 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8975 nil nil line)))
8976 ((string= type "file")
8977 ;; FILE link
8978 (let* ((filename (match-string 2 line))
8979 (abs-p (file-name-absolute-p filename))
8980 (thefile (if abs-p (expand-file-name filename) filename))
8981 (thefile (save-match-data
8982 (if (string-match ":[0-9]+$" thefile)
8983 (replace-match "" t t thefile)
8984 thefile)))
8985 (file-is-image-p
8986 (save-match-data
8987 (string-match (org-image-file-name-regexp) thefile))))
8988 (setq line (replace-match
8989 (if (and org-export-html-inline-images
8990 file-is-image-p)
8991 (concat "<img src=\"" thefile "\"/>")
8992 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8993 nil nil line))))
8994
8995 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8996 (setq line (replace-match
8997 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
8998
8999 ;; TODO items
9000 (if (and (string-match org-todo-line-regexp line)
9001 (match-beginning 2))
9002 (if (equal (match-string 2 line) org-done-string)
9003 (setq line (replace-match
9004 "<span style='color:green'>\\2</span>"
9005 nil nil line 2))
9006 (setq line (replace-match "<span style='color:red'>\\2</span>"
9007 nil nil line 2))))
9008
9009 ;; DEADLINES
9010 (if (string-match org-deadline-line-regexp line)
9011 (progn
9012 (if (save-match-data
9013 (string-match "<a href"
9014 (substring line 0 (match-beginning 0))))
9015 nil ; Don't do the replacement - it is inside a link
9016 (setq line (replace-match "<span style='color:red'>\\&</span>"
9017 nil nil line 1)))))
9018
9019
9020 (cond
9021 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9022 ;; This is a headline
9023 (setq level (- (match-end 1) (match-beginning 1))
9024 txt (match-string 2 line))
9025 (if (<= level umax) (setq head-count (+ head-count 1)))
9026 (org-html-level-start level txt umax
9027 (and org-export-with-toc (<= level umax))
9028 head-count)
9029 ;; QUOTES
9030 (when (string-match quote-re line)
9031 (insert "<pre>")
9032 (setq inquote t)))
9033
9034 ((and org-export-with-tables
9035 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9036 (if (not table-open)
9037 ;; New table starts
9038 (setq table-open t table-buffer nil table-orig-buffer nil))
9039 ;; Accumulate lines
9040 (setq table-buffer (cons line table-buffer)
9041 table-orig-buffer (cons origline table-orig-buffer))
9042 (when (or (not lines)
9043 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9044 (car lines))))
9045 (setq table-open nil
9046 table-buffer (nreverse table-buffer)
9047 table-orig-buffer (nreverse table-orig-buffer))
9048 (insert (org-format-table-html table-buffer table-orig-buffer))))
9049 (t
9050 ;; Normal lines
9051 ;; Lines starting with "-", and empty lines make new paragraph.
9052 ;; FIXME: Should we add + and *?
9053 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
9054 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9055 )))
9056 (if org-export-html-with-timestamp
9057 (insert org-export-html-html-helper-timestamp))
9058 (insert "</body>\n</html>\n")
9059 (normal-mode)
9060 (save-buffer)
9061 (goto-char (point-min)))))
9062
9063 (defun org-format-table-html (lines olines)
9064 "Find out which HTML converter to use and return the HTML code."
9065 (if (string-match "^[ \t]*|" (car lines))
9066 ;; A normal org table
9067 (org-format-org-table-html lines)
9068 ;; Table made by table.el - test for spanning
9069 (let* ((hlines (delq nil (mapcar
9070 (lambda (x)
9071 (if (string-match "^[ \t]*\\+-" x) x
9072 nil))
9073 lines)))
9074 (first (car hlines))
9075 (ll (and (string-match "\\S-+" first)
9076 (match-string 0 first)))
9077 (re (concat "^[ \t]*" (regexp-quote ll)))
9078 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9079 hlines))))
9080 (if (and (not spanning)
9081 (not org-export-prefer-native-exporter-for-tables))
9082 ;; We can use my own converter with HTML conversions
9083 (org-format-table-table-html lines)
9084 ;; Need to use the code generator in table.el, with the original text.
9085 (org-format-table-table-html-using-table-generate-source olines)))))
9086
9087 (defun org-format-org-table-html (lines)
9088 "Format a table into html."
9089 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9090 (setq lines (nreverse lines))
9091 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9092 (setq lines (nreverse lines))
9093 (let ((head (and org-export-highlight-first-table-line
9094 (delq nil (mapcar
9095 (lambda (x) (string-match "^[ \t]*|-" x))
9096 (cdr lines)))))
9097 line fields html)
9098 (setq html (concat org-export-html-table-tag "\n"))
9099 (while (setq line (pop lines))
9100 (catch 'next-line
9101 (if (string-match "^[ \t]*|-" line)
9102 (progn
9103 (setq head nil) ;; head ends here, first time around
9104 ;; ignore this line
9105 (throw 'next-line t)))
9106 ;; Break the line into fields
9107 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9108 (setq html (concat
9109 html
9110 "<tr>"
9111 (mapconcat (lambda (x)
9112 (if head
9113 (concat "<th>" x "</th>")
9114 (concat "<td valign=\"top\">" x "</td>")))
9115 fields "")
9116 "</tr>\n"))))
9117 (setq html (concat html "</table>\n"))
9118 html))
9119
9120 (defun org-fake-empty-table-line (line)
9121 "Replace everything except \"|\" with spaces."
9122 (let ((i (length line))
9123 (newstr (copy-sequence line)))
9124 (while (> i 0)
9125 (setq i (1- i))
9126 (if (not (eq (aref newstr i) ?|))
9127 (aset newstr i ?\ )))
9128 newstr))
9129
9130 (defun org-format-table-table-html (lines)
9131 "Format a table generated by table.el into html.
9132 This conversion does *not* use `table-generate-source' from table.el.
9133 This has the advantage that Org-mode's HTML conversions can be used.
9134 But it has the disadvantage, that no cell- or row-spanning is allowed."
9135 (let (line field-buffer
9136 (head org-export-highlight-first-table-line)
9137 fields html empty)
9138 (setq html (concat org-export-html-table-tag "\n"))
9139 (while (setq line (pop lines))
9140 (setq empty "&nbsp")
9141 (catch 'next-line
9142 (if (string-match "^[ \t]*\\+-" line)
9143 (progn
9144 (if field-buffer
9145 (progn
9146 (setq html (concat
9147 html
9148 "<tr>"
9149 (mapconcat
9150 (lambda (x)
9151 (if (equal x "") (setq x empty))
9152 (if head
9153 (concat "<th valign=\"top\">" x
9154 "</th>\n")
9155 (concat "<td valign=\"top\">" x
9156 "</td>\n")))
9157 field-buffer "\n")
9158 "</tr>\n"))
9159 (setq head nil)
9160 (setq field-buffer nil)))
9161 ;; Ignore this line
9162 (throw 'next-line t)))
9163 ;; Break the line into fields and store the fields
9164 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9165 (if field-buffer
9166 (setq field-buffer (mapcar
9167 (lambda (x)
9168 (concat x "<br>" (pop fields)))
9169 field-buffer))
9170 (setq field-buffer fields))))
9171 (setq html (concat html "</table>\n"))
9172 html))
9173
9174 (defun org-format-table-table-html-using-table-generate-source (lines)
9175 "Format a table into html, using `table-generate-source' from table.el.
9176 This has the advantage that cell- or row-spanning is allowed.
9177 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9178 (require 'table)
9179 (with-current-buffer (get-buffer-create " org-tmp1 ")
9180 (erase-buffer)
9181 (insert (mapconcat 'identity lines "\n"))
9182 (goto-char (point-min))
9183 (if (not (re-search-forward "|[^+]" nil t))
9184 (error "Error processing table"))
9185 (table-recognize-table)
9186 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9187 (table-generate-source 'html " org-tmp2 ")
9188 (set-buffer " org-tmp2 ")
9189 (buffer-substring (point-min) (point-max))))
9190
9191 (defun org-html-expand (string)
9192 "Prepare STRING for HTML export. Applies all active conversions."
9193 ;; First check if there is a link in the line - if yes, apply conversions
9194 ;; only before the start of the link.
9195 (let* ((m (string-match org-link-regexp string))
9196 (s (if m (substring string 0 m) string))
9197 (r (if m (substring string m) "")))
9198 ;; convert < to &lt; and > to &gt;
9199 (while (string-match "<" s)
9200 (setq s (replace-match "&lt;" t t s)))
9201 (while (string-match ">" s)
9202 (setq s (replace-match "&gt;" t t s)))
9203 (if org-export-html-expand
9204 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
9205 (setq s (replace-match "<\\1>" nil nil s))))
9206 (if org-export-with-emphasize
9207 (setq s (org-export-html-convert-emphasize s)))
9208 (if org-export-with-sub-superscripts
9209 (setq s (org-export-html-convert-sub-super s)))
9210 (if org-export-with-TeX-macros
9211 (let ((start 0) wd ass)
9212 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9213 (setq wd (match-string 1 s))
9214 (if (setq ass (assoc wd org-html-entities))
9215 (setq s (replace-match (or (cdr ass)
9216 (concat "&" (car ass) ";"))
9217 t t s))
9218 (setq start (+ start (length wd)))))))
9219 (concat s r)))
9220
9221 (defun org-create-multibrace-regexp (left right n)
9222 "Create a regular expression which will match a balanced sexp.
9223 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9224 as single character strings.
9225 The regexp returned will match the entire expression including the
9226 delimiters. It will also define a single group which contains the
9227 match except for the outermost delimiters. The maximum depth of
9228 stacked delimiters is N. Escaping delimiters is not possible."
9229 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9230 (or "\\|")
9231 (re nothing)
9232 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9233 (while (> n 1)
9234 (setq n (1- n)
9235 re (concat re or next)
9236 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9237 (concat left "\\(" re "\\)" right)))
9238
9239 (defvar org-match-substring-regexp
9240 (concat
9241 "\\([^\\]\\)\\([_^]\\)\\("
9242 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9243 "\\|"
9244 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9245 "\\|"
9246 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9247 "The regular expression matching a sub- or superscript.")
9248
9249 (defun org-export-html-convert-sub-super (string)
9250 "Convert sub- and superscripts in STRING to HTML."
9251 (let (key c)
9252 (while (string-match org-match-substring-regexp string)
9253 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9254 (setq c (or (match-string 8 string)
9255 (match-string 6 string)
9256 (match-string 5 string)))
9257 (setq string (replace-match
9258 (concat (match-string 1 string)
9259 "<" key ">" c "</" key ">")
9260 t t string)))
9261 (while (string-match "\\\\\\([_^]\\)" string)
9262 (setq string (replace-match (match-string 1 string) t t string))))
9263 string)
9264
9265 (defun org-export-html-convert-emphasize (string)
9266 (while (string-match
9267 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9268 string)
9269 (setq string (replace-match
9270 (concat "<b>" (match-string 3 string) "</b>")
9271 t t string 2)))
9272 (while (string-match
9273 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9274 string)
9275 (setq string (replace-match
9276 (concat "<i>" (match-string 3 string) "</i>")
9277 t t string 2)))
9278 (while (string-match
9279 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9280 string)
9281 (setq string (replace-match
9282 (concat "<u>" (match-string 3 string) "</u>")
9283 t t string 2)))
9284 string)
9285
9286 (defun org-parse-key-lines ()
9287 "Find the special key lines with the information for exporters."
9288 (save-excursion
9289 (goto-char 0)
9290 (let ((re (org-make-options-regexp
9291 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9292 key)
9293 (while (re-search-forward re nil t)
9294 (setq key (match-string 1))
9295 (cond ((string-equal key "TITLE")
9296 (setq title (match-string 2)))
9297 ((string-equal key "AUTHOR")
9298 (setq author (match-string 2)))
9299 ((string-equal key "EMAIL")
9300 (setq email (match-string 2)))
9301 ((string-equal key "LANGUAGE")
9302 (setq language (match-string 2)))
9303 ((string-equal key "TEXT")
9304 (setq text (concat text "\n" (match-string 2))))
9305 ((string-equal key "OPTIONS")
9306 (setq options (match-string 2))))))))
9307
9308 (defun org-parse-export-options (s)
9309 "Parse the export options line."
9310 (let ((op '(("H" . org-export-headline-levels)
9311 ("num" . org-export-with-section-numbers)
9312 ("toc" . org-export-with-toc)
9313 ("\\n" . org-export-preserve-breaks)
9314 ("@" . org-export-html-expand)
9315 (":" . org-export-with-fixed-width)
9316 ("|" . org-export-with-tables)
9317 ("^" . org-export-with-sub-superscripts)
9318 ("*" . org-export-with-emphasize)
9319 ("TeX" . org-export-with-TeX-macros)))
9320 o)
9321 (while (setq o (pop op))
9322 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9323 s)
9324 (set (make-local-variable (cdr o))
9325 (car (read-from-string (match-string 1 s))))))))
9326
9327 (defun org-html-level-start (level title umax with-toc head-count)
9328 "Insert a new level in HTML export."
9329 (let ((l (1+ (max level umax))))
9330 (while (<= l org-level-max)
9331 (if (aref levels-open (1- l))
9332 (progn
9333 (org-html-level-close l)
9334 (aset levels-open (1- l) nil)))
9335 (setq l (1+ l)))
9336 (if (> level umax)
9337 (progn
9338 (if (aref levels-open (1- level))
9339 (insert "<li>" title "<p>\n")
9340 (aset levels-open (1- level) t)
9341 (insert "<ul><li>" title "<p>\n")))
9342 (if org-export-with-section-numbers
9343 (setq title (concat (org-section-number level) " " title)))
9344 (setq level (+ level 1))
9345 (if with-toc
9346 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9347 level head-count title level))
9348 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9349
9350 (defun org-html-level-close (&rest args)
9351 "Terminate one level in HTML export."
9352 (insert "</ul>"))
9353
9354
9355 ;; Variable holding the vector with section numbers
9356 (defvar org-section-numbers (make-vector org-level-max 0))
9357
9358 (defun org-init-section-numbers ()
9359 "Initialize the vector for the section numbers."
9360 (let* ((level -1)
9361 (numbers (nreverse (org-split-string "" "\\.")))
9362 (depth (1- (length org-section-numbers)))
9363 (i depth) number-string)
9364 (while (>= i 0)
9365 (if (> i level)
9366 (aset org-section-numbers i 0)
9367 (setq number-string (or (car numbers) "0"))
9368 (if (string-match "\\`[A-Z]\\'" number-string)
9369 (aset org-section-numbers i
9370 (- (string-to-char number-string) ?A -1))
9371 (aset org-section-numbers i (string-to-number number-string)))
9372 (pop numbers))
9373 (setq i (1- i)))))
9374
9375 (defun org-section-number (&optional level)
9376 "Return a string with the current section number.
9377 When LEVEL is non-nil, increase section numbers on that level."
9378 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9379 (when level
9380 (when (> level -1)
9381 (aset org-section-numbers
9382 level (1+ (aref org-section-numbers level))))
9383 (setq idx (1+ level))
9384 (while (<= idx depth)
9385 (if (not (= idx 1))
9386 (aset org-section-numbers idx 0))
9387 (setq idx (1+ idx))))
9388 (setq idx 0)
9389 (while (<= idx depth)
9390 (setq n (aref org-section-numbers idx))
9391 (setq string (concat string (if (not (string= string "")) "." "")
9392 (int-to-string n)))
9393 (setq idx (1+ idx)))
9394 (save-match-data
9395 (if (string-match "\\`\\([@0]\\.\\)+" string)
9396 (setq string (replace-match "" nil nil string)))
9397 (if (string-match "\\(\\.0\\)+\\'" string)
9398 (setq string (replace-match "" nil nil string))))
9399 string))
9400
9401
9402 ;;; Key bindings
9403
9404 ;; - Bindings in Org-mode map are currently
9405 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9406 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9407 ;; e (?) useful from outline-mode
9408 ;; i k @ expendable from outline-mode
9409 ;; 0123456789 ! %^& ()_{} " `' free
9410
9411 ;; TAB key with modifiers
9412 (define-key org-mode-map "\C-i" 'org-cycle)
9413 (define-key org-mode-map [(meta tab)] 'org-complete)
9414 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
9415 ;; The following line is necessary under Suse GNU/Linux
9416 (unless org-xemacs-p
9417 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9418 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9419
9420 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9421 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
9422 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9423 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
9424 (define-key org-mode-map [(meta return)] 'org-meta-return)
9425 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
9426 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
9427
9428 ;; Cursor keys with modifiers
9429 (define-key org-mode-map [(meta left)] 'org-metaleft)
9430 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
9431 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
9432 (define-key org-mode-map [(meta right)] 'org-metaright)
9433 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
9434 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
9435 (define-key org-mode-map [(meta up)] 'org-metaup)
9436 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
9437 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
9438 (define-key org-mode-map [(meta down)] 'org-metadown)
9439 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
9440 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
9441
9442 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9443 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
9444 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9445 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
9446 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9447 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
9448 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9449 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
9450 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9451 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
9452 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9453 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
9454 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9455 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-timestamp-down-day)
9456 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9457 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-timestamp-up-day)
9458
9459 ;; All the other keys
9460 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9461 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9462 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9463 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9464 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9465 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9466 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9467 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9468 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9469 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9470 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9471 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9472 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9473 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9474 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9475 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
9476 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9477 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9478 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9479 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9480 (define-key org-mode-map "\C-c[" 'org-add-file)
9481 (define-key org-mode-map "\C-c]" 'org-remove-file)
9482 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9483 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9484 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9485 (define-key org-mode-map "\C-m" 'org-return)
9486 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9487 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9488 (define-key org-mode-map "\C-c+" 'org-table-sum)
9489 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9490 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9491 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9492 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9493 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9494 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9495 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9496 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9497 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9498 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9499 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9500 ;; OPML support is only planned
9501 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9502 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9503 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9504 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9505 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9506 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
9507 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
9508
9509 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
9510 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
9511 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
9512
9513 (defsubst org-table-p () (org-at-table-p))
9514
9515 (defun org-self-insert-command (N)
9516 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9517 If the cursor is in a table looking at whitespace, the whitespace is
9518 overwritten, and the table is not marked as requiring realignment."
9519 (interactive "p")
9520 (if (and (org-table-p)
9521 (or
9522 (and org-table-auto-blank-field
9523 (member last-command
9524 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
9525 (org-table-blank-field))
9526 t)
9527 (eq N 1)
9528 (looking-at "[^|\n]* +|"))
9529 (let (org-table-may-need-update)
9530 (goto-char (1- (match-end 0)))
9531 (delete-backward-char 1)
9532 (goto-char (match-beginning 0))
9533 (self-insert-command N))
9534 (setq org-table-may-need-update t)
9535 (self-insert-command N)))
9536
9537 ;; FIXME:
9538 ;; The following two functions might still be optimized to trigger
9539 ;; re-alignment less frequently.
9540
9541 (defun org-delete-backward-char (N)
9542 "Like `delete-backward-char', insert whitespace at field end in tables.
9543 When deleting backwards, in tables this function will insert whitespace in
9544 front of the next \"|\" separator, to keep the table aligned. The table will
9545 still be marked for re-alignment, because a narrow field may lead to a
9546 reduced column width."
9547 (interactive "p")
9548 (if (and (org-table-p)
9549 (eq N 1)
9550 (string-match "|" (buffer-substring (point-at-bol) (point)))
9551 (looking-at ".*?|"))
9552 (let ((pos (point)))
9553 (backward-delete-char N)
9554 (skip-chars-forward "^|")
9555 (insert " ")
9556 (goto-char (1- pos)))
9557 (backward-delete-char N)))
9558
9559 (defun org-delete-char (N)
9560 "Like `delete-char', but insert whitespace at field end in tables.
9561 When deleting characters, in tables this function will insert whitespace in
9562 front of the next \"|\" separator, to keep the table aligned. The table
9563 will still be marked for re-alignment, because a narrow field may lead to
9564 a reduced column width."
9565 (interactive "p")
9566 (if (and (org-table-p)
9567 (not (bolp))
9568 (not (= (char-after) ?|))
9569 (eq N 1))
9570 (if (looking-at ".*?|")
9571 (let ((pos (point)))
9572 (replace-match (concat
9573 (substring (match-string 0) 1 -1)
9574 " |"))
9575 (goto-char pos)))
9576 (delete-char N)))
9577
9578 ;; How to do this: Measure non-white length of current string
9579 ;; If equal to column width, we should realign.
9580
9581 (defun org-remap (map &rest commands)
9582 "In MAP, remap the functions given in COMMANDS.
9583 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
9584 (let (new old)
9585 (while commands
9586 (setq old (pop commands) new (pop commands))
9587 (if (fboundp 'command-remapping)
9588 (define-key map (vector 'remap old) new)
9589 (substitute-key-definition old new map global-map)))))
9590
9591 (when (eq org-enable-table-editor 'optimized)
9592 ;; If the user wants maximum table support, we need to hijack
9593 ;; some standard editing functions
9594 (org-remap org-mode-map
9595 'self-insert-command 'org-self-insert-command
9596 'delete-char 'org-delete-char
9597 'delete-backward-char 'org-delete-backward-char)
9598 (define-key org-mode-map "|" 'org-force-self-insert))
9599
9600 (defun org-shiftcursor-error ()
9601 "Throw an error because Shift-Cursor command was applied in wrong context."
9602 (error "This command is only active in tables and on headlines"))
9603
9604 (defun org-shifttab ()
9605 "Global visibility cycling or move to previous table field.
9606 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
9607 See the individual commands for more information."
9608 (interactive)
9609 (cond
9610 ((org-at-table-p) (org-table-previous-field))
9611 (t (org-cycle '(4)))))
9612
9613 (defun org-shiftmetaleft ()
9614 "Promote subtree or delete table column.
9615 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
9616 See the individual commands for more information."
9617 (interactive)
9618 (cond
9619 ((org-at-table-p) (org-table-delete-column))
9620 ((org-on-heading-p) (org-promote-subtree))
9621 (t (org-shiftcursor-error))))
9622
9623 (defun org-shiftmetaright ()
9624 "Demote subtree or insert table column.
9625 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
9626 See the individual commands for more information."
9627 (interactive)
9628 (cond
9629 ((org-at-table-p) (org-table-insert-column))
9630 ((org-on-heading-p) (org-demote-subtree))
9631 (t (org-shiftcursor-error))))
9632
9633 (defun org-shiftmetaup (&optional arg)
9634 "Move subtree up or kill table row.
9635 Calls `org-move-subtree-up' or `org-table-kill-row', depending on context.
9636 See the individual commands for more information."
9637 (interactive "P")
9638 (cond
9639 ((org-at-table-p) (org-table-kill-row))
9640 ((org-on-heading-p) (org-move-subtree-up arg))
9641 (t (org-shiftcursor-error))))
9642 (defun org-shiftmetadown (&optional arg)
9643 "Move subtree down or insert table row.
9644 Calls `org-move-subtree-down' or `org-table-insert-row', depending on context.
9645 See the individual commands for more information."
9646 (interactive "P")
9647 (cond
9648 ((org-at-table-p) (org-table-insert-row arg))
9649 ((org-on-heading-p) (org-move-subtree-down arg))
9650 (t (org-shiftcursor-error))))
9651
9652 (defun org-metaleft (&optional arg)
9653 "Promote heading or move table column to left.
9654 Calls `org-do-promote' or `org-table-move-column', depending on context.
9655 See the individual commands for more information."
9656 (interactive "P")
9657 (cond
9658 ((org-at-table-p) (org-table-move-column 'left))
9659 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9660 (t (backward-word (prefix-numeric-value arg)))))
9661
9662 (defun org-metaright (&optional arg)
9663 "Demote subtree or move table column to right.
9664 Calls `org-do-demote' or `org-table-move-column', depending on context.
9665 See the individual commands for more information."
9666 (interactive "P")
9667 (cond
9668 ((org-at-table-p) (org-table-move-column nil))
9669 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9670 (t (forward-word (prefix-numeric-value arg)))))
9671
9672 (defun org-metaup (&optional arg)
9673 "Move subtree up or move table row up.
9674 Calls `org-move-subtree-up' or `org-table-move-row', depending on context.
9675 See the individual commands for more information."
9676 (interactive "P")
9677 (cond
9678 ((org-at-table-p) (org-table-move-row 'up))
9679 ((org-on-heading-p) (org-move-subtree-up arg))
9680 (t (org-shiftcursor-error))))
9681
9682 (defun org-metadown (&optional arg)
9683 "Move subtree down or move table row down.
9684 Calls `org-move-subtree-down' or `org-table-move-row', depending on context.
9685 See the individual commands for more information."
9686 (interactive "P")
9687 (cond
9688 ((org-at-table-p) (org-table-move-row nil))
9689 ((org-on-heading-p) (org-move-subtree-down arg))
9690 (t (org-shiftcursor-error))))
9691
9692 (defun org-shiftup (&optional arg)
9693 "Increase item in timestamp or increase priority of current item.
9694 Calls `org-timestamp-up' or `org-priority-up', depending on context.
9695 See the individual commands for more information."
9696 (interactive "P")
9697 (cond
9698 ((org-at-timestamp-p) (org-timestamp-up arg))
9699 (t (org-priority-up))))
9700
9701 (defun org-shiftdown (&optional arg)
9702 "Decrease item in timestamp or decrease priority of current item.
9703 Calls `org-timestamp-down' or `org-priority-down', depending on context.
9704 See the individual commands for more information."
9705 (interactive "P")
9706 (cond
9707 ((org-at-timestamp-p) (org-timestamp-down arg))
9708 (t (org-priority-down))))
9709
9710 (defun org-copy-special ()
9711 "Copy region in table or copy current subtree.
9712 Calls `org-table-copy' or `org-copy-subtree', depending on context.
9713 See the individual commands for more information."
9714 (interactive)
9715 (call-interactively
9716 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9717
9718 (defun org-cut-special ()
9719 "Cut region in table or cut current subtree.
9720 Calls `org-table-copy' or `org-cut-subtree', depending on context.
9721 See the individual commands for more information."
9722 (interactive)
9723 (call-interactively
9724 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9725
9726 (defun org-paste-special (arg)
9727 "Paste rectangular region into table, or past subtree relative to level.
9728 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
9729 See the individual commands for more information."
9730 (interactive "P")
9731 (if (org-at-table-p)
9732 (org-table-paste-rectangle)
9733 (org-paste-subtree arg)))
9734
9735 (defun org-ctrl-c-ctrl-c (&optional arg)
9736 "Call realign table, or recognize a table.el table, or update keywords.
9737 When the cursor is inside a table created by the table.el package,
9738 activate that table. Otherwise, if the cursor is at a normal table
9739 created with org.el, re-align that table. This command works even if
9740 the automatic table editor has been turned off.
9741 If the cursor is in one of the special #+KEYWORD lines, this triggers
9742 scanning the buffer for these lines and updating the information.
9743 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
9744 (interactive "P")
9745 (let ((org-enable-table-editor t))
9746 (cond
9747 ((org-at-table.el-p)
9748 (require 'table)
9749 (beginning-of-line 1)
9750 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9751 (table-recognize-table))
9752 ((org-at-table-p)
9753 (org-table-maybe-eval-formula)
9754 (if arg
9755 (org-table-recalculate t)
9756 (org-table-maybe-recalculate-line))
9757 (org-table-align))
9758 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9759 (cond
9760 ((equal (match-string 1) "TBLFM")
9761 ;; Recalculate the table before this line
9762 (save-excursion
9763 (beginning-of-line 1)
9764 (skip-chars-backward " \r\n\t")
9765 (if (org-at-table-p) (org-table-recalculate t))))
9766 (t
9767 (org-mode-restart))))
9768 ((org-region-active-p)
9769 (org-table-convert-region (region-beginning) (region-end) arg))
9770 ((and (region-beginning) (region-end))
9771 (if (y-or-n-p "Convert inactive region to table? ")
9772 (org-table-convert-region (region-beginning) (region-end) arg)
9773 (error "Abort")))
9774 (t (error "No table at point, and no region to make one")))))
9775
9776 (defun org-mode-restart ()
9777 "Restart Org-mode, to scan again for special lines.
9778 Also updates the keyword regular expressions."
9779 (interactive)
9780 (let ((org-inhibit-startup t)) (org-mode))
9781 (message "Org-mode restarted to refresh keyword and special line setup"))
9782
9783 (defun org-return ()
9784 "Goto next table row or insert a newline.
9785 Calls `org-table-next-row' or `newline', depending on context.
9786 See the individual commands for more information."
9787 (interactive)
9788 (cond
9789 ((org-at-table-p)
9790 (org-table-justify-field-maybe)
9791 (org-table-next-row))
9792 (t (newline))))
9793
9794 (defun org-meta-return (&optional arg)
9795 "Insert a new heading or wrap a region in a table.
9796 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
9797 See the individual commands for more information."
9798 (interactive "P")
9799 (cond
9800 ((org-at-table-p)
9801 (org-table-wrap-region arg))
9802 (t (org-insert-heading))))
9803
9804 ;;; Menu entries
9805
9806 ;; Define the Org-mode menus
9807 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9808 '("Tbl"
9809 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9810 ["Next Field" org-cycle (org-at-table-p)]
9811 ["Previous Field" org-shifttab (org-at-table-p)]
9812 ["Next Row" org-return (org-at-table-p)]
9813 "--"
9814 ["Blank Field" org-table-blank-field (org-at-table-p)]
9815 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9816 "--"
9817 ("Column"
9818 ["Move Column Left" org-metaleft (org-at-table-p)]
9819 ["Move Column Right" org-metaright (org-at-table-p)]
9820 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9821 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9822 ("Row"
9823 ["Move Row Up" org-metaup (org-at-table-p)]
9824 ["Move Row Down" org-metadown (org-at-table-p)]
9825 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9826 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9827 "--"
9828 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9829 ("Rectangle"
9830 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9831 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9832 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9833 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9834 "--"
9835 ("Calculate"
9836 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
9837 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9838 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
9839 "--"
9840 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9841 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9842 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9843 "--"
9844 ["Sum Column/Rectangle" org-table-sum
9845 (or (org-at-table-p) (org-region-active-p))]
9846 ["Which Column?" org-table-current-column (org-at-table-p)])
9847 ["Debug Formulas"
9848 (setq org-table-formula-debug (not org-table-formula-debug))
9849 :style toggle :selected org-table-formula-debug]
9850 "--"
9851 ["Invisible Vlines" org-table-toggle-vline-visibility
9852 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9853 "--"
9854 ["Create" org-table-create (and (not (org-at-table-p))
9855 org-enable-table-editor)]
9856 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9857 ["Import from File" org-table-import (not (org-at-table-p))]
9858 ["Export to File" org-table-export (org-at-table-p)]
9859 "--"
9860 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9861
9862 (easy-menu-define org-org-menu org-mode-map "Org menu"
9863 '("Org"
9864 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9865 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
9866 ["Sparse Tree" org-occur t]
9867 ["Show All" show-all t]
9868 "--"
9869 ["New Heading" org-insert-heading t]
9870 ("Navigate Headings"
9871 ["Up" outline-up-heading t]
9872 ["Next" outline-next-visible-heading t]
9873 ["Previous" outline-previous-visible-heading t]
9874 ["Next Same Level" outline-forward-same-level t]
9875 ["Previous Same Level" outline-backward-same-level t]
9876 "--"
9877 ["Jump" org-goto t])
9878 ("Edit Structure"
9879 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9880 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9881 "--"
9882 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9883 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9884 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9885 "--"
9886 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9887 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9888 ["Demote Heading" org-metaright (not (org-at-table-p))]
9889 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9890 "--"
9891 ["Archive Subtree" org-archive-subtree t])
9892 "--"
9893 ("TODO Lists"
9894 ["TODO/DONE/-" org-todo t]
9895 ["Show TODO Tree" org-show-todo-tree t]
9896 "--"
9897 ["Set Priority" org-priority t]
9898 ["Priority Up" org-shiftup t]
9899 ["Priority Down" org-shiftdown t])
9900 ("Dates and Scheduling"
9901 ["Timestamp" org-time-stamp t]
9902 ["Timestamp (inactive)" org-time-stamp-inactive t]
9903 ("Change Date"
9904 ["1 Day Later" org-timestamp-up-day t]
9905 ["1 Day Earlier" org-timestamp-down-day t]
9906 ["1 ... Later" org-shiftup t]
9907 ["1 ... Earlier" org-shiftdown t])
9908 ["Compute Time Range" org-evaluate-time-range t]
9909 ["Schedule Item" org-schedule t]
9910 ["Deadline" org-deadline t]
9911 "--"
9912 ["Goto Calendar" org-goto-calendar t]
9913 ["Date from Calendar" org-date-from-calendar t])
9914 "--"
9915 ("Timeline/Agenda"
9916 ["Show TODO Tree this File" org-show-todo-tree t]
9917 ["Check Deadlines this File" org-check-deadlines t]
9918 ["Timeline Current File" org-timeline t]
9919 "--"
9920 ["Agenda" org-agenda t])
9921 ("File List for Agenda")
9922 "--"
9923 ("Hyperlinks"
9924 ["Store Link (Global)" org-store-link t]
9925 ["Insert Link" org-insert-link t]
9926 ["Follow Link" org-open-at-point t])
9927 "--"
9928 ("Export"
9929 ["ASCII" org-export-as-ascii t]
9930 ["Extract Visible Text" org-export-copy-visible t]
9931 ["HTML" org-export-as-html t]
9932 ["HTML and Open" org-export-as-html-and-open t]
9933 ; ["OPML" org-export-as-opml nil]
9934 "--"
9935 ["Option Template" org-insert-export-options-template t]
9936 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9937 "--"
9938 ("Documentation"
9939 ["Show Version" org-version t]
9940 ["Info Documentation" org-info t])
9941 ("Customize"
9942 ["Browse Org Group" org-customize t]
9943 "--"
9944 ["Build Full Customize Menu" org-create-customize-menu
9945 (fboundp 'customize-menu-create)])
9946 "--"
9947 ["Refresh setup" org-mode-restart t]
9948 ))
9949
9950 (defun org-info (&optional node)
9951 "Read documentation for Org-mode in the info system.
9952 With optional NODE, go directly to that node."
9953 (interactive)
9954 (require 'info)
9955 (Info-goto-node (format "(org)%s" (or node ""))))
9956
9957 (defun org-install-agenda-files-menu ()
9958 (easy-menu-change
9959 '("Org") "File List for Agenda"
9960 (append
9961 (list
9962 ["Edit File List" (customize-variable 'org-agenda-files) t]
9963 ["Add Current File to List" org-add-file t]
9964 ["Remove Current File from List" org-remove-file t]
9965 "--")
9966 (mapcar 'org-file-menu-entry org-agenda-files))))
9967
9968 ;;; Documentation
9969
9970 (defun org-customize ()
9971 "Call the customize function with org as argument."
9972 (interactive)
9973 (customize-browse 'org))
9974
9975 (defun org-create-customize-menu ()
9976 "Create a full customization menu for Org-mode, insert it into the menu."
9977 (interactive)
9978 (if (fboundp 'customize-menu-create)
9979 (progn
9980 (easy-menu-change
9981 '("Org") "Customize"
9982 `(["Browse Org group" org-customize t]
9983 "--"
9984 ,(customize-menu-create 'org)
9985 ["Set" Custom-set t]
9986 ["Save" Custom-save t]
9987 ["Reset to Current" Custom-reset-current t]
9988 ["Reset to Saved" Custom-reset-saved t]
9989 ["Reset to Standard Settings" Custom-reset-standard t]))
9990 (message "\"Org\"-menu now contains full customization menu"))
9991 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9992
9993 ;;; Miscellaneous stuff
9994
9995 (defun org-move-line-down (arg)
9996 "Move the current line down. With prefix argument, move it past ARG lines."
9997 (interactive "p")
9998 (let ((col (current-column))
9999 beg end pos)
10000 (beginning-of-line 1) (setq beg (point))
10001 (beginning-of-line 2) (setq end (point))
10002 (beginning-of-line (+ 1 arg))
10003 (setq pos (move-marker (make-marker) (point)))
10004 (insert (delete-and-extract-region beg end))
10005 (goto-char pos)
10006 (move-to-column col)))
10007
10008 (defun org-move-line-up (arg)
10009 "Move the current line up. 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 (- 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 ;; Functions needed for Emacs/XEmacs region compatibility
10022
10023 (defun org-region-active-p ()
10024 "Is `transient-mark-mode' on and the region active?
10025 Works on both Emacs and XEmacs."
10026 (if org-ignore-region
10027 nil
10028 (if org-xemacs-p
10029 (and zmacs-regions (region-active-p))
10030 (and transient-mark-mode mark-active))))
10031
10032 (defun org-add-to-invisibility-spec (arg)
10033 "Add elements to `buffer-invisibility-spec'.
10034 See documentation for `buffer-invisibility-spec' for the kind of elements
10035 that can be added."
10036 (cond
10037 ((fboundp 'add-to-invisibility-spec)
10038 (add-to-invisibility-spec arg))
10039 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
10040 (setq buffer-invisibility-spec (list arg)))
10041 (t
10042 (setq buffer-invisibility-spec
10043 (cons arg buffer-invisibility-spec)))))
10044
10045 (defun org-remove-from-invisibility-spec (arg)
10046 "Remove elements from `buffer-invisibility-spec'."
10047 (if (fboundp 'remove-from-invisibility-spec)
10048 (remove-from-invisibility-spec arg)
10049 (if (consp buffer-invisibility-spec)
10050 (setq buffer-invisibility-spec
10051 (delete arg buffer-invisibility-spec)))))
10052
10053 (defun org-in-invisibility-spec-p (arg)
10054 "Is ARG a member of `buffer-invisibility-spec'?."
10055 (if (consp buffer-invisibility-spec)
10056 (member arg buffer-invisibility-spec)
10057 nil))
10058
10059 (defun org-image-file-name-regexp ()
10060 "Return regexp matching the file names of images."
10061 (if (fboundp 'image-file-name-regexp)
10062 (image-file-name-regexp)
10063 (let ((image-file-name-extensions
10064 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
10065 "xbm" "xpm" "pbm" "pgm" "ppm")))
10066 (concat "\\."
10067 (regexp-opt (nconc (mapcar 'upcase
10068 image-file-name-extensions)
10069 image-file-name-extensions)
10070 t)
10071 "\\'"))))
10072
10073 ;; Functions needed for compatibility with old outline.el
10074
10075 ;; The following functions capture almost the entire compatibility code
10076 ;; between the different versions of outline-mode. The only other place
10077 ;; where this is important are the font-lock-keywords. Search for
10078 ;; `org-noutline-p' to find it.
10079
10080 ;; C-a should go to the beginning of a *visible* line, also in the
10081 ;; new outline.el. I guess this should be patched into Emacs?
10082 (defun org-beginning-of-line ()
10083 "Go to the beginning of the current line. If that is invisible, continue
10084 to a visible line beginning. This makes the function of C-a more intuitive."
10085 (interactive)
10086 (beginning-of-line 1)
10087 (if (bobp)
10088 nil
10089 (backward-char 1)
10090 (if (org-invisible-p)
10091 (while (and (not (bobp)) (org-invisible-p))
10092 (backward-char 1)
10093 (beginning-of-line 1))
10094 (forward-char 1))))
10095 (when org-noutline-p
10096 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
10097
10098 (defun org-invisible-p ()
10099 "Check if point is at a character currently not visible."
10100 (if org-noutline-p
10101 ;; Early versions of noutline don't have `outline-invisible-p'.
10102 (if (fboundp 'outline-invisible-p)
10103 (outline-invisible-p)
10104 (get-char-property (point) 'invisible))
10105 (save-excursion
10106 (skip-chars-backward "^\r\n")
10107 (equal (char-before) ?\r))))
10108
10109 (defun org-back-to-heading (&optional invisible-ok)
10110 "Move to previous heading line, or beg of this line if it's a heading.
10111 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
10112 (if org-noutline-p
10113 (outline-back-to-heading invisible-ok)
10114 (if (looking-at outline-regexp)
10115 t
10116 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
10117 outline-regexp)
10118 nil t)
10119 (if invisible-ok
10120 (progn (goto-char (match-end 1))
10121 (looking-at outline-regexp)))
10122 (error "Before first heading")))))
10123
10124 (defun org-on-heading-p (&optional invisible-ok)
10125 "Return t if point is on a (visible) heading line.
10126 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
10127 (if org-noutline-p
10128 (outline-on-heading-p 'invisible-ok)
10129 (save-excursion
10130 (skip-chars-backward "^\n\r")
10131 (and (looking-at outline-regexp)
10132 (or invisible-ok
10133 (bobp)
10134 (equal (char-before) ?\n))))))
10135
10136 (defun org-up-heading-all (arg)
10137 "Move to the heading line of which the present line is a subheading.
10138 This function considers both visible and invisible heading lines.
10139 With argument, move up ARG levels."
10140 (if org-noutline-p
10141 (if (fboundp 'outline-up-heading-all)
10142 (outline-up-heading-all arg) ; emacs 21 version of outline.el
10143 (outline-up-heading arg t)) ; emacs 22 version of outline.el
10144 (org-back-to-heading t)
10145 (looking-at outline-regexp)
10146 (if (<= (- (match-end 0) (match-beginning 0)) arg)
10147 (error "Cannot move up %d levels" arg)
10148 (re-search-backward
10149 (concat "[\n\r]" (regexp-quote
10150 (make-string (- (match-end 0) (match-beginning 0) arg)
10151 ?*))
10152 "[^*]"))
10153 (forward-char 1))))
10154
10155 (defun org-show-hidden-entry ()
10156 "Show an entry where even the heading is hidden."
10157 (save-excursion
10158 (if (not org-noutline-p)
10159 (progn
10160 (org-back-to-heading t)
10161 (org-flag-heading nil)))
10162 (org-show-entry)))
10163
10164 (defun org-check-occur-regexp (regexp)
10165 "If REGEXP starts with \"^\", modify it to check for \\r as well.
10166 Of course, only for the old outline mode."
10167 (if org-noutline-p
10168 regexp
10169 (if (string-match "^\\^" regexp)
10170 (concat "[\n\r]" (substring regexp 1))
10171 regexp)))
10172
10173 (defun org-flag-heading (flag &optional entry)
10174 "Flag the current heading. FLAG non-nil means make invisible.
10175 When ENTRY is non-nil, show the entire entry."
10176 (save-excursion
10177 (org-back-to-heading t)
10178 (if (not org-noutline-p)
10179 ;; Make the current headline visible
10180 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
10181 ;; Check if we should show the entire entry
10182 (if entry
10183 (progn
10184 (org-show-entry)
10185 (save-excursion ;; FIXME: Is this the fix for points in the -|
10186 ;; middle of text? |
10187 (and (outline-next-heading) ;; |
10188 (org-flag-heading nil)))) ; show the next heading _|
10189 (outline-flag-region (max 1 (1- (point)))
10190 (save-excursion (outline-end-of-heading) (point))
10191 (if org-noutline-p
10192 flag
10193 (if flag ?\r ?\n))))))
10194
10195 (defun org-show-subtree ()
10196 "Show everything after this heading at deeper levels."
10197 (outline-flag-region
10198 (point)
10199 (save-excursion
10200 (outline-end-of-subtree) (outline-next-heading) (point))
10201 (if org-noutline-p nil ?\n)))
10202
10203 (defun org-show-entry ()
10204 "Show the body directly following this heading.
10205 Show the heading too, if it is currently invisible."
10206 (interactive)
10207 (save-excursion
10208 (org-back-to-heading t)
10209 (outline-flag-region
10210 (1- (point))
10211 (save-excursion
10212 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
10213 (or (match-beginning 1) (point-max)))
10214 (if org-noutline-p nil ?\n))))
10215
10216
10217 (defun org-make-options-regexp (kwds)
10218 "Make a regular expression for keyword lines."
10219 (concat
10220 (if org-noutline-p "^" "[\n\r]")
10221 "#?[ \t]*\\+\\("
10222 (mapconcat 'regexp-quote kwds "\\|")
10223 "\\):[ \t]*"
10224 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10225
10226 ;; Make `bookmark-jump' show the jump location if it was hidden.
10227 (eval-after-load "bookmark"
10228 '(if (boundp 'bookmark-after-jump-hook)
10229 ;; We can use the hook
10230 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
10231 ;; Hook not available, use advice
10232 (defadvice bookmark-jump (after org-make-visible activate)
10233 "Make the position visible."
10234 (org-bookmark-jump-unhide))))
10235
10236 (defun org-bookmark-jump-unhide ()
10237 "Unhide the current position, to show the bookmark location."
10238 (and (eq major-mode 'org-mode)
10239 (or (org-invisible-p)
10240 (save-excursion (goto-char (max (point-min) (1- (point))))
10241 (org-invisible-p)))
10242 (org-show-hierarchy-above)))
10243
10244 ;;; Finish up
10245
10246 (provide 'org)
10247
10248 (run-hooks 'org-load-hook)
10249
10250 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10251 ;;; org.el ends here