]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-agenda-start-on-weekday, org-calendar-to-agenda-key,
[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.12
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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, 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.12
84 ;; - Tables can store formulas (one per column) and compute fields.
85 ;; Not quite like a full spreadsheet, but very powerful.
86 ;; - table.el keybinding is now `C-c ~'.
87 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
88 ;; - Small changes to keys in agenda buffer. Affected keys:
89 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
90 ;; - Bug fixes.
91 ;;
92 ;; Version 3.11
93 ;; - Links inserted with C-c C-l are now by default enclosed in angle
94 ;; brackets. See the new variable `org-link-format'.
95 ;; - ">" terminates a link, this is a way to have several links in a line.
96 ;; Both "<" and ">" are no longer allowed as characters in a link.
97 ;; - Archiving of finished tasks.
98 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
99 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
100 ;; - Compatibility problems with viper-mode fixed.
101 ;; - Improved html export of tables.
102 ;; - Various clean-up changes.
103 ;;
104 ;; Version 3.10
105 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
106 ;;
107 ;; Version 3.09
108 ;; - Time-of-day specifications in agenda are extracted and placed
109 ;; into the prefix. Timed entries can be placed into a time grid for
110 ;; day.
111 ;;
112 ;; Version 3.08
113 ;; - "|" no longer allowed as part of a link, to allow links in tables.
114 ;; - The prefix of items in the agenda buffer can be configured.
115 ;; - Cleanup.
116 ;;
117 ;; Version 3.07
118 ;; - Some folding incinsistencies removed.
119 ;; - BBDB links to company-only entries.
120 ;; - Bug fixes and global cleanup.
121 ;;
122 ;; Version 3.06
123 ;; - M-S-RET inserts a new TODO heading.
124 ;; - New startup option `content'.
125 ;; - Better visual response when TODO items in agenda change status.
126 ;; - Window positioning after visibility state changes optimized and made
127 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
128 ;;
129 ;; Version 3.05
130 ;; - Agenda entries from the diary are linked to the diary file, so
131 ;; adding and editing diary entries can be done directly from the agenda.
132 ;; - Many calendar/diary commands available directly from agenda.
133 ;; - Field copying in tables with S-RET does increment.
134 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
135 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
136 ;;
137 ;; Version 3.04
138 ;; - Table editor optimized to need fewer realignments, and to keep
139 ;; table shape when typing in fields.
140 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
141 ;; into arbitrary major modes.
142 ;; - Fixed bug with realignment in XEmacs.
143 ;; - Startup options can be set with special #+STARTUP line.
144 ;; - Heading following a match in org-occur can be suppressed.
145 ;;
146 ;; Version 3.03
147 ;; - Copyright transfer to the FSF.
148 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
149 ;; - Timeline now always contains today, and `.' jumps to it.
150 ;; - Table editor:
151 ;; - cut and paste of rectangular regions in tables
152 ;; - command to convert org-mode table to table.el table and back
153 ;; - command to treat several cells like a paragraph and fill it
154 ;; - command to convert a buffer region to a table
155 ;; - import/export tables as tab-separated files (exchange with Excel)
156 ;; - Agenda:
157 ;; - Sorting mechanism for agenda items rewritten from scratch.
158 ;; - Sorting fully configurable.
159 ;; - Entries specifying a time are sorted together.
160 ;; - Completion also covers option keywords after `#-'.
161 ;; - Bug fixes.
162 ;;
163 ;; Version 3.01
164 ;; - New reference card, thanks to Philip Rooke for creating it.
165 ;; - Single file agenda renamed to "Timeline". It no longer shows
166 ;; warnings about upcoming deadlines/overdue scheduled items.
167 ;; That functionality is now limited to the (multifile) agenda.
168 ;; - When reading a date, the calendar can be manipulated with keys.
169 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
170 ;; - Minor bug fixes and documentation improvements.
171
172 ;;; Code:
173
174 (eval-when-compile (require 'cl) (require 'calendar))
175 (require 'outline)
176 (require 'time-date)
177 (require 'easymenu)
178
179 ;;; Customization variables
180
181 (defvar org-version "3.12"
182 "The version number of the file org.el.")
183 (defun org-version ()
184 (interactive)
185 (message "Org-mode version %s" org-version))
186
187 ;; The following two constants are for compatibility with different Emacs
188 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
189 ;; The compatibility code in org.el is based on these two constants.
190 (defconst org-xemacs-p (featurep 'xemacs)
191 "Are we running xemacs?")
192 (defconst org-noutline-p (featurep 'noutline)
193 "Are we using the new outline mode?")
194
195 (defgroup org nil
196 "Outline-based notes management and organizer "
197 :tag "Org"
198 :group 'outlines
199 :group 'hypermedia
200 :group 'calendar)
201
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
204 :tag "Org Startup"
205 :group 'org)
206
207 (defcustom org-CUA-compatible nil
208 "Non-nil means use alternative key bindings for S-<cursor movement>.
209 Org-mode used S-<cursor movement> for changing timestamps and priorities.
210 S-<cursor movement> is also used for example by `CUA-mode' to select text.
211 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
212 alternative bindings. Setting this variable to t will replace the following
213 keys both in Org-mode and in the Org-agenda buffer.
214
215 S-RET -> C-S-RET
216 S-up -> M-p
217 S-down -> M-n
218 S-left -> M--
219 S-right -> M-+
220
221 If you do not like the alternative keys, take a look at the variable
222 `org-disputed-keys'.
223
224 This option is only relevant at load-time of Org-mode. Changing it requires
225 a restart of Emacs to become effective."
226 :group 'org-startup
227 :type 'boolean)
228
229 (defvar org-disputed-keys
230 '((S-up [(shift up)] [(meta ?p)])
231 (S-down [(shift down)] [(meta ?n)])
232 (S-left [(shift left)] [(meta ?-)])
233 (S-right [(shift right)] [(meta ?+)])
234 (S-return [(shift return)] [(control shift return)]))
235 "Keys for which Org-mode and other modes compete.
236 This is an alist, cars are symbols for lookup, 1st element is the default key,
237 second element will be used when `org-CUA-compatible' is t.")
238
239 (defun org-key (key)
240 "Select a key according to `org-CUA-compatible'."
241 (nth (if org-CUA-compatible 2 1)
242 (or (assq key org-disputed-keys)
243 (error "Invalid Key %s in `org-key'" key))))
244
245 (defcustom org-startup-folded t
246 "Non-nil means, entering Org-mode will switch to OVERVIEW.
247 This can also be configured on a per-file basis by adding one of
248 the following lines anywhere in the buffer:
249
250 #+STARTUP: fold
251 #+STARTUP: nofold
252 #+STARTUP: content"
253 :group 'org-startup
254 :type '(choice
255 (const :tag "nofold: show all" nil)
256 (const :tag "fold: overview" t)
257 (const :tag "content: all headlines" content)))
258
259 (defcustom org-startup-truncated t
260 "Non-nil means, entering Org-mode will set `truncate-lines'.
261 This is useful since some lines containing links can be very long and
262 uninteresting. Also tables look terrible when wrapped."
263 :group 'org-startup
264 :type 'boolean)
265
266 (defcustom org-startup-with-deadline-check nil
267 "Non-nil means, entering Org-mode will run the deadline check.
268 This means, if you start editing an org file, you will get an
269 immediate reminder of any due deadlines.
270 This can also be configured on a per-file basis by adding one of
271 the following lines anywhere in the buffer:
272
273 #+STARTUP: dlcheck
274 #+STARTUP: nodlcheck"
275 :group 'org-startup
276 :type 'boolean)
277
278 (defcustom org-insert-mode-line-in-empty-file nil
279 "Non-nil means insert the first line setting Org-mode in empty files.
280 When the function `org-mode' is called interactively in an empty file, this
281 normally means that the file name does not automatically trigger Org-mode.
282 To ensure that the file will always be in Org-mode in the future, a
283 line enforcing Org-mode will be inserted into the buffer, if this option
284 has been set."
285 :group 'org-startup
286 :type 'boolean)
287
288 (defgroup org-keywords nil
289 "Options concerning TODO items in Org-mode."
290 :tag "Org Keywords"
291 :group 'org)
292
293 (defcustom org-todo-keywords '("TODO" "DONE")
294 "List of TODO entry keywords.
295 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
296 considered to mean that the entry is \"done\". All the other mean that
297 action is required, and will make the entry show up in todo lists, diaries
298 etc.
299 The command \\[org-todo] cycles an entry through these states, and an
300 additional state where no keyword is present. For details about this
301 cycling, see also the variable `org-todo-interpretation'
302 Changes become only effective after restarting Emacs."
303 :group 'org-keywords
304 :type '(repeat (string :tag "Keyword")))
305
306 (defcustom org-todo-interpretation 'sequence
307 "Controls how TODO keywords are interpreted.
308 \\<org-mode-map>Possible values are `sequence' and `type'.
309 This variable is only relevant if `org-todo-keywords' contains more than two
310 states. There are two ways how these keywords can be used:
311
312 - As a sequence in the process of working on a TODO item, for example
313 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
314 org-todo-interpretation 'sequence)
315
316 - As different types of TODO items, for example
317 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
318 org-todo-interpretation 'type)
319
320 When the states are interpreted as a sequence, \\[org-todo] always cycles
321 to the next state, in order to walk through all different states. So with
322 \\[org-todo], you turn an empty entry into the state TODO. When you started
323 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
324 later to VERIFY and finally to DONE.
325
326 When the states are interpreted as types, \\[org-todo] still cycles through
327 when it is called several times in direct succession, in order to initially
328 select the type. However, if not called immediately after a previous
329 \\[org-todo], it switches from each type directly to DONE. So with the
330 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
331 RELAXED. If you later return to this entry and press \\[org-todo] again,
332 RELAXED will not be changed REMIND, but directly to DONE.
333
334 You can create a large number of types. To initially select a
335 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
336 type with completion. Of course, you can also type the keyword
337 directly into the buffer. M-TAB completes TODO keywords at the
338 beginning of a headline."
339 :group 'org-keywords
340 :type '(choice (const sequence)
341 (const type)))
342
343 (defcustom org-default-priority ?B
344 "The default priority of TODO items.
345 This is the priority an item get if no explicit priority is given."
346 :group 'org-keywords
347 :type 'character)
348
349 (defcustom org-lowest-priority ?C
350 "The lowest priority of TODO items. A character like ?A, ?B etc."
351 :group 'org-keywords
352 :type 'character)
353
354 (defcustom org-deadline-string "DEADLINE:"
355 "String to mark deadline entries.
356 A deadline is this string, followed by a time stamp. Should be a word,
357 terminated by a colon. You can insert a schedule keyword and
358 a timestamp with \\[org-deadline].
359 Changes become only effective after restarting Emacs."
360 :group 'org-keywords
361 :type 'string)
362
363 (defcustom org-scheduled-string "SCHEDULED:"
364 "String to mark scheduled TODO entries.
365 A schedule is this string, followed by a time stamp. Should be a word,
366 terminated by a colon. You can insert a schedule keyword and
367 a timestamp with \\[org-schedule].
368 Changes become only effective after restarting Emacs."
369 :group 'org-keywords
370 :type 'string)
371
372 (defcustom org-comment-string "COMMENT"
373 "Entries starting with this keyword will never be exported.
374 An entry can be toggled between COMMENT and normal with
375 \\[org-toggle-comment].
376 Changes become only effective after restarting Emacs."
377 :group 'org-keywords
378 :type 'string)
379
380 (defcustom org-after-todo-state-change-hook nil
381 "Hook which is run after the state of a TODO item was changed.
382 The new state (a string with a todo keyword, or nil) is available in the
383 Lisp variable `state'."
384 :group 'org-keywords
385 :type 'hook)
386
387 ;; Variables for pre-computed regular expressions, all buffer local
388 (defvar org-todo-kwd-priority-p nil
389 "Do TODO items have priorities?")
390 (make-variable-buffer-local 'org-todo-kwd-priority-p)
391 (defvar org-todo-kwd-max-priority nil
392 "Maximum priority of TODO items.")
393 (make-variable-buffer-local 'org-todo-kwd-max-priority)
394 (defvar org-ds-keyword-length 12
395 "Maximum length of the Deadline and SCHEDULED keywords.")
396 (make-variable-buffer-local 'org-ds-keyword-length)
397 (defvar org-done-string nil
398 "The last string in `org-todo-keywords', indicating an item is DONE.")
399 (make-variable-buffer-local 'org-done-string)
400 (defvar org-todo-regexp nil
401 "Matches any of the TODO state keywords.")
402 (make-variable-buffer-local 'org-todo-regexp)
403 (defvar org-not-done-regexp nil
404 "Matches any of the TODO state keywords except the last one.")
405 (make-variable-buffer-local 'org-not-done-regexp)
406 (defvar org-todo-line-regexp nil
407 "Matches a headline and puts TODO state into group 2 if present.")
408 (make-variable-buffer-local 'org-todo-line-regexp)
409 (defvar org-nl-done-regexp nil
410 "Matches newline followed by a headline with the DONE keyword.")
411 (make-variable-buffer-local 'org-nl-done-regexp)
412 (defvar org-looking-at-done-regexp nil
413 "Matches the DONE keyword a point.")
414 (make-variable-buffer-local 'org-looking-at-done-regexp)
415 (defvar org-deadline-regexp nil
416 "Matches the DEADLINE keyword.")
417 (make-variable-buffer-local 'org-deadline-regexp)
418 (defvar org-deadline-time-regexp nil
419 "Matches the DEADLINE keyword together with a time stamp.")
420 (make-variable-buffer-local 'org-deadline-time-regexp)
421 (defvar org-deadline-line-regexp nil
422 "Matches the DEADLINE keyword and the rest of the line.")
423 (make-variable-buffer-local 'org-deadline-line-regexp)
424 (defvar org-scheduled-regexp nil
425 "Matches the SCHEDULED keyword.")
426 (make-variable-buffer-local 'org-scheduled-regexp)
427 (defvar org-scheduled-time-regexp nil
428 "Matches the SCHEDULED keyword together with a time stamp.")
429 (make-variable-buffer-local 'org-scheduled-time-regexp)
430
431 (defvar org-category nil
432 "Variable used by org files to set a category for agenda display.
433 Such files should use a file variable to set it, for example
434
435 -*- mode: org; org-category: \"ELisp\"
436
437 or contain a special line
438
439 #+CATEGORY: ELisp
440
441 If the file does not specify a category, then file's base name
442 is used instead.")
443
444 (defun org-set-regexps-and-options ()
445 "Precompute regular expressions for current buffer."
446 (when (eq major-mode 'org-mode)
447 (let ((re (org-make-options-regexp
448 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
449 "STARTUP" "ARCHIVE")))
450 (splitre "[ \t]+")
451 kwds int key value cat arch)
452 (save-excursion
453 (save-restriction
454 (widen)
455 (goto-char (point-min))
456 (while (re-search-forward re nil t)
457 (setq key (match-string 1) value (match-string 2))
458 (cond
459 ((equal key "CATEGORY")
460 (if (string-match "[ \t]+$" value)
461 (setq value (replace-match "" t t value)))
462 (setq cat (intern value)))
463 ((equal key "SEQ_TODO")
464 (setq int 'sequence
465 kwds (append kwds (org-split-string value splitre))))
466 ((equal key "PRI_TODO")
467 (setq int 'priority
468 kwds (append kwds (org-split-string value splitre))))
469 ((equal key "TYP_TODO")
470 (setq int 'type
471 kwds (append kwds (org-split-string value splitre))))
472 ((equal key "STARTUP")
473 (let ((opts (org-split-string value splitre))
474 (set '(("fold" org-startup-folded t)
475 ("nofold" org-startup-folded nil)
476 ("content" org-startup-folded content)
477 ("dlcheck" org-startup-with-deadline-check t)
478 ("nodlcheck" org-startup-with-deadline-check nil)))
479 l var val)
480 (while (setq l (assoc (pop opts) set))
481 (setq var (nth 1 l) val (nth 2 l))
482 (set (make-local-variable var) val))))
483 ((equal key "ARCHIVE")
484 (string-match " *$" value)
485 (setq arch (replace-match "" t t value))
486 (remove-text-properties 0 (length arch)
487 '(face t fontified t) arch)))
488 )))
489 (and cat (set (make-local-variable 'org-category) cat))
490 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
491 (and arch (set (make-local-variable 'org-archive-location) arch))
492 (and int (set (make-local-variable 'org-todo-interpretation) int)))
493 ;; Compute the regular expressions and other local variables
494 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
495 org-todo-kwd-max-priority (1- (length org-todo-keywords))
496 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
497 (length org-scheduled-string)))
498 org-done-string
499 (nth (1- (length org-todo-keywords)) org-todo-keywords)
500 org-todo-regexp
501 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
502 "\\|") "\\)\\>")
503 org-not-done-regexp
504 (concat "\\<\\("
505 (mapconcat 'regexp-quote
506 (nreverse (cdr (reverse org-todo-keywords)))
507 "\\|")
508 "\\)\\>")
509 org-todo-line-regexp
510 (concat "^\\(\\*+\\)[ \t]*\\("
511 (mapconcat 'regexp-quote org-todo-keywords "\\|")
512 "\\)? *\\(.*\\)")
513 org-nl-done-regexp
514 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
515 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
516 org-deadline-regexp (concat "\\<" org-deadline-string)
517 org-deadline-time-regexp
518 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
519 org-deadline-line-regexp
520 (concat "\\<\\(" org-deadline-string "\\).*")
521 org-scheduled-regexp
522 (concat "\\<" org-scheduled-string)
523 org-scheduled-time-regexp
524 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
525 (org-set-font-lock-defaults)))
526
527 (defgroup org-time nil
528 "Options concerning time stamps and deadlines in Org-mode."
529 :tag "Org Time"
530 :group 'org)
531
532 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
533 "Formats for `format-time-string' which are used for time stamps.
534 It is not recommended to change this constant.")
535
536
537 (defcustom org-deadline-warning-days 30
538 "No. of days before expiration during which a deadline becomes active.
539 This variable governs the display in the org file."
540 :group 'org-time
541 :type 'number)
542
543 (defcustom org-popup-calendar-for-date-prompt t
544 "Non-nil means, pop up a calendar when prompting for a date.
545 In the calendar, the date can be selected with mouse-1. However, the
546 minibuffer will also be active, and you can simply enter the date as well.
547 When nil, only the minibuffer will be available."
548 :group 'org-time
549 :type 'number)
550
551 (defcustom org-calendar-follow-timestamp-change t
552 "Non-nil means, make the calendar window follow timestamp changes.
553 When a timestamp is modified and the calendar window is visible, it will be
554 moved to the new date."
555 :group 'org-time
556 :type 'boolean)
557
558 (defgroup org-agenda nil
559 "Options concerning agenda display Org-mode."
560 :tag "Org Agenda"
561 :group 'org)
562
563 (defcustom org-agenda-files nil
564 "A list of org files for agenda/diary display.
565 Entries are added to this list with \\[org-add-file] and removed with
566 \\[org-remove-file]. You can also use customize to edit the list."
567 :group 'org-agenda
568 :type '(repeat file))
569
570 (defcustom org-select-timeline-window t
571 "Non-nil means, after creating a timeline, move cursor into Timeline window.
572 When nil, cursor will remain in the current window."
573 :group 'org-agenda
574 :type 'boolean)
575
576 (defcustom org-select-agenda-window t
577 "Non-nil means, after creating an agenda, move cursor into Agenda window.
578 When nil, cursor will remain in the current window."
579 :group 'org-agenda
580 :type 'boolean)
581
582 (defcustom org-fit-agenda-window t
583 "Non-nil means, change window size of agenda to fit content."
584 :group 'org-agenda
585 :type 'boolean)
586
587 (defcustom org-agenda-show-all-dates t
588 "Non-nil means, `org-agenda' shows every day in the selected range.
589 When nil, only the days which actually have entries are shown."
590 :group 'org-agenda
591 :type 'boolean)
592
593 ;; FIXME: First day of month works only for current month because it would
594 ;; require a variable ndays treatment.
595 (defcustom org-agenda-start-on-weekday 1
596 "Non-nil means, start the overview always on the specified weekday.
597 0 denotes Sunday, 1 denotes Monday etc.
598 When nil, always start on the current day."
599 :group 'org-agenda
600 :type '(choice (const :tag "Today" nil)
601 (const :tag "First day of month" t)
602 (number :tag "Weekday No.")))
603
604 (defcustom org-agenda-ndays 7
605 "Number of days to include in overview display."
606 :group 'org-agenda
607 :type 'number)
608
609 (defcustom org-agenda-include-all-todo t
610 "Non-nil means, the agenda will always contain all TODO entries.
611 When nil, date-less entries will only be shown if `org-agenda' is called
612 with a prefix argument.
613 When non-nil, the TODO entries will be listed at the top of the agenda, before
614 the entries for specific days."
615 :group 'org-agenda
616 :type 'boolean)
617
618 (defcustom org-agenda-include-diary nil
619 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
620 :group 'org-agenda
621 :type 'boolean)
622
623 (defcustom org-calendar-to-agenda-key [?c]
624 "The key to be installed in `calendar-mode-map' for switching to the agenda.
625 The command `org-calendar-goto-agenda' will be bound to this key. The
626 default is the character `c' because then `c' can be used to switch back and
627 forth between agenda and calendar."
628 :group 'org-agenda
629 :type 'sexp)
630
631 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
632 "Sorting structure for the agenda items of a single day.
633 This is a list of symbols which will be used in sequence to determine
634 if an entry should be listed before another entry. The following
635 symbols are recognized:
636
637 time-up Put entries with time-of-day indications first, early first
638 time-down Put entries with time-of-day indications first, late first
639 category-keep Keep the default order of categories, corresponding to the
640 sequence in `org-agenda-files'.
641 category-up Sort alphabetically by category, A-Z.
642 category-down Sort alphabetically by category, Z-A.
643 priority-up Sort numerically by priority, high priority last.
644 priority-down Sort numerically by priority, high priority first.
645
646 The different possibilities will be tried in sequence, and testing stops
647 if one comparison returns a \"not-equal\". For example, the default
648 '(time-up category-keep priority-down)
649 means: Pull out all entries having a specified time of day and sort them,
650 in order to make a time schedule for the current day the first thing in the
651 agenda listing for the day. Of the entries without a time indication, keep
652 the grouped in categories, don't sort the categories, but keep them in
653 the sequence given in `org-agenda-files'. Within each category sort by
654 priority.
655
656 Leaving out `category-keep' would mean that items will be sorted across
657 categories by priority."
658 :group 'org-agenda
659 :type '(repeat
660 (choice
661 (const time-up)
662 (const time-down)
663 (const category-keep)
664 (const category-up)
665 (const category-down)
666 (const priority-up)
667 (const priority-down))))
668
669 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
670 "Format specification for the prefix of items in the agenda buffer.
671 This format works similar to a printf format, with the following meaning:
672
673 %c the category of the item, \"Diary\" for entries from the diary, or
674 as given by the CATEGORY keyword or derived from the file name.
675 %t the time-of-day specification if one applies to the entry, in the
676 format HH:MM
677 %s Scheduling/Deadline information, a short string
678
679 All specifiers work basically like the standard `%s' of printf, but may
680 contain two additional characters: A question mark just after the `%' and
681 a whitespace/punctuation character just before the final letter.
682
683 If the first character after `%' is a question mark, the entire field
684 will only be included if the corresponding value applies to the
685 current entry. This is useful for fields which should have fixed
686 width when present, but zero width when absent. For example,
687 \"%?-12t\" will result in a 12 character time field if a time of the
688 day is specified, but will completely disappear in entries which do
689 not contain a time.
690
691 If there is punctuation or whitespace character just before the final
692 format letter, this character will be appended to the field value if
693 the value is not empty. For example, the format \"%-12:c\" leads to
694 \"Diary: \" if the category is \"Diary\". If the category were be
695 empty, no additional colon would be interted.
696
697 The default value of this option is \" %-12:c%?-12t% s\", meaning:
698 - Indent the line with two space characters
699 - Give the category in a 12 chars wide field, padded with whitespace on
700 the right (because of `-'). Append a colon if there is a category
701 (because of `:').
702 - If there is a time-of-day, put it into a 12 chars wide field. If no
703 time, don't put in an empty field, just skip it (because of '?').
704 - Finally, put the scheduling information and append a whitespace.
705
706 As another example, if you don't want the time-of-day of entries in
707 the prefix, you could use:
708
709 (setq org-agenda-prefix-format \" %-11:c% s\")
710
711 See also the variable `org-agenda-remove-times-when-in-prefix'."
712 :type 'string
713 :group 'org-agenda)
714
715 (defcustom org-timeline-prefix-format " % s"
716 "Like `org-agenda-prefix-format', but for the timeline of a single file."
717 :type 'string
718 :group 'org-agenda)
719
720 (defvar org-prefix-format-compiled nil
721 "The compiled version of the most recently used prefix format.
722 Depending on which command was used last, this may be the compiled version
723 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
724
725 (defcustom org-agenda-use-time-grid t
726 "Non-nil means, show a time grid in the agenda schedule.
727 A time grid is a set of lines for specific times (like every two hours between
728 8:00 and 20:00). The items scheduled for a day at specific times are
729 sorted in between these lines.
730 For details about when the grid will be shown, and what it will look like, see
731 the variable `org-agenda-time-grid'."
732 :group 'org-agenda
733 :type 'boolean)
734
735 (defcustom org-agenda-time-grid
736 '((daily today require-timed)
737 "----------------"
738 (800 1000 1200 1400 1600 1800 2000))
739
740 "The settings for time grid for agenda display.
741 This is a list of three items. The first item is again a list. It contains
742 symbols specifying conditions when the grid should be displayed:
743
744 daily if the agenda shows a single day
745 weekly if the agenda shows an entire week
746 today show grid on current date, independent of daily/weekly display
747 require-timed show grid only if at least on item has a time specification
748
749 The second item is a string which will be places behing the grid time.
750
751 The third item is a list of integers, indicating the times that should have
752 a grid line."
753 :group 'org-agenda
754 :type
755 '(list
756 (set :greedy t :tag "Grid Display Options"
757 (const :tag "Show grid in single day agenda display" daily)
758 (const :tag "Show grid in weekly agenda display" weekly)
759 (const :tag "Always show grid for today" today)
760 (const :tag "Show grid only if any timed entries are present"
761 require-timed)
762 (const :tag "Skip grid times already present in an entry"
763 remove-match))
764 (string :tag "Grid String")
765 (repeat :tag "Grid Times" (integer :tag "Time"))))
766
767 (defcustom org-agenda-remove-times-when-in-prefix t
768 "Non-nil means, remove duplicate time specifications in agenda items.
769 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
770 time-of-day specification in a headline or diary entry is extracted and
771 placed into the prefix. If this option is non-nil, the original specification
772 \(a timestamp or -range, or just a plain time(range) specification like
773 11:30-4pm) will be removed for agenda display. This makes the agenda less
774 cluttered.
775 The option can be t or nil. It may also be the symbol `beg', indicating
776 that the time should only be removed what it is located at the beginning of
777 the headline/diary entry."
778 :group 'org-agenda
779 :type '(choice
780 (const :tag "Always" t)
781 (const :tag "Never" nil)
782 (const :tag "When at beginning of entry" beg)))
783
784 (defcustom org-sort-agenda-notime-is-late t
785 "Non-nil means, items without time are considered late.
786 This is only relevant for sorting. When t, items which have no explicit
787 time like 15:30 will be considered as 24:01, i.e. later than any items which
788 do have a time. When nil, the default time is before 0:00. You can use this
789 option to decide if the schedule for today should come before or after timeless
790 agenda entries."
791 :group 'org-agenda
792 :type 'boolean)
793
794 (defgroup org-structure nil
795 "Options concerning structure editing in Org-mode."
796 :tag "Org Structure"
797 :group 'org)
798
799 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
800 "Hook that is run after `org-cycle' has changed the buffer visibility.
801 The function(s) in this hook must accept a single argument which indicates
802 the new state that was set by the most recent `org-cycle' command. The
803 argument is a symbol. After a global state change, it can have the values
804 `overview', `content', or `all'. After a local state change, it can have
805 the values `folded', `children', or `subtree'."
806 :group 'org-structure
807 :type 'hook)
808
809 (defcustom org-occur-hook '(org-first-headline-recenter)
810 "Hook that is run after `org-occur' has constructed a sparse tree.
811 This can be used to recenter the window to show as much of the structure
812 as possible."
813 :group 'org-structure
814 :type 'hook)
815
816 (defcustom org-adapt-indentation t
817 "Non-nil means, adapt indentation when promoting and demoting.
818 When this is set and the *entire* text in an entry is indented, the
819 indentation is increased by one space in a demotion command, and
820 decreased by one in a promotion command. If any line in the entry
821 body starts at column 0, indentation is not changed at all."
822 :group 'org-structure
823 :type 'boolean)
824
825 (defcustom org-cycle-emulate-tab t
826 "Where should `org-cycle' emulate TAB.
827 nil Never
828 white Only in completely white lines
829 t Everywhere except in headlines"
830 :group 'org-structure
831 :type '(choice (const :tag "Never" nil)
832 (const :tag "Only in completely white lines" white)
833 (const :tag "Everywhere except in headlines" t)
834 ))
835
836 (defcustom org-show-following-heading t
837 "Non-nil means, show heading following match in `org-occur'.
838 When doing an `org-occur' it is useful to show the headline which
839 follows the match, even if they do not match the regexp. This makes it
840 easier to edit directly inside the sparse tree. However, if you use
841 org-occur mainly as an overview, the following headlines are
842 unnecessary clutter."
843 :group 'org-structure
844 :type 'boolean)
845
846 (defcustom org-archive-location "%s_archive::"
847 "The location where subtrees should be archived.
848 This string consists of two parts, separated by a double-colon.
849
850 The first part is a file name - when omitted, archiving happens in the same
851 file. `%s' will be replaced by the current file name (without directory part).
852 Archiving to a different file is useful to keep archived entries from
853 contributing to the Org-mode Agenda.
854
855 The part after the double colon is a headline. The archived entries will be
856 filed under that headline. When omitted, the subtrees are simply filed away
857 at the end of the file, as top-level entries.
858
859 Here are a few examples:
860 \"%s_archive::\"
861 If the current file is Projects.org, archive in file
862 Projects.org_archive, as top-level trees. This is the default.
863
864 \"::* Archived Tasks\"
865 Archive in the current file, under the top-level headline
866 \"* Archived Tasks\".
867
868 \"~/org/archive.org::\"
869 Archive in file ~/org/archive.org (absolute path), as top-level trees.
870
871 \"basement::** Finished Tasks\"
872 Archive in file ./basement (relative path), as level 3 trees
873 below the level 2 heading \"** Finished Tasks\".
874
875 You may set this option on a per-file basis by adding to the buffer a
876 line like
877
878 #+ARCHIVE: basement::** Finished Tasks"
879 :group 'org-structure
880 :type 'string)
881
882 (defcustom org-archive-mark-done t
883 "Non-nil means, mark archived entries as DONE."
884 :group 'org-structure
885 :type 'boolean)
886
887 (defcustom org-archive-stamp-time t
888 "Non-nil means, add a time stamp to archived entries.
889 The time stamp will be added directly after the TODO state keyword in the
890 first line, so it is probably best to use this in combinations with
891 `org-archive-mark-done'."
892 :group 'org-structure
893 :type 'boolean)
894
895 (defgroup org-link nil
896 "Options concerning links in Org-mode."
897 :tag "Org Link"
898 :group 'org)
899
900 (defcustom org-link-format "<%s>"
901 "Default format for linkes in the buffer.
902 This is a format string for printf, %s will be replaced by the link text.
903 If you want to make sure that your link is always properly terminated,
904 include angle brackets into this format, like \"<%s>\". Some people also
905 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
906 :group 'org-link
907 :type '(choice
908 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
909 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
910 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
911 (string :tag "Other" :value "<%s>")))
912
913 (defcustom org-allow-space-in-links t
914 "Non-nil means, file names in links may contain space characters.
915 When nil, it becomes possible to put several links into a line.
916 Note that in tables, a link never extends accross fields, so in a table
917 it is always possible to put several links into a line.
918 Changing this variable requires a re-launch of Emacs to become effective."
919 :group 'org-link
920 :type 'boolean)
921
922 (defcustom org-line-numbers-in-file-links t
923 "Non-nil means, file links from `org-store-link' contain line numbers.
924 The line number will be added to the file name with :NNN and interpreted
925 by the command `org-open-at-point'.
926 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
927 negates this setting for the duration of the command."
928 :group 'org-link
929 :type 'boolean)
930
931 (defcustom org-keep-stored-link-after-insertion nil
932 "Non-nil means, keep link in list for entire session.
933
934 The command `org-store-link' adds a link pointing to the current
935 location to an internal list. These links accumulate during a session.
936 The command `org-insert-link' can be used to insert links into any
937 Org-mode file (offering completion for all stored links). When this
938 option is nil, every link which has been inserted once using \\[org-insert-link]
939 will be removed from the list, to make completing the unused links
940 more efficient."
941 :group 'org-link
942 :type 'boolean)
943
944 (defcustom org-link-frame-setup
945 '((vm . vm-visit-folder-other-frame)
946 (gnus . gnus-other-frame)
947 (file . find-file-other-window))
948 "Setup the frame configuration for following links.
949 When following a link with Emacs, it may often be useful to display
950 this link in another window or frame. This variable can be used to
951 set this up for the different types of links.
952 For VM, use any of
953 `vm-visit-folder'
954 `vm-visit-folder-other-frame'
955 For Gnus, use any of
956 `gnus'
957 `gnus-other-frame'
958 For FILE, use any of
959 `find-file'
960 `find-file-other-window'
961 `find-file-other-frame'
962 For the calendar, use the variable `calendar-setup'.
963 For BBDB, it is currently only possible to display the matches in
964 another window."
965 :group 'org-link
966 :type '(list
967 (cons (const vm)
968 (choice
969 (const vm-visit-folder)
970 (const vm-visit-folder-other-window)
971 (const vm-visit-folder-other-frame)))
972 (cons (const gnus)
973 (choice
974 (const gnus)
975 (const gnus-other-frame)))
976 (cons (const file)
977 (choice
978 (const find-file)
979 (const find-file-other-window)
980 (const find-file-other-frame)))))
981
982 (defcustom org-usenet-links-prefer-google nil
983 "Non-nil means, `org-store-link' will create web links to Google groups.
984 When nil, Gnus will be used for such links.
985 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
986 negates this setting for the duration of the command."
987 :group 'org-link
988 :type 'boolean)
989
990 (defcustom org-open-non-existing-files nil
991 "Non-nil means, `org-open-file' will open non-existing file.
992 When nil, an error will be generated."
993 :group 'org-link
994 :type 'boolean)
995
996 (defcustom org-confirm-shell-links t
997 "Non-nil means, ask for confirmation before executing shell links.
998 The default is true, to keep new users from shooting into their own foot."
999 :group 'org-link
1000 :type 'boolean)
1001
1002 (defconst org-file-apps-defaults-linux
1003 '((t . emacs)
1004 ("jpg" . "xv %s")
1005 ("gif" . "xv %s")
1006 ("ppm" . "xv %s")
1007 ("pgm" . "xv %s")
1008 ("pbm" . "xv %s")
1009 ("tif" . "xv %s")
1010 ("png" . "xv %s")
1011 ("ps" . "gv %s")
1012 ("ps.gz" . "gv %s")
1013 ("eps" . "gv %s")
1014 ("eps.gz" . "gv %s")
1015 ("dvi" . "xdvi %s")
1016 ("mpeg" . "plaympeg %s")
1017 ("mp3" . "plaympeg %s")
1018 ("fig" . "xfig %s")
1019 ("pdf" . "acroread %s")
1020 ("doc" . "soffice %s")
1021 ("ppt" . "soffice %s")
1022 ("pps" . "soffice %s")
1023 ("html" . "netscape -remote openURL(%s,new-window)")
1024 ("htm" . "netscape -remote openURL(%s,new-window)")
1025 ("xs" . "soffice %s"))
1026 "Default file applications on a UNIX/LINUX system.
1027 See `org-file-apps'.")
1028
1029 (defconst org-file-apps-defaults-macosx
1030 '((t . "open %s")
1031 ("ps" . "gv %s")
1032 ("ps.gz" . "gv %s")
1033 ("eps" . "gv %s")
1034 ("eps.gz" . "gv %s")
1035 ("dvi" . "xdvi %s")
1036 ("fig" . "xfig %s"))
1037 "Default file applications on a MacOS X system.
1038 The system \"open\" is known as a default, but we use X11 applications
1039 for some files for which the OS does not have a good default.
1040 See `org-file-apps'.")
1041
1042 (defconst org-file-apps-defaults-windowsnt
1043 '((t . (w32-shell-execute "open" file)))
1044 "Default file applications on a Windows NT system.
1045 The system \"open\" is used for most files.
1046 See `org-file-apps'.")
1047
1048 (defcustom org-file-apps
1049 '(
1050 ("txt" . emacs)
1051 ("tex" . emacs)
1052 ("ltx" . emacs)
1053 ("org" . emacs)
1054 ("el" . emacs)
1055 )
1056 "External applications for opening `file:path' items in a document.
1057 Org-mode uses system defaults for different file types, but
1058 you can use this variable to set the application for a given file
1059 extension. The entries in this list are cons cells with a file extension
1060 and the corresponding command. Possible values for the command are:
1061 `emacs' The file will be visited by the current Emacs process.
1062 `default' Use the default application for this file type.
1063 string A command to be executed by a shell; %s will be replaced
1064 by the path to the file.
1065 sexp A Lisp form which will be evaluated. The file path will
1066 be available in the Lisp variable `file'.
1067 For more examples, see the system specific constants
1068 `org-file-apps-defaults-macosx'
1069 `org-file-apps-defaults-windowsnt'
1070 `org-file-apps-defaults-linux'."
1071 :group 'org-link
1072 :type '(repeat
1073 (cons (string :tag "Extension")
1074 (choice :value ""
1075 (const :tag "Visit with Emacs" 'emacs)
1076 (const :tag "Use system default" 'default)
1077 (string :tag "Command")
1078 (sexp :tag "Lisp form")))))
1079
1080
1081 (defgroup org-remember nil
1082 "Options concerning interaction with remember.el."
1083 :tag "Org Remember"
1084 :group 'org)
1085
1086 (defcustom org-directory "~/org"
1087 "Directory with org files.
1088 This directory will be used as default to prompt for org files.
1089 Used by the hooks for remember.el."
1090 :group 'org-remember
1091 :type 'directory)
1092
1093 (defcustom org-default-notes-file "~/.notes"
1094 "Default target for storing notes.
1095 Used by the hooks for remember.el. This can be a string, or nil to mean
1096 the value of `remember-data-file'."
1097 :group 'org-remember
1098 :type '(choice
1099 (const :tag "Default from remember-data-file" nil)
1100 file))
1101
1102 (defcustom org-reverse-note-order nil
1103 "Non-nil means, store new notes at the beginning of a file or entry.
1104 When nil, new notes will be filed to the end of a file or entry."
1105 :group 'org-remember
1106 :type '(choice
1107 (const :tag "Reverse always" t)
1108 (const :tag "Reverse never" nil)
1109 (repeat :tag "By file name regexp"
1110 (cons regexp boolean))))
1111
1112 (defgroup org-table nil
1113 "Options concerning tables in Org-mode."
1114 :tag "Org Table"
1115 :group 'org)
1116
1117 (defcustom org-enable-table-editor 'optimized
1118 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1119 When nil, such lines will be treated like ordinary lines.
1120
1121 When equal to the symbol `optimized', the table editor will be optimized to
1122 do the following:
1123 - Use automatic overwrite mode in front of whitespace in table fields.
1124 This makes the structure of the table stay intact as long as the edited
1125 field does not exceed the column width.
1126 - Minimize the number of realigns. Normally, the table is aligned each time
1127 TAB or RET are pressed to move to another field. With optimization this
1128 happens only if changes to a field might have changed the column width.
1129 Optimization requires replacing the functions `self-insert-command',
1130 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1131 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1132 very good at guessing when a re-align will be necessary, but you can always
1133 force one with `C-c C-c'.
1134
1135 If you would like to use the optimized version in Org-mode, but the
1136 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1137
1138 This variable can be used to turn on and off the table editor during a session,
1139 but in order to toggle optimization, a restart is required."
1140 :group 'org-table
1141 :type '(choice
1142 (const :tag "off" nil)
1143 (const :tag "on" t)
1144 (const :tag "on, optimized" optimized)))
1145
1146 (defcustom org-table-default-size "5x2"
1147 "The default size for newly created tables, Columns x Rows."
1148 :group 'org-table
1149 :type 'string)
1150
1151 (defcustom org-table-automatic-realign t
1152 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1153 When nil, aligning is only done with \\[org-table-align], or after column
1154 removal/insertion."
1155 :group 'org-table
1156 :type 'boolean)
1157
1158 (defcustom org-table-spaces-around-separators '(1 . 1)
1159 "The number of spaces to be placed before and after separators."
1160 :group 'org-table
1161 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1162
1163 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1164 "The number of spaces to be placed before and after separators.
1165 This option applies when the column separators have been made invisible."
1166 :group 'org-table
1167 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1168
1169 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1170 "Regular expression for recognizing numbers in table columns.
1171 If a table column contains mostly numbers, it will be aligned to the
1172 right. If not, it will be aligned to the left.
1173
1174 The default value of this option is a regular expression which allows
1175 anything which looks remotely like a number as used in scientific
1176 context. For example, all of the following will be considered a
1177 number:
1178 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1179
1180 Other options offered by the customize interface are more restrictive."
1181 :group 'org-table
1182 :type '(choice
1183 (const :tag "Positive Integers"
1184 "^[0-9]+$")
1185 (const :tag "Integers"
1186 "^[-+]?[0-9]+$")
1187 (const :tag "Floating Point Numbers"
1188 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1189 (const :tag "Floating Point Number or Integer"
1190 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1191 (const :tag "Exponential, Floating point, Integer"
1192 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1193 (const :tag "Very General Number-Like"
1194 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1195 (string :tag "Regexp:")))
1196
1197 (defcustom org-table-number-fraction 0.5
1198 "Fraction of numbers in a column required to make the column align right.
1199 In a column all non-white fields are considered. If at least this
1200 fraction of fields is matched by `org-table-number-fraction',
1201 alignment to the right border applies."
1202 :group 'org-table
1203 :type 'number)
1204
1205 (defcustom org-export-highlight-first-table-line t
1206 "Non-nil means, highlight the first table line.
1207 In HTML export, this means use <th> instead of <td>.
1208 In tables created with table.el, this applies to the first table line.
1209 In Org-mode tables, all lines before the first horizontal separator
1210 line will be formatted with <th> tags."
1211 :group 'org-table
1212 :type 'boolean)
1213
1214
1215 (defgroup org-table-calculation nil
1216 "Options concerning tables in Org-mode."
1217 :tag "Org Table Calculation"
1218 :group 'org)
1219
1220 (defcustom org-table-copy-increment t
1221 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1222 :group 'org-table-calculation
1223 :type 'boolean)
1224
1225 (defcustom org-calc-default-modes
1226 '(calc-internal-prec 12
1227 calc-float-format (float 5)
1228 calc-angle-mode deg
1229 calc-prefer-frac nil
1230 calc-symbolic-mode nil)
1231 "List with Calc mode settings for use in calc-eval for table formulas.
1232 The list must contain alternating symbols (calc modes variables and values.
1233 Don't remove any of the default settings, just change the values. Org-mode
1234 relies on the variables to be present in the list."
1235 :group 'org-table-calculation
1236 :type 'plist)
1237
1238 (defcustom org-table-formula-evaluate-inline t
1239 "Non-nil means, TAB and RET evaluate a formula in current table field.
1240 If the current field starts with an equal sign, it is assumed to be a formula
1241 which should be evaluated as described in the manual and in the documentation
1242 string of the command `org-table-eval-formula'. This feature requires the
1243 Emacs calc package.
1244 When this variable is nil, formula calculation is only available through
1245 the command \\[org-table-eval-formula]."
1246 :group 'org-table-calculation
1247 :type 'boolean)
1248
1249
1250 (defcustom org-table-formula-use-constants t
1251 "Non-nil means, interpret constants in formulas in tables.
1252 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1253 by the value given in `org-table-formula-constants', or by a value obtained
1254 from the `constants.el' package."
1255 :group 'org-table-calculation
1256 :type 'boolean)
1257
1258 (defcustom org-table-formula-constants nil
1259 "Alist with constant names and values, for use in table formulas.
1260 The car of each element is a name of a constant, without the `$' before it.
1261 The cdr is the value as a string. For example, if you'd like to use the
1262 speed of light in a formula, you would configure
1263
1264 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1265
1266 and then use it in an equation like `$1*$c'."
1267 :group 'org-table-calculation
1268 :type '(repeat
1269 (cons (string :tag "name")
1270 (string :tag "value"))))
1271
1272 (defcustom org-table-formula-numbers-only nil
1273 "Non-nil means, calculate only with numbers in table formulas.
1274 Then all input fields will be converted to a number, and the result
1275 must also be a number. When nil, calc's full potential is available
1276 in table calculations, including symbolics etc."
1277 :group 'org-table-calculation
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 (defcustom org-export-prefer-native-exporter-for-tables nil
1288 "Non-nil means, always export tables created with table.el natively.
1289 Natively means, use the HTML code generator in table.el.
1290 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1291 the table does not use row- or column-spanning). This has the
1292 advantage, that the automatic HTML conversions for math symbols and
1293 sub/superscripts can be applied. Org-mode's HTML generator is also
1294 much faster."
1295 :group 'org-table
1296 :type 'boolean)
1297
1298 (defcustom org-enable-fixed-width-editor t
1299 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1300 This currently only means, they are never auto-wrapped.
1301 When nil, such lines will be treated like ordinary lines."
1302 :group 'org-table
1303 :type 'boolean)
1304
1305 (defgroup org-export nil
1306 "Options for exporting org-listings."
1307 :tag "Org Export"
1308 :group 'org)
1309
1310 (defcustom org-export-language-setup
1311 '(("en" "Author" "Date" "Table of Contents")
1312 ("da" "Ophavsmand" "Dato" "Indhold")
1313 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1314 ("es" "Autor" "Fecha" "\xccndice")
1315 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1316 ("it" "Autore" "Data" "Indice")
1317 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1318 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1319 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1320 "Terms used in export text, translated to different languages.
1321 Use the variable `org-export-default-language' to set the language,
1322 or use the +OPTION lines for a per-file setting."
1323 :group 'org-export
1324 :type '(repeat
1325 (list
1326 (string :tag "HTML language tag")
1327 (string :tag "Author")
1328 (string :tag "Date")
1329 (string :tag "Table of Contents"))))
1330
1331 (defcustom org-export-default-language "en"
1332 "The default language of HTML export, as a string.
1333 This should have an association in `org-export-language-setup'."
1334 :group 'org-export
1335 :type 'string)
1336
1337 (defcustom org-export-headline-levels 3
1338 "The last level which is still exported as a headline.
1339 Inferior levels will produce itemize lists when exported.
1340 Note that a numeric prefix argument to an exporter function overrides
1341 this setting.
1342
1343 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1344 :group 'org-export
1345 :type 'number)
1346
1347 (defcustom org-export-with-section-numbers t
1348 "Non-nil means, add section numbers to headlines when exporting.
1349
1350 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1351 :group 'org-export
1352 :type 'boolean)
1353
1354 (defcustom org-export-with-toc t
1355 "Non-nil means, create a table of contents in exported files.
1356 The TOC contains headlines with levels up to`org-export-headline-levels'.
1357
1358 Headlines which contain any TODO items will be marked with \"(*)\" in
1359 ASCII export, and with red color in HTML output.
1360
1361 In HTML output, the TOC will be clickable.
1362
1363 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1364 :group 'org-export
1365 :type 'boolean)
1366
1367 (defcustom org-export-preserve-breaks nil
1368 "Non-nil means, preserve all line breaks when exporting.
1369 Normally, in HTML output paragraphs will be reformatted. In ASCII
1370 export, line breaks will always be preserved, regardless of this variable.
1371
1372 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1373 :group 'org-export
1374 :type 'boolean)
1375
1376 (defcustom org-export-html-inline-images t
1377 "Non-nil means, inline images into exported HTML pages.
1378 The link will still be to the original location of the image file.
1379 So if you are moving the page, lets say to your public HTML site,
1380 you will have to move the image and maybe change the link."
1381 :group 'org-export
1382 :type 'boolean)
1383
1384 (defcustom org-export-html-expand t
1385 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1386 When nil, these tags will be exported as plain text and therefore
1387 not be interpreted by a browser.
1388
1389 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1390 :group 'org-export
1391 :type 'boolean)
1392
1393 (defcustom org-export-with-fixed-width t
1394 "Non-nil means, lines starting with \":\" will be in fixed width font.
1395 This can be used to have pre-formatted text, fragments of code etc. For
1396 example
1397 : ;; Some Lisp examples
1398 : (while (defc cnt)
1399 : (ding))
1400 will be looking just like this in also HTML. In ASCII export, this option
1401 has no effect.
1402
1403 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1404 :group 'org-export
1405 :type 'boolean)
1406
1407 (defcustom org-export-with-tables t
1408 "If non-nil, lines starting with \"|\" define a table.
1409 For example:
1410
1411 | Name | Address | Birthday |
1412 |-------------+----------+-----------|
1413 | Arthur Dent | England | 29.2.2100 |
1414
1415 In ASCII export, this option has no effect.
1416
1417 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1418 :group 'org-export
1419 :type 'boolean)
1420
1421 (defcustom org-export-html-table-tag
1422 "<table border=1 cellspacing=0 cellpadding=6>"
1423 "The HTML tag used to start a table.
1424 This must be a <table> tag, but you may change the options like
1425 borders and spacing."
1426 :group 'org-export
1427 :type 'string)
1428
1429 (defcustom org-export-with-emphasize t
1430 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1431 If the export target supports emphasizing text, the word will be
1432 typeset in bold, italic, or underlined, respectively. Works only for
1433 single words, but you can say: I *really* *mean* *this*.
1434 In ASCII export, this option has no effect.
1435
1436 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1437 :group 'org-export
1438 :type 'boolean)
1439
1440 (defcustom org-match-sexp-depth 3
1441 "Number of stacked braces for sub/superscript matching.
1442 This has to be set before loading org.el to be effective."
1443 :group 'org-export
1444 :type 'integer)
1445
1446 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1447 (defcustom org-export-with-sub-superscripts t
1448 "Non-nil means, interpret \"_\" and \"^\" for export.
1449 When this option is turned on, you can use TeX-like syntax for sub- and
1450 superscripts. Several characters after \"_\" or \"^\" will be
1451 considered as a single item - so grouping with {} is normally not
1452 needed. For example, the following things will be parsed as single
1453 sub- or superscripts.
1454
1455 10^24 or 10^tau several digits will be considered 1 item
1456 10^-12 or 10^-tau a leading sign with digits or a word
1457 x^2-y^3 will be read as x^2 - y^3, because items are
1458 terminated by almost any nonword/nondigit char.
1459 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1460
1461 Still, ambiguity is possible - so when in doubt use {} to enclose the
1462 sub/superscript.
1463 In ASCII export, this option has no effect.
1464
1465 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1466 :group 'org-export
1467 :type 'boolean)
1468
1469 (defcustom org-export-with-TeX-macros t
1470 "Non-nil means, interpret simple TeX-like macros when exporting.
1471 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1472 No only real TeX macros will work here, but the standard HTML entities
1473 for math can be used as macro names as well. For a list of supported
1474 names in HTML export, see the constant `org-html-entities'.
1475 In ASCII export, this option has no effect.
1476
1477 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1478 :group 'org-export
1479 :type 'boolean)
1480
1481 (defcustom org-export-html-with-timestamp nil
1482 "If non-nil, write `org-export-html-html-helper-timestamp'
1483 into the exported html text. Otherwise, the buffer will just be saved
1484 to a file."
1485 :group 'org-export
1486 :type 'boolean)
1487
1488 (defcustom org-export-html-html-helper-timestamp
1489 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1490 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1491 :group 'org-export
1492 :type 'string)
1493
1494 (defcustom org-export-ascii-show-new-buffer t
1495 "Non-nil means, popup buffer containing the exported ASCII text.
1496 Otherwise the buffer will just be saved to a file and stay hidden."
1497 :group 'org-export
1498 :type 'boolean)
1499
1500 (defcustom org-export-html-show-new-buffer nil
1501 "Non-nil means, popup buffer containing the exported HTML text.
1502 Otherwise, the buffer will just be saved to a file and stay hidden."
1503 :group 'org-export
1504 :type 'boolean)
1505
1506 (defgroup org-faces nil
1507 "Faces for highlighting in Org-mode."
1508 :tag "Org Faces"
1509 :group 'org)
1510
1511 (defface org-level-1 ;; font-lock-function-name-face
1512 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1513 (((class color) (background light)) (:foreground "Blue"))
1514 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1515 (t (:inverse-video t :bold t)))
1516 "Face used for level 1 headlines."
1517 :group 'org-faces)
1518
1519 (defface org-level-2 ;; font-lock-variable-name-face
1520 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1521 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1522 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1523 (t (:bold t :italic t)))
1524 "Face used for level 2 headlines."
1525 :group 'org-faces)
1526
1527 (defface org-level-3 ;; font-lock-keyword-face
1528 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1529 (((class color) (background light)) (:foreground "Purple"))
1530 (((class color) (background dark)) (:foreground "Cyan"))
1531 (t (:bold t)))
1532 "Face used for level 3 headlines."
1533 :group 'org-faces)
1534
1535 (defface org-level-4 ;; font-lock-comment-face
1536 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1537 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1538 (((class color) (background light)) (:foreground "Firebrick"))
1539 (((class color) (background dark)) (:foreground "chocolate1"))
1540 (t (:bold t :italic t)))
1541 "Face used for level 4 headlines."
1542 :group 'org-faces)
1543
1544 (defface org-level-5 ;; font-lock-type-face
1545 '((((type tty) (class color)) (:foreground "green"))
1546 (((class color) (background light)) (:foreground "ForestGreen"))
1547 (((class color) (background dark)) (:foreground "PaleGreen"))
1548 (t (:bold t :underline t)))
1549 "Face used for level 5 headlines."
1550 :group 'org-faces)
1551
1552 (defface org-level-6 ;; font-lock-constant-face
1553 '((((type tty) (class color)) (:foreground "magenta"))
1554 (((class color) (background light)) (:foreground "CadetBlue"))
1555 (((class color) (background dark)) (:foreground "Aquamarine"))
1556 (t (:bold t :underline t)))
1557 "Face used for level 6 headlines."
1558 :group 'org-faces)
1559
1560 (defface org-level-7 ;; font-lock-builtin-face
1561 '((((type tty) (class color)) (:foreground "blue" :weight light))
1562 (((class color) (background light)) (:foreground "Orchid"))
1563 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1564 (t (:bold t)))
1565 "Face used for level 7 headlines."
1566 :group 'org-faces)
1567
1568 (defface org-level-8 ;; font-lock-string-face
1569 '((((type tty) (class color)) (:foreground "green"))
1570 (((class color) (background light)) (:foreground "RosyBrown"))
1571 (((class color) (background dark)) (:foreground "LightSalmon"))
1572 (t (:italic t)))
1573 "Face used for level 8 headlines."
1574 :group 'org-faces)
1575
1576 (defface org-warning ;; font-lock-warning-face
1577 '((((type tty) (class color)) (:foreground "red"))
1578 (((class color) (background light)) (:foreground "Red" :bold t))
1579 (((class color) (background dark)) (:foreground "Red1" :bold t))
1580 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1581 (t (:inverse-video t :bold t)))
1582 "Face for deadlines and TODO keywords."
1583 :group 'org-faces)
1584
1585 (defcustom org-fontify-done-headline nil
1586 "Non-nil means, change the face of a headline if it is marked DONE.
1587 Normally, only the TODO/DONE keyword indicates the state of a headline.
1588 When this is non-nil, the headline after the keyword is set to the
1589 `org-headline-done' as an additional indication."
1590 :group 'org-faces
1591 :type 'boolean)
1592
1593 (defface org-headline-done ;; font-lock-string-face
1594 '((((type tty) (class color)) (:foreground "green"))
1595 (((class color) (background light)) (:foreground "RosyBrown"))
1596 (((class color) (background dark)) (:foreground "LightSalmon"))
1597 (t (:italic t)))
1598 "Face used to indicate that a headline is DONE. See also the variable
1599 `org-fontify-done-headline'."
1600 :group 'org-faces)
1601
1602 ;; Inheritance does not yet work for xemacs. So we just copy...
1603
1604 (defface org-deadline-announce
1605 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1606 (((class color) (background light)) (:foreground "Blue"))
1607 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1608 (t (:inverse-video t :bold t)))
1609 "Face for upcoming deadlines."
1610 :group 'org-faces)
1611
1612 (defface org-scheduled-today
1613 '((((type tty) (class color)) (:foreground "green"))
1614 (((class color) (background light)) (:foreground "DarkGreen"))
1615 (((class color) (background dark)) (:foreground "PaleGreen"))
1616 (t (:bold t :underline t)))
1617 "Face for items scheduled for a certain day."
1618 :group 'org-faces)
1619
1620 (defface org-scheduled-previously
1621 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1622 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1623 (((class color) (background light)) (:foreground "Firebrick"))
1624 (((class color) (background dark)) (:foreground "chocolate1"))
1625 (t (:bold t :italic t)))
1626 "Face for items scheduled previously, and not yet done."
1627 :group 'org-faces)
1628
1629 (defface org-formula
1630 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1631 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1632 (((class color) (background light)) (:foreground "Firebrick"))
1633 (((class color) (background dark)) (:foreground "chocolate1"))
1634 (t (:bold t :italic t)))
1635 "Face for items scheduled previously, and not yet done."
1636 :group 'org-faces)
1637
1638 (defface org-link
1639 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1640 (((class color) (background light)) (:foreground "Purple"))
1641 (((class color) (background dark)) (:foreground "Cyan"))
1642 (t (:bold t)))
1643 "Face for links."
1644 :group 'org-faces)
1645
1646 (defface org-done ;; font-lock-type-face
1647 '((((type tty) (class color)) (:foreground "green"))
1648 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1649 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1650 (t (:bold t :underline t)))
1651 "Face used for DONE."
1652 :group 'org-faces)
1653
1654 (defface org-table ;; font-lock-function-name-face
1655 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1656 (((class color) (background light)) (:foreground "Blue"))
1657 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1658 (t (:inverse-video t :bold t)))
1659 "Face used for tables."
1660 :group 'org-faces)
1661
1662 (defface org-time-grid ;; font-lock-variable-name-face
1663 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1664 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1665 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1666 (t (:bold t :italic t)))
1667 "Face used for time grids."
1668 :group 'org-faces)
1669
1670 (defvar org-level-faces
1671 '(
1672 org-level-1
1673 org-level-2
1674 org-level-3
1675 org-level-4
1676 org-level-5
1677 org-level-6
1678 org-level-7
1679 org-level-8
1680 ))
1681 (defvar org-n-levels (length org-level-faces))
1682
1683 ;; Tell the compiler about dynamically scoped variables,
1684 ;; and variables from other packages
1685 (eval-when-compile
1686 (defvar zmacs-regions)
1687 (defvar original-date)
1688 (defvar org-transient-mark-mode)
1689 (defvar org-old-auto-fill-inhibit-regexp)
1690 (defvar orgtbl-mode-menu)
1691 (defvar org-html-entities)
1692 (defvar org-goto-start-pos)
1693 (defvar org-cursor-color)
1694 (defvar org-time-was-given)
1695 (defvar org-ts-what)
1696 (defvar mark-active)
1697 (defvar timecnt)
1698 (defvar levels-open)
1699 (defvar title)
1700 (defvar author)
1701 (defvar email)
1702 (defvar text)
1703 (defvar entry)
1704 (defvar date)
1705 (defvar language)
1706 (defvar options)
1707 (defvar ans1)
1708 (defvar ans2)
1709 (defvar starting-day)
1710 (defvar include-all-loc)
1711 (defvar vm-message-pointer)
1712 (defvar vm-folder-directory)
1713 (defvar wl-summary-buffer-elmo-folder)
1714 (defvar wl-summary-buffer-folder-name)
1715 (defvar gnus-group-name)
1716 (defvar gnus-article-current)
1717 (defvar w3m-current-url)
1718 (defvar org-selected-point)
1719 (defvar calendar-mode-map)
1720 (defvar remember-save-after-remembering)
1721 (defvar remember-data-file))
1722
1723
1724 ;;; Define the mode
1725
1726 (defvar org-mode-map (copy-keymap outline-mode-map)
1727 "Keymap for Org-mode.")
1728
1729 (defvar org-struct-menu)
1730 (defvar org-org-menu)
1731 (defvar org-tbl-menu)
1732
1733 ;; We use a before-change function to check if a table might need
1734 ;; an update.
1735 (defvar org-table-may-need-update t
1736 "Indicates of a table might need an update.
1737 This variable is set by `org-before-change-function'. `org-table-align'
1738 sets it back to nil.")
1739 (defvar org-mode-hook nil)
1740 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1741
1742
1743 ;;;###autoload
1744 (define-derived-mode org-mode outline-mode "Org"
1745 "Outline-based notes management and organizer, alias
1746 \"Carstens outline-mode for keeping track of everything.\"
1747
1748 Org-mode develops organizational tasks around a NOTES file which
1749 contains information about projects as plain text. Org-mode is
1750 implemented on top of outline-mode, which is ideal to keep the content
1751 of large files well structured. It supports ToDo items, deadlines and
1752 time stamps, which magically appear in the diary listing of the Emacs
1753 calendar. Tables are easily created with a built-in table editor.
1754 Plain text URL-like links connect to websites, emails (VM), Usenet
1755 messages (Gnus), BBDB entries, and any files related to the project.
1756 For printing and sharing of notes, an Org-mode file (or a part of it)
1757 can be exported as a structured ASCII or HTML file.
1758
1759 The following commands are available:
1760
1761 \\{org-mode-map}"
1762 (easy-menu-add org-org-menu)
1763 (easy-menu-add org-tbl-menu)
1764 (org-install-agenda-files-menu)
1765 (setq outline-regexp "\\*+")
1766 (if org-startup-truncated (setq truncate-lines t))
1767 (org-set-regexps-and-options)
1768 (set (make-local-variable 'font-lock-unfontify-region-function)
1769 'org-unfontify-region)
1770 ;; Activate before-change-function
1771 (set (make-local-variable 'org-table-may-need-update) t)
1772 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1773 (add-hook 'before-change-functions 'org-before-change-function nil
1774 'local)
1775 ;; Paragraph regular expressions
1776 (set (make-local-variable 'paragraph-separate) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1777 (set (make-local-variable 'paragraph-start) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1778 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1779 (set (make-local-variable 'auto-fill-inhibit-regexp)
1780 (concat "\\*\\|#"
1781 (if (or org-enable-table-editor org-enable-fixed-width-editor)
1782 (concat
1783 "\\|[ \t]*["
1784 (if org-enable-table-editor "|" "")
1785 (if org-enable-fixed-width-editor ":" "")
1786 "]"))))
1787 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
1788 (if (and org-insert-mode-line-in-empty-file
1789 (interactive-p)
1790 (= (point-min) (point-max)))
1791 (insert " -*- mode: org -*-\n\n"))
1792
1793 ;; Get rid of Outline menus, they are not needed
1794 ;; Need to do this here because define-derived-mode sets up
1795 ;; the keymap so late.
1796 (if org-xemacs-p
1797 (progn
1798 (delete-menu-item '("Headings"))
1799 (delete-menu-item '("Show"))
1800 (delete-menu-item '("Hide"))
1801 (set-menubar-dirty-flag))
1802 (define-key org-mode-map [menu-bar headings] 'undefined)
1803 (define-key org-mode-map [menu-bar hide] 'undefined)
1804 (define-key org-mode-map [menu-bar show] 'undefined))
1805
1806 (unless org-inhibit-startup
1807 (if org-startup-with-deadline-check
1808 (call-interactively 'org-check-deadlines)
1809 (cond
1810 ((eq org-startup-folded t)
1811 (org-cycle '(4)))
1812 ((eq org-startup-folded 'content)
1813 (let ((this-command 'org-cycle) (last-command 'org-cycle))
1814 (org-cycle '(4)) (org-cycle '(4))))))))
1815
1816 (defun org-fill-paragraph (&optional justify)
1817 "Re-align a table, pass through to `fill-paragraph' if no table."
1818 (save-excursion
1819 (beginning-of-line 1)
1820 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1821
1822 (defsubst org-current-line (&optional pos)
1823 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
1824
1825 ;;; Font-Lock stuff
1826
1827 (defvar org-mouse-map (make-sparse-keymap))
1828 (define-key org-mouse-map
1829 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
1830 (define-key org-mouse-map
1831 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1832
1833 (require 'font-lock)
1834
1835 (defconst org-non-link-chars "\t\n\r|<>\000")
1836 (defconst org-link-regexp
1837 (if org-allow-space-in-links
1838 (concat
1839 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1840 (concat
1841 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1842 )
1843 "Regular expression for matching links.")
1844 (defconst org-link-maybe-angles-regexp
1845 (concat "<?\\(" org-link-regexp "\\)>?")
1846 "Matches a link and optionally surrounding angle brackets.")
1847 (defconst org-protected-link-regexp
1848 (concat "\000" org-link-regexp "\000")
1849 "Matches a link and optionally surrounding angle brackets.")
1850
1851 (defconst org-ts-lengths
1852 (cons (length (format-time-string (car org-time-stamp-formats)))
1853 (length (format-time-string (cdr org-time-stamp-formats))))
1854 "This holds the lengths of the two different time formats.")
1855 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1856 "Regular expression for fast time stamp matching.")
1857 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1858 "Regular expression matching time strings for analysis.")
1859 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1860 "Regular expression matching time stamps, with groups.")
1861 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1862 "Regular expression matching a time stamp range.")
1863 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1864 org-ts-regexp "\\)?")
1865 "Regular expression matching a time stamp or time stamp range.")
1866
1867 (defun org-activate-links (limit)
1868 "Run through the buffer and add overlays to links."
1869 (if (re-search-forward org-link-regexp limit t)
1870 (progn
1871 (add-text-properties (match-beginning 0) (match-end 0)
1872 (list 'mouse-face 'highlight
1873 'keymap org-mouse-map))
1874 t)))
1875
1876 (defun org-activate-dates (limit)
1877 "Run through the buffer and add overlays to dates."
1878 (if (re-search-forward org-tsr-regexp limit t)
1879 (progn
1880 (add-text-properties (match-beginning 0) (match-end 0)
1881 (list 'mouse-face 'highlight
1882 'keymap org-mouse-map))
1883 t)))
1884
1885 (defun org-font-lock-level ()
1886 (save-excursion
1887 (org-back-to-heading t)
1888 (- (match-end 0) (match-beginning 0))))
1889
1890 (defvar org-font-lock-keywords nil)
1891
1892 (defun org-set-font-lock-defaults ()
1893 (let ((org-font-lock-extra-keywords
1894 (list
1895 '(org-activate-links (0 'org-link))
1896 '(org-activate-dates (0 'org-link))
1897 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1898 '(1 'org-warning t))
1899 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning t))
1900 (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1901 (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1902 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1903 ;; (3 'bold))
1904 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1905 ;; (3 'italic))
1906 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1907 ;; (3 'underline))
1908 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1909 '(1 'org-warning t))
1910 '("^#.*" (0 'font-lock-comment-face t))
1911 (if org-fontify-done-headline
1912 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1913 '(1 'org-done t) '(2 'org-headline-done t))
1914 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1915 '(1 'org-done t)))
1916 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1917 (1 'org-table t))
1918 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1919 '("| *\\(=[^|\n]*\\)" (1 'org-formula t))
1920 '("^[ \t]*| *\\([#!$*]\\) *|" (1 'org-formula t))
1921 )))
1922 (set (make-local-variable 'org-font-lock-keywords)
1923 (append
1924 (if org-noutline-p ; FIXME: I am not sure if eval will work
1925 ; on XEmacs if noutline is ever ported
1926 '((eval . (list "^\\(\\*+\\).*"
1927 0 '(nth
1928 (% (- (match-end 1) (match-beginning 1) 1)
1929 org-n-levels)
1930 org-level-faces)
1931 nil t)))
1932 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1933 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1934 org-n-levels)
1935 org-level-faces)
1936 nil t))))
1937 org-font-lock-extra-keywords))
1938 (set (make-local-variable 'font-lock-defaults)
1939 '(org-font-lock-keywords t nil nil backward-paragraph))
1940 (kill-local-variable 'font-lock-keywords) nil))
1941
1942 (defun org-unfontify-region (beg end &optional maybe_loudly)
1943 "Remove fontification and activation overlays from links."
1944 (font-lock-default-unfontify-region beg end)
1945 (let* ((buffer-undo-list t)
1946 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1947 (inhibit-modification-hooks t)
1948 deactivate-mark buffer-file-name buffer-file-truename)
1949 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1950
1951 ;;; Visibility cycling
1952
1953 (defvar org-cycle-global-status nil)
1954 (defvar org-cycle-subtree-status nil)
1955 (defun org-cycle (&optional arg)
1956 "Visibility cycling for Org-mode.
1957
1958 - When this function is called with a prefix argument, rotate the entire
1959 buffer through 3 states (global cycling):
1960 1. OVERVIEW: Show only top-level headlines.
1961 2. CONTENTS: Show all headlines of all levels, but no body text.
1962 3. SHOW ALL: Show everything.
1963
1964 - When point is at the beginning of a headline, rotate the subtree started
1965 by this line through 3 different states (local cycling):
1966 1. FOLDED: Only the main headline is shown.
1967 2. CHILDREN: The main headline and the direct children are shown. From
1968 this state, you can move to one of the children and
1969 zoom in further.
1970 3. SUBTREE: Show the entire subtree, including body text.
1971
1972 - When there is a numeric prefix, go up to a heading with level ARG, do
1973 a `show-subtree' and return to the previous cursor position. If ARG
1974 is negative, go up that many levels.
1975
1976 - When point is not at the beginning of a headline, execute
1977 `indent-relative', like TAB normally does. See the option
1978 `org-cycle-emulate-tab' for details.
1979
1980 - Special case: if point is the the beginning of the buffer and there is
1981 no headline in line 1, this function will act as if called with prefix arg."
1982 (interactive "P")
1983
1984 (if (or (and (bobp) (not (looking-at outline-regexp)))
1985 (equal arg '(4)))
1986 ;; special case: use global cycling
1987 (setq arg t))
1988
1989 (cond
1990
1991 ((org-at-table-p 'any)
1992 ;; Enter the table or move to the next field in the table
1993 (or (org-table-recognize-table.el)
1994 (progn
1995 (org-table-justify-field-maybe)
1996 (org-table-next-field))))
1997
1998 ((eq arg t) ;; Global cycling
1999
2000 (cond
2001 ((and (eq last-command this-command)
2002 (eq org-cycle-global-status 'overview))
2003 ;; We just created the overview - now do table of contents
2004 ;; This can be slow in very large buffers, so indicate action
2005 (message "CONTENTS...")
2006 (save-excursion
2007 ;; Visit all headings and show their offspring
2008 (goto-char (point-max))
2009 (catch 'exit
2010 (while (and (progn (condition-case nil
2011 (outline-previous-visible-heading 1)
2012 (error (goto-char (point-min))))
2013 t)
2014 (looking-at outline-regexp))
2015 (show-branches)
2016 (if (bobp) (throw 'exit nil))))
2017 (message "CONTENTS...done"))
2018 (setq org-cycle-global-status 'contents)
2019 (run-hook-with-args 'org-cycle-hook 'contents))
2020
2021 ((and (eq last-command this-command)
2022 (eq org-cycle-global-status 'contents))
2023 ;; We just showed the table of contents - now show everything
2024 (show-all)
2025 (message "SHOW ALL")
2026 (setq org-cycle-global-status 'all)
2027 (run-hook-with-args 'org-cycle-hook 'all))
2028
2029 (t
2030 ;; Default action: go to overview
2031 (hide-sublevels 1)
2032 (message "OVERVIEW")
2033 (setq org-cycle-global-status 'overview)
2034 (run-hook-with-args 'org-cycle-hook 'overview))))
2035
2036 ((integerp arg)
2037 ;; Show-subtree, ARG levels up from here.
2038 (save-excursion
2039 (org-back-to-heading)
2040 (outline-up-heading (if (< arg 0) (- arg)
2041 (- (outline-level) arg)))
2042 (org-show-subtree)))
2043
2044 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2045 ;; At a heading: rotate between three different views
2046 (org-back-to-heading)
2047 (let ((goal-column 0) eoh eol eos)
2048 ;; First, some boundaries
2049 (save-excursion
2050 (org-back-to-heading)
2051 (save-excursion
2052 (beginning-of-line 2)
2053 (while (and (not (eobp)) ;; this is like `next-line'
2054 (get-char-property (1- (point)) 'invisible))
2055 (beginning-of-line 2)) (setq eol (point)))
2056 (outline-end-of-heading) (setq eoh (point))
2057 (outline-end-of-subtree) (setq eos (point))
2058 (outline-next-heading))
2059 ;; Find out what to do next and set `this-command'
2060 (cond
2061 ((= eos eoh)
2062 ;; Nothing is hidden behind this heading
2063 (message "EMPTY ENTRY")
2064 (setq org-cycle-subtree-status nil))
2065 ((>= eol eos)
2066 ;; Entire subtree is hidden in one line: open it
2067 (org-show-entry)
2068 (show-children)
2069 (message "CHILDREN")
2070 (setq org-cycle-subtree-status 'children)
2071 (run-hook-with-args 'org-cycle-hook 'children))
2072 ((and (eq last-command this-command)
2073 (eq org-cycle-subtree-status 'children))
2074 ;; We just showed the children, now show everything.
2075 (org-show-subtree)
2076 (message "SUBTREE")
2077 (setq org-cycle-subtree-status 'subtree)
2078 (run-hook-with-args 'org-cycle-hook 'subtree))
2079 (t
2080 ;; Default action: hide the subtree.
2081 (hide-subtree)
2082 (message "FOLDED")
2083 (setq org-cycle-subtree-status 'folded)
2084 (run-hook-with-args 'org-cycle-hook 'folded)))))
2085
2086 ;; TAB emulation
2087 (buffer-read-only (org-back-to-heading))
2088 ((if (and (eq org-cycle-emulate-tab 'white)
2089 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2090 t
2091 (eq org-cycle-emulate-tab t))
2092 (if (and (looking-at "[ \n\r\t]")
2093 (string-match "^[ \t]*$" (buffer-substring
2094 (point-at-bol) (point))))
2095 (progn
2096 (beginning-of-line 1)
2097 (and (looking-at "[ \t]+") (replace-match ""))))
2098 (indent-relative))
2099
2100 (t (save-excursion
2101 (org-back-to-heading)
2102 (org-cycle)))))
2103
2104 (defun org-optimize-window-after-visibility-change (state)
2105 "Adjust the window after a change in outline visibility.
2106 This function is the default value of the hook `org-cycle-hook'."
2107 (cond
2108 ((eq state 'overview) (org-first-headline-recenter 1))
2109 ((eq state 'content) nil)
2110 ((eq state 'all) nil)
2111 ((eq state 'folded) nil)
2112 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2113 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2114
2115 (defun org-subtree-end-visible-p ()
2116 "Is the end of the current subtree visible?"
2117 (pos-visible-in-window-p
2118 (save-excursion (outline-end-of-subtree) (point))))
2119
2120 (defun org-first-headline-recenter (&optional N)
2121 "Move cursor to the first headline and recenter the headline.
2122 Optional argument N means, put the headline into the Nth line of the window."
2123 (goto-char (point-min))
2124 (when (re-search-forward (concat "^" outline-regexp) nil t)
2125 (beginning-of-line)
2126 (recenter (prefix-numeric-value N))))
2127
2128 (defvar org-goto-window-configuration nil)
2129 (defvar org-goto-marker nil)
2130 (defvar org-goto-map (make-sparse-keymap))
2131 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2132 (while (setq cmd (pop cmds))
2133 (substitute-key-definition cmd cmd org-goto-map global-map)))
2134 (define-key org-goto-map "\C-m" 'org-goto-ret)
2135 (define-key org-goto-map [(left)] 'org-goto-left)
2136 (define-key org-goto-map [(right)] 'org-goto-right)
2137 (define-key org-goto-map [(?q)] 'org-goto-quit)
2138 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2139 (define-key org-goto-map "\C-i" 'org-cycle)
2140 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2141 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2142 (define-key org-goto-map "n" 'outline-next-visible-heading)
2143 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2144 (define-key org-goto-map "f" 'outline-forward-same-level)
2145 (define-key org-goto-map "b" 'outline-backward-same-level)
2146 (define-key org-goto-map "u" 'outline-up-heading)
2147 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2148 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2149 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2150 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2151 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2152 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2153 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2154
2155 (defconst org-goto-help
2156 "Select a location to jump to, press RET
2157 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2158
2159 (defun org-goto ()
2160 "Go to a different location of the document, keeping current visibility.
2161
2162 When you want to go to a different location in a document, the fastest way
2163 is often to fold the entire buffer and then dive into the tree. This
2164 method has the disadvantage, that the previous location will be folded,
2165 which may not be what you want.
2166
2167 This command works around this by showing a copy of the current buffer in
2168 overview mode. You can dive into the tree in that copy, to find the
2169 location you want to reach. When pressing RET, the command returns to the
2170 original buffer in which the visibility is still unchanged. It then jumps
2171 to the new location, making it and the headline hierarchy above it visible."
2172 (interactive)
2173 (let* ((org-goto-start-pos (point))
2174 (selected-point
2175 (org-get-location (current-buffer) org-goto-help)))
2176 (if selected-point
2177 (progn
2178 (goto-char selected-point)
2179 (if (org-invisible-p) (org-show-hierarchy-above)))
2180 (error "Quit"))))
2181
2182 (defun org-get-location (buf help)
2183 "Let the user select a location in the Org-mode buffer BUF.
2184 This function uses a recursive edit. It returns the selected position
2185 or nil."
2186 (let (org-selected-point)
2187 (save-excursion
2188 (save-window-excursion
2189 (delete-other-windows)
2190 (switch-to-buffer (get-buffer-create "*org-goto*"))
2191 (with-output-to-temp-buffer "*Help*"
2192 (princ help))
2193 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2194 (setq buffer-read-only nil)
2195 (erase-buffer)
2196 (insert-buffer buf)
2197 (let ((org-startup-truncated t)
2198 (org-startup-folded t)
2199 (org-startup-with-deadline-check nil))
2200 (org-mode))
2201 (setq buffer-read-only t)
2202 (if (boundp 'org-goto-start-pos)
2203 (goto-char org-goto-start-pos)
2204 (goto-char (point-min)))
2205 (org-beginning-of-line)
2206 (message "Select location and press RET")
2207 ;; now we make sure that during selection, ony very few keys work
2208 ;; and that it is impossible to switch to another window.
2209 (let ((gm (current-global-map))
2210 (overriding-local-map org-goto-map))
2211 (unwind-protect
2212 (progn
2213 (use-global-map org-goto-map)
2214 (recursive-edit))
2215 (use-global-map gm)))))
2216 (kill-buffer "*org-goto*")
2217 org-selected-point))
2218
2219 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2220 (defun org-goto-ret (&optional arg)
2221 "Finish `org-goto' by going to the new location."
2222 (interactive "P")
2223 (setq org-selected-point (point)
2224 current-prefix-arg arg)
2225 (throw 'exit nil))
2226
2227 (defun org-goto-left ()
2228 "Finish `org-goto' by going to the new location."
2229 (interactive)
2230 (if (org-on-heading-p)
2231 (progn
2232 (beginning-of-line 1)
2233 (setq org-selected-point (point)
2234 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2235 (throw 'exit nil))
2236 (error "Not on a heading")))
2237
2238 (defun org-goto-right ()
2239 "Finish `org-goto' by going to the new location."
2240 (interactive)
2241 (if (org-on-heading-p)
2242 (progn
2243 (outline-end-of-subtree)
2244 (or (eobp) (forward-char 1))
2245 (setq org-selected-point (point)
2246 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2247 (throw 'exit nil))
2248 (error "Not on a heading")))
2249
2250 (defun org-goto-quit ()
2251 "Finish `org-goto' without cursor motion."
2252 (interactive)
2253 (setq org-selected-point nil)
2254 (throw 'exit nil))
2255
2256 ;;; Promotion, Demotion, Inserting new headlines
2257
2258 (defvar org-ignore-region nil
2259 "To temporarily disable the active region.")
2260
2261 (defun org-insert-heading ()
2262 "Insert a new heading with same depth at point."
2263 (interactive)
2264 (let* ((head (save-excursion
2265 (condition-case nil
2266 (org-back-to-heading)
2267 (error (outline-next-heading)))
2268 (prog1 (match-string 0)
2269 (funcall outline-level)))))
2270 (unless (bolp) (newline))
2271 (insert head)
2272 (unless (eolp)
2273 (save-excursion (newline-and-indent)))
2274 (unless (equal (char-before) ?\ )
2275 (insert " "))
2276 (run-hooks 'org-insert-heading-hook)))
2277
2278 (defun org-insert-todo-heading (arg)
2279 "Insert a new heading with the same level and TODO state as current heading.
2280 If the heading has no TODO state, or if the state is DONE, use the first
2281 state (TODO by default). Also with prefix arg, force first state."
2282 (interactive "P")
2283 (org-insert-heading)
2284 (save-excursion
2285 (org-back-to-heading)
2286 (outline-previous-heading)
2287 (looking-at org-todo-line-regexp))
2288 (if (or arg
2289 (not (match-beginning 2))
2290 (equal (match-string 2) org-done-string))
2291 (insert (car org-todo-keywords) " ")
2292 (insert (match-string 2) " ")))
2293
2294 (defun org-promote-subtree ()
2295 "Promote the entire subtree.
2296 See also `org-promote'."
2297 (interactive)
2298 (save-excursion
2299 (org-map-tree 'org-promote)))
2300
2301 (defun org-demote-subtree ()
2302 "Demote the entire subtree. See `org-demote'.
2303 See also `org-promote'."
2304 (interactive)
2305 (save-excursion
2306 (org-map-tree 'org-demote)))
2307
2308 (defun org-do-promote ()
2309 "Promote the current heading higher up the tree.
2310 If the region is active in `transient-mark-mode', promote all headings
2311 in the region."
2312 (interactive)
2313 (save-excursion
2314 (if (org-region-active-p)
2315 (org-map-region 'org-promote (region-beginning) (region-end))
2316 (org-promote)))
2317 (org-fix-position-after-promote))
2318
2319 (defun org-do-demote ()
2320 "Demote the current heading lower down the tree.
2321 If the region is active in `transient-mark-mode', demote all headings
2322 in the region."
2323 (interactive)
2324 (save-excursion
2325 (if (org-region-active-p)
2326 (org-map-region 'org-demote (region-beginning) (region-end))
2327 (org-demote)))
2328 (org-fix-position-after-promote))
2329
2330 (defun org-fix-position-after-promote ()
2331 "Make sure that after pro/demotion cursor position is right."
2332 (and (equal (char-after) ?\ )
2333 (equal (char-before) ?*)
2334 (forward-char 1)))
2335
2336 (defun org-promote ()
2337 "Promote the current heading higher up the tree.
2338 If the region is active in `transient-mark-mode', promote all headings
2339 in the region."
2340 (org-back-to-heading t)
2341 (let* ((level (save-match-data (funcall outline-level)))
2342 (up-head (make-string (1- level) ?*)))
2343 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2344 (replace-match up-head nil t)
2345 (if org-adapt-indentation
2346 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2347
2348 (defun org-demote ()
2349 "Demote the current heading lower down the tree.
2350 If the region is active in `transient-mark-mode', demote all headings
2351 in the region."
2352 (org-back-to-heading t)
2353 (let* ((level (save-match-data (funcall outline-level)))
2354 (down-head (make-string (1+ level) ?*)))
2355 (replace-match down-head nil t)
2356 (if org-adapt-indentation
2357 (org-fixup-indentation "^ " " " "^\\S-"))))
2358
2359 (defun org-map-tree (fun)
2360 "Call FUN for every heading underneath the current one."
2361 (org-back-to-heading)
2362 (let ((level (outline-level)))
2363 (save-excursion
2364 (funcall fun)
2365 (while (and (progn
2366 (outline-next-heading)
2367 (> (funcall outline-level) level))
2368 (not (eobp)))
2369 (funcall fun)))))
2370
2371 (defun org-map-region (fun beg end)
2372 "Call FUN for every heading between BEG and END."
2373 (let ((org-ignore-region t))
2374 (save-excursion
2375 (setq end (copy-marker end))
2376 (goto-char beg)
2377 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2378 (< (point) end))
2379 (funcall fun))
2380 (while (and (progn
2381 (outline-next-heading)
2382 (< (point) end))
2383 (not (eobp)))
2384 (funcall fun)))))
2385
2386 (defun org-fixup-indentation (from to prohibit)
2387 "Change the indentation in the current entry by re-replacing FROM with TO.
2388 However, if the regexp PROHIBIT matches at all, don't do anything.
2389 This is being used to change indentation along with the length of the
2390 heading marker. But if there are any lines which are not indented, nothing
2391 is changed at all."
2392 (save-excursion
2393 (let ((end (save-excursion (outline-next-heading)
2394 (point-marker))))
2395 (unless (save-excursion (re-search-forward prohibit end t))
2396 (while (re-search-forward from end t)
2397 (replace-match to)
2398 (beginning-of-line 2)))
2399 (move-marker end nil))))
2400
2401 ;;; Vertical tree motion, cutting and pasting of subtrees
2402
2403 (defun org-move-subtree-up (&optional arg)
2404 "Move the current subtree up past ARG headlines of the same level."
2405 (interactive "p")
2406 (org-move-subtree-down (- (prefix-numeric-value arg))))
2407
2408 (defun org-move-subtree-down (&optional arg)
2409 "Move the current subtree down past ARG headlines of the same level."
2410 (interactive "p")
2411 (setq arg (prefix-numeric-value arg))
2412 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2413 'outline-get-last-sibling))
2414 (ins-point (make-marker))
2415 (cnt (abs arg))
2416 beg end txt folded)
2417 ;; Select the tree
2418 (org-back-to-heading)
2419 (setq beg (point))
2420 (save-match-data
2421 (save-excursion (outline-end-of-heading)
2422 (setq folded (org-invisible-p)))
2423 (outline-end-of-subtree))
2424 (outline-next-heading)
2425 (setq end (point))
2426 ;; Find insertion point, with error handling
2427 (goto-char beg)
2428 (while (> cnt 0)
2429 (or (and (funcall movfunc) (looking-at outline-regexp))
2430 (progn (goto-char beg)
2431 (error "Cannot move past superior level or buffer limit")))
2432 (setq cnt (1- cnt)))
2433 (if (> arg 0)
2434 ;; Moving forward - still need to move over subtree
2435 (progn (outline-end-of-subtree)
2436 (outline-next-heading)
2437 (if (not (or (looking-at (concat "^" outline-regexp))
2438 (bolp)))
2439 (newline))))
2440 (move-marker ins-point (point))
2441 (setq txt (buffer-substring beg end))
2442 (delete-region beg end)
2443 (insert txt)
2444 (goto-char ins-point)
2445 (if folded (hide-subtree))
2446 (move-marker ins-point nil)))
2447
2448 (defvar org-subtree-clip ""
2449 "Clipboard for cut and paste of subtrees.
2450 This is actually only a copy of the kill, because we use the normal kill
2451 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2452
2453 (defvar org-subtree-clip-folded nil
2454 "Was the last copied subtree folded?
2455 This is used to fold the tree back after pasting.")
2456
2457 (defun org-cut-subtree ()
2458 "Cut the current subtree into the clipboard.
2459 This is a short-hand for marking the subtree and then cutting it."
2460 (interactive)
2461 (org-copy-subtree 'cut))
2462
2463 (defun org-copy-subtree (&optional cut)
2464 "Cut the current subtree into the clipboard.
2465 This is a short-hand for marking the subtree and then copying it.
2466 If CUT is non nil, actually cut the subtree."
2467 (interactive)
2468 (let (beg end folded)
2469 (org-back-to-heading)
2470 (setq beg (point))
2471 (save-match-data
2472 (save-excursion (outline-end-of-heading)
2473 (setq folded (org-invisible-p)))
2474 (outline-end-of-subtree))
2475 (if (equal (char-after) ?\n) (forward-char 1))
2476 (setq end (point))
2477 (goto-char beg)
2478 (when (> end beg)
2479 (setq org-subtree-clip-folded folded)
2480 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2481 (setq org-subtree-clip (current-kill 0))
2482 (message "%s: Subtree with %d characters"
2483 (if cut "Cut" "Copied")
2484 (length org-subtree-clip)))))
2485
2486 (defun org-paste-subtree (&optional level tree)
2487 "Paste the clipboard as a subtree, with modification of headline level.
2488 The entire subtree is promoted or demoted in order to match a new headline
2489 level. By default, the new level is derived from the visible headings
2490 before and after the insertion point, and taken to be the inferior headline
2491 level of the two. So if the previous visible heading is level 3 and the
2492 next is level 4 (or vice versa), level 4 will be used for insertion.
2493 This makes sure that the subtree remains an independent subtree and does
2494 not swallow low level entries.
2495
2496 You can also force a different level, either by using a numeric prefix
2497 argument, or by inserting the heading marker by hand. For example, if the
2498 cursor is after \"*****\", then the tree will be shifted to level 5.
2499
2500 If you want to insert the tree as is, just use \\[yank].
2501
2502 If optional TREE is given, use this text instead of the kill ring."
2503 (interactive "P")
2504 (unless (org-kill-is-subtree-p tree)
2505 (error
2506 (substitute-command-keys
2507 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2508 (let* ((txt (or tree (current-kill 0)))
2509 (^re (concat "^\\(" outline-regexp "\\)"))
2510 (re (concat "\\(" outline-regexp "\\)"))
2511 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2512
2513 (old-level (if (string-match ^re txt)
2514 (- (match-end 0) (match-beginning 0))
2515 -1))
2516 (force-level (cond (level (prefix-numeric-value level))
2517 ((string-match
2518 ^re_ (buffer-substring (point-at-bol) (point)))
2519 (- (match-end 0) (match-beginning 0)))
2520 (t nil)))
2521 (previous-level (save-excursion
2522 (condition-case nil
2523 (progn
2524 (outline-previous-visible-heading 1)
2525 (if (looking-at re)
2526 (- (match-end 0) (match-beginning 0))
2527 1))
2528 (error 1))))
2529 (next-level (save-excursion
2530 (condition-case nil
2531 (progn
2532 (outline-next-visible-heading 1)
2533 (if (looking-at re)
2534 (- (match-end 0) (match-beginning 0))
2535 1))
2536 (error 1))))
2537 (new-level (or force-level (max previous-level next-level)))
2538 (shift (if (or (= old-level -1)
2539 (= new-level -1)
2540 (= old-level new-level))
2541 0
2542 (- new-level old-level)))
2543 (shift1 shift)
2544 (delta (if (> shift 0) -1 1))
2545 (func (if (> shift 0) 'org-demote 'org-promote))
2546 beg end)
2547 ;; Remove the forces level indicator
2548 (if force-level
2549 (delete-region (point-at-bol) (point)))
2550 ;; Make sure we start at the beginning of an empty line
2551 (if (not (bolp)) (insert "\n"))
2552 (if (not (looking-at "[ \t]*$"))
2553 (progn (insert "\n") (backward-char 1)))
2554 ;; Paste
2555 (setq beg (point))
2556 (insert txt)
2557 (setq end (point))
2558 (goto-char beg)
2559 ;; Shift if necessary
2560 (if (= shift 0)
2561 (message "Pasted at level %d, without shift" new-level)
2562 (save-restriction
2563 (narrow-to-region beg end)
2564 (while (not (= shift 0))
2565 (org-map-region func (point-min) (point-max))
2566 (setq shift (+ delta shift)))
2567 (goto-char (point-min))
2568 (message "Pasted at level %d, with shift by %d levels"
2569 new-level shift1)))
2570 (if (and (eq org-subtree-clip (current-kill 0))
2571 org-subtree-clip-folded)
2572 ;; The tree was folded before it was killed/copied
2573 (hide-subtree))))
2574
2575 (defun org-kill-is-subtree-p (&optional txt)
2576 "Check if the current kill is an outline subtree, or a set of trees.
2577 Returns nil if kill does not start with a headline, or if the first
2578 headline level is not the largest headline level in the tree.
2579 So this will actually accept several entries of equal levels as well,
2580 which is OK for `org-paste-subtree'.
2581 If optional TXT is given, check this string instead of the current kill."
2582 (let* ((kill (or txt (current-kill 0) ""))
2583 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2584 (- (match-end 0) (match-beginning 0))))
2585 (re (concat "^" outline-regexp))
2586 (start 1))
2587 (if (not start-level)
2588 nil ;; does not even start with a heading
2589 (catch 'exit
2590 (while (setq start (string-match re kill (1+ start)))
2591 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2592 (throw 'exit nil)))
2593 t))))
2594
2595 (defun org-archive-subtree ()
2596 "Move the current subtree to the archive.
2597 The archive can be a certain top-level heading in the current file, or in
2598 a different file. The tree will be moved to that location, the subtree
2599 heading be marked DONE, and the current time will be added."
2600 (interactive)
2601 ;; Save all relevant TODO keyword-relatex variables
2602 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2603 (tr-org-todo-keywords org-todo-keywords)
2604 (tr-org-todo-interpretation org-todo-interpretation)
2605 (tr-org-done-string org-done-string)
2606 (tr-org-todo-regexp org-todo-regexp)
2607 (tr-org-todo-line-regexp org-todo-line-regexp)
2608 (this-buffer (current-buffer))
2609 file heading buffer level newfile-p)
2610 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2611 (progn
2612 (setq file (format (match-string 1 org-archive-location)
2613 (file-name-nondirectory (buffer-file-name)))
2614 heading (match-string 2 org-archive-location)))
2615 (error "Invalid `org-archive-location'"))
2616 (if (> (length file) 0)
2617 (setq newfile-p (not (file-exists-p file))
2618 buffer (find-file-noselect file))
2619 (setq buffer (current-buffer)))
2620 (unless buffer
2621 (error "Cannot access file \"%s\"" file))
2622 (if (and (> (length heading) 0)
2623 (string-match "^\\*+" heading))
2624 (setq level (match-end 0))
2625 (setq heading nil level 0))
2626 (save-excursion
2627 (org-copy-subtree) ; We first only copy, in case something goes wrong
2628 (set-buffer buffer)
2629 ;; Enforce org-mode for the archive buffer
2630 (if (not (eq major-mode 'org-mode))
2631 ;; Force the mode for future visits.
2632 (let ((org-insert-mode-line-in-empty-file t))
2633 (call-interactively 'org-mode)))
2634 (when newfile-p
2635 (goto-char (point-max))
2636 (insert (format "\nArchived entries from file %s\n\n"
2637 (buffer-file-name this-buffer))))
2638 ;; Force the TODO keywords of the original buffer
2639 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2640 (org-todo-keywords tr-org-todo-keywords)
2641 (org-todo-interpretation tr-org-todo-interpretation)
2642 (org-done-string tr-org-done-string)
2643 (org-todo-regexp tr-org-todo-regexp)
2644 (org-todo-line-regexp tr-org-todo-line-regexp))
2645 (goto-char (point-min))
2646 (if heading
2647 (progn
2648 (if (re-search-forward
2649 (concat "\\(^\\|\r\\)"
2650 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2651 nil t)
2652 (goto-char (match-end 0))
2653 ;; Heading not found, just insert it at the end
2654 (goto-char (point-max))
2655 (or (bolp) (insert "\n"))
2656 (insert "\n" heading "\n")
2657 (end-of-line 0))
2658 ;; Make the heading visible, and the following as well
2659 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2660 (if (re-search-forward
2661 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2662 nil t)
2663 (progn (goto-char (match-beginning 0)) (insert "\n")
2664 (beginning-of-line 0))
2665 (goto-char (point-max)) (insert "\n")))
2666 (goto-char (point-max)) (insert "\n"))
2667 ;; Paste
2668 (org-paste-subtree (1+ level))
2669 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2670 (if org-archive-mark-done
2671 (org-todo (length org-todo-keywords)))
2672 ;; Move cursor to right after the TODO keyword
2673 (when org-archive-stamp-time
2674 (beginning-of-line 1)
2675 (looking-at org-todo-line-regexp)
2676 (goto-char (or (match-end 2) (match-beginning 3)))
2677 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2678 (current-time))
2679 ")"))
2680 ;; Save the buffer, if it is not the same buffer.
2681 (if (not (eq this-buffer buffer)) (save-buffer))))
2682 ;; Here we are back in the original buffer. Everything seems to have
2683 ;; worked. So now cut the tree and finish up.
2684 (org-cut-subtree)
2685 (if (looking-at "[ \t]*$") (kill-line))
2686 (message "Subtree archived %s"
2687 (if (eq this-buffer buffer)
2688 (concat "under heading: " heading)
2689 (concat "in file: " (abbreviate-file-name file))))))
2690
2691 ;;; Completion
2692
2693 (defun org-complete (&optional arg)
2694 "Perform completion on word at point.
2695 At the beginning of a headline, this completes TODO keywords as given in
2696 `org-todo-keywords'.
2697 If the current word is preceded by a backslash, completes the TeX symbols
2698 that are supported for HTML support.
2699 If the current word is preceded by \"#+\", completes special words for
2700 setting file options.
2701 At all other locations, this simply calls `ispell-complete-word'."
2702 (interactive "P")
2703 (catch 'exit
2704 (let* ((end (point))
2705 (beg (save-excursion
2706 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2707 (skip-chars-backward "a-zA-Z0-9_:$")
2708 (point)))
2709 (texp (equal (char-before beg) ?\\))
2710 (form (equal (char-before beg) ?=))
2711 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2712 beg)
2713 "#+"))
2714 (pattern (buffer-substring-no-properties beg end))
2715 (completion-ignore-case opt)
2716 (type nil)
2717 (table (cond
2718 (opt
2719 (setq type :opt)
2720 (mapcar (lambda (x)
2721 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2722 (cons (match-string 2 x) (match-string 1 x)))
2723 (org-split-string (org-get-current-options) "\n")))
2724 (texp
2725 (setq type :tex)
2726 org-html-entities)
2727 (form
2728 (setq type :form)
2729 '(("sum") ("sumv") ("sumh")))
2730 ((string-match "\\`\\*+[ \t]*\\'"
2731 (buffer-substring (point-at-bol) beg))
2732 (setq type :todo)
2733 (mapcar 'list org-todo-keywords))
2734 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2735 (completion (try-completion pattern table)))
2736 (cond ((eq completion t)
2737 (if (equal type :opt)
2738 (insert (substring (cdr (assoc (upcase pattern) table))
2739 (length pattern)))))
2740 ((null completion)
2741 (message "Can't find completion for \"%s\"" pattern)
2742 (ding))
2743 ((not (string= pattern completion))
2744 (delete-region beg end)
2745 (if (string-match " +$" completion)
2746 (setq completion (replace-match "" t t completion)))
2747 (insert completion)
2748 (if (get-buffer-window "*Completions*")
2749 (delete-window (get-buffer-window "*Completions*")))
2750 (if (and (eq type :todo)
2751 (assoc completion table))
2752 (insert " "))
2753 (if (and (equal type :opt) (assoc completion table))
2754 (message (substitute-command-keys
2755 "Press \\[org-complete] again to insert example settings"))))
2756 (t
2757 (message "Making completion list...")
2758 (let ((list (sort (all-completions pattern table) 'string<)))
2759 (with-output-to-temp-buffer "*Completions*"
2760 (display-completion-list list)))
2761 (message "Making completion list...%s" "done"))))))
2762
2763 ;;; Comments, TODO and DEADLINE
2764
2765 (defun org-toggle-comment ()
2766 "Change the COMMENT state of an entry."
2767 (interactive)
2768 (save-excursion
2769 (org-back-to-heading)
2770 (if (looking-at (concat outline-regexp
2771 "\\( +\\<" org-comment-string "\\>\\)"))
2772 (replace-match "" t t nil 1)
2773 (if (looking-at outline-regexp)
2774 (progn
2775 (goto-char (match-end 0))
2776 (insert " " org-comment-string))))))
2777
2778 (defvar org-last-todo-state-is-todo nil
2779 "This is non-nil when the last TODO state change led to a TODO state.
2780 If the last change removed the TODO tag or switched to DONE, then
2781 this is nil.")
2782
2783 (defun org-todo (&optional arg)
2784 "Change the TODO state of an item.
2785 The state of an item is given by a keyword at the start of the heading,
2786 like
2787 *** TODO Write paper
2788 *** DONE Call mom
2789
2790 The different keywords are specified in the variable `org-todo-keywords'. By
2791 default the available states are \"TODO\" and \"DONE\".
2792 So for this example: when the item starts with TODO, it is changed to DONE.
2793 When it starts with DONE, the DONE is removed. And when neither TODO nor
2794 DONE are present, add TODO at the beginning of the heading.
2795
2796 With prefix arg, use completion to determined the new state. With numeric
2797 prefix arg, switch to that state."
2798 (interactive "P")
2799 (save-excursion
2800 (org-back-to-heading)
2801 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2802 (or (looking-at (concat " +" org-todo-regexp " *"))
2803 (looking-at " *"))
2804 (let* ((this (match-string 1))
2805 (completion-ignore-case t)
2806 (member (member this org-todo-keywords))
2807 (tail (cdr member))
2808 (state (cond
2809 ((equal arg '(4))
2810 ;; Read a state with completion
2811 (completing-read "State: " (mapcar (lambda(x) (list x))
2812 org-todo-keywords)
2813 nil t))
2814 (arg
2815 ;; user requests a specific state
2816 (nth (1- (prefix-numeric-value arg))
2817 org-todo-keywords))
2818 ((null member) (car org-todo-keywords))
2819 ((null tail) nil) ;; -> first entry
2820 ((eq org-todo-interpretation 'sequence)
2821 (car tail))
2822 ((memq org-todo-interpretation '(type priority))
2823 (if (eq this-command last-command)
2824 (car tail)
2825 (if (> (length tail) 0) org-done-string nil)))
2826 (t nil)))
2827 (next (if state (concat " " state " ") " ")))
2828 (replace-match next t t)
2829 (setq org-last-todo-state-is-todo
2830 (not (equal state org-done-string)))
2831 (run-hooks 'org-after-todo-state-change-hook)))
2832 ;; Fixup cursor location if close to the keyword
2833 (if (and (outline-on-heading-p)
2834 (not (bolp))
2835 (save-excursion (beginning-of-line 1)
2836 (looking-at org-todo-line-regexp))
2837 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2838 (progn
2839 (goto-char (or (match-end 2) (match-end 1)))
2840 (just-one-space))))
2841
2842 (defun org-show-todo-tree (arg)
2843 "Make a compact tree which shows all headlines marked with TODO.
2844 The tree will show the lines where the regexp matches, and all higher
2845 headlines above the match."
2846 (interactive "P")
2847 (let ((case-fold-search nil)
2848 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2849 (message "%d TODO entries found"
2850 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2851
2852 (defun org-deadline ()
2853 "Insert the DEADLINE: string to make a deadline.
2854 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2855 to modify it to the correct date."
2856 (interactive)
2857 (insert
2858 org-deadline-string " "
2859 (format-time-string (car org-time-stamp-formats)
2860 (org-read-date nil 'to-time)))
2861 (message (substitute-command-keys
2862 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2863
2864 (defun org-schedule ()
2865 "Insert the SCHEDULED: string to schedule a TODO item.
2866 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2867 to modify it to the correct date."
2868 (interactive)
2869 (insert
2870 org-scheduled-string " "
2871 (format-time-string (car org-time-stamp-formats)
2872 (org-read-date nil 'to-time)))
2873 (message (substitute-command-keys
2874 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2875
2876
2877 (defun org-occur (regexp &optional callback)
2878 "Make a compact tree which shows all matches of REGEXP.
2879 The tree will show the lines where the regexp matches, and all higher
2880 headlines above the match. It will also show the heading after the match,
2881 to make sure editing the matching entry is easy.
2882 If CALLBACK is non-nil, it is a function which is called to confirm
2883 that the match should indeed be shown."
2884 (interactive "sRegexp: ")
2885 (setq regexp (org-check-occur-regexp regexp))
2886 (let ((cnt 0))
2887 (save-excursion
2888 (goto-char (point-min))
2889 (hide-sublevels 1)
2890 (while (re-search-forward regexp nil t)
2891 (when (or (not callback)
2892 (funcall callback))
2893 (setq cnt (1+ cnt))
2894 (org-show-hierarchy-above))))
2895 (run-hooks 'org-occur-hook)
2896 (if (interactive-p)
2897 (message "%d match(es) for regexp %s" cnt regexp))
2898 cnt))
2899
2900 (defun org-show-hierarchy-above ()
2901 "Make sure point and the headings hierarchy above is visible."
2902 (if (org-on-heading-p t)
2903 (org-flag-heading nil) ; only show the heading
2904 (org-show-hidden-entry)) ; show entire entry
2905 (save-excursion
2906 (and org-show-following-heading
2907 (outline-next-heading)
2908 (org-flag-heading nil))) ; show the next heading
2909 (save-excursion ; show all higher headings
2910 (while (condition-case nil
2911 (progn (org-up-heading-all 1) t)
2912 (error nil))
2913 (org-flag-heading nil))))
2914
2915 ;;; Priorities
2916
2917 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2918 "Regular expression matching the priority indicator.")
2919
2920 (defvar org-remove-priority-next-time nil)
2921
2922 (defun org-priority-up ()
2923 "Increase the priority of the current item."
2924 (interactive)
2925 (org-priority 'up))
2926
2927 (defun org-priority-down ()
2928 "Decrease the priority of the current item."
2929 (interactive)
2930 (org-priority 'down))
2931
2932 (defun org-priority (&optional action)
2933 "Change the priority of an item by ARG.
2934 ACTION can be set, up, or down."
2935 (interactive)
2936 (setq action (or action 'set))
2937 (let (current new news have remove)
2938 (save-excursion
2939 (org-back-to-heading)
2940 (if (looking-at org-priority-regexp)
2941 (setq current (string-to-char (match-string 2))
2942 have t)
2943 (setq current org-default-priority))
2944 (cond
2945 ((eq action 'set)
2946 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2947 (setq new (read-char-exclusive))
2948 (cond ((equal new ?\ ) (setq remove t))
2949 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2950 (error "Priority must be between `%c' and `%c'"
2951 ?A org-lowest-priority))))
2952 ((eq action 'up)
2953 (setq new (1- current)))
2954 ((eq action 'down)
2955 (setq new (1+ current)))
2956 (t (error "Invalid action")))
2957 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2958 (setq news (format "%c" new))
2959 (if have
2960 (if remove
2961 (replace-match "" t t nil 1)
2962 (replace-match news t t nil 2))
2963 (if remove
2964 (error "No priority cookie found in line")
2965 (looking-at org-todo-line-regexp)
2966 (if (match-end 2)
2967 (progn
2968 (goto-char (match-end 2))
2969 (insert " [#" news "]"))
2970 (goto-char (match-beginning 3))
2971 (insert "[#" news "] ")))))
2972 (if remove
2973 (message "Priority removed")
2974 (message "Priority of current item set to %s" news))))
2975
2976
2977 (defun org-get-priority (s)
2978 "Find priority cookie and return priority."
2979 (save-match-data
2980 (if (not (string-match org-priority-regexp s))
2981 (* 1000 (- org-lowest-priority org-default-priority))
2982 (* 1000 (- org-lowest-priority
2983 (string-to-char (match-string 2 s)))))))
2984
2985 ;;; Timestamps
2986
2987 (defvar org-last-changed-timestamp nil)
2988
2989 (defun org-time-stamp (arg)
2990 "Prompt for a date/time and insert a time stamp.
2991 If the user specifies a time like HH:MM, or if this command is called
2992 with a prefix argument, the time stamp will contain date and time.
2993 Otherwise, only the date will be included. All parts of a date not
2994 specified by the user will be filled in from the current date/time.
2995 So if you press just return without typing anything, the time stamp
2996 will represent the current date/time. If there is already a timestamp
2997 at the cursor, it will be modified."
2998 (interactive "P")
2999 (let ((fmt (if arg (cdr org-time-stamp-formats)
3000 (car org-time-stamp-formats)))
3001 (org-time-was-given nil)
3002 time)
3003 (cond
3004 ((and (org-at-timestamp-p)
3005 (eq last-command 'org-time-stamp)
3006 (eq this-command 'org-time-stamp))
3007 (insert "--")
3008 (setq time (let ((this-command this-command))
3009 (org-read-date arg 'totime)))
3010 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3011 (insert (format-time-string fmt time)))
3012 ((org-at-timestamp-p)
3013 (setq time (let ((this-command this-command))
3014 (org-read-date arg 'totime)))
3015 (and (org-at-timestamp-p) (replace-match
3016 (setq org-last-changed-timestamp
3017 (format-time-string fmt time))
3018 t t))
3019 (message "Timestamp updated"))
3020 (t
3021 (setq time (let ((this-command this-command))
3022 (org-read-date arg 'totime)))
3023 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3024 (insert (format-time-string fmt time))))))
3025
3026 ;;; FIXME: Make the function take "Fri" as "next friday"
3027 (defun org-read-date (&optional with-time to-time)
3028 "Read a date and make things smooth for the user.
3029 The prompt will suggest to enter an ISO date, but you can also enter anything
3030 which will at least partially be understood by `parse-time-string'.
3031 Unrecognized parts of the date will default to the current day, month ,year,
3032 hour and minute. For example,
3033 3-2-5 --> 2003-02-05
3034 feb 15 --> currentyear-02-15
3035 sep 12 9 --> 2009-09-12
3036 12:45 --> today 12:45
3037 22 sept 0:34 --> currentyear-09-22 0:34
3038 12 --> currentyear-currentmonth-12
3039 etc.
3040 The function understands only English month and weekday abbreviations,
3041 but this can be configured with the variables `parse-time-months' and
3042 `parse-time-weekdays'.
3043
3044 While prompting, a calendar is popped up - you can also select the
3045 date with the mouse (button 1). The calendar shows a period of three
3046 month. To scroll it to other months, use the keys `>' and `<'.
3047 If you don't like the calendar, turn it off with
3048 \(setq org-popup-calendar-for-date-prompt nil).
3049
3050 With optional argument TO-TIME, the date will immediately be converted
3051 to an internal time.
3052 With an optional argument WITH-TIME, the prompt will suggest to also
3053 insert a time. Note that when WITH-TIME is not set, you can still
3054 enter a time, and this function will inform the calling routine about
3055 this change. The calling routine may then choose to change the format
3056 used to insert the time stamp into the buffer to include the time."
3057 (let* ((default-time
3058 ;; Default time is either today, or, when entering a range,
3059 ;; the range start.
3060 (if (save-excursion
3061 (re-search-backward
3062 (concat org-ts-regexp "--\\=")
3063 (- (point) 20) t))
3064 (apply
3065 'encode-time
3066 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3067 (parse-time-string (match-string 1))))
3068 (current-time)))
3069 (timestr (format-time-string
3070 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3071 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3072 ans ans1 ans2
3073 second minute hour day month year tl)
3074
3075 (if org-popup-calendar-for-date-prompt
3076 ;; Also show a calendar for date selection
3077 ;; Copied (with modifications) from planner.el by John Wiegley
3078 (save-excursion
3079 (save-window-excursion
3080 (calendar)
3081 (calendar-forward-day (- (time-to-days default-time)
3082 (calendar-absolute-from-gregorian
3083 (calendar-current-date))))
3084 (let* ((old-map (current-local-map))
3085 (map (copy-keymap calendar-mode-map))
3086 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3087 (define-key map (kbd "RET") 'org-calendar-select)
3088 (define-key map (if org-xemacs-p [button1] [mouse-1])
3089 'org-calendar-select)
3090 (define-key minibuffer-local-map [(meta shift left)]
3091 (lambda () (interactive)
3092 (org-eval-in-calendar '(calendar-backward-month 1))))
3093 (define-key minibuffer-local-map [(meta shift right)]
3094 (lambda () (interactive)
3095 (org-eval-in-calendar '(calendar-forward-month 1))))
3096 (define-key minibuffer-local-map [(shift up)]
3097 (lambda () (interactive)
3098 (org-eval-in-calendar '(calendar-backward-week 1))))
3099 (define-key minibuffer-local-map [(shift down)]
3100 (lambda () (interactive)
3101 (org-eval-in-calendar '(calendar-forward-week 1))))
3102 (define-key minibuffer-local-map [(shift left)]
3103 (lambda () (interactive)
3104 (org-eval-in-calendar '(calendar-backward-day 1))))
3105 (define-key minibuffer-local-map [(shift right)]
3106 (lambda () (interactive)
3107 (org-eval-in-calendar '(calendar-forward-day 1))))
3108 (define-key minibuffer-local-map ">"
3109 (lambda () (interactive)
3110 (org-eval-in-calendar '(scroll-calendar-left 1))))
3111 (define-key minibuffer-local-map "<"
3112 (lambda () (interactive)
3113 (org-eval-in-calendar '(scroll-calendar-right 1))))
3114 (unwind-protect
3115 (progn
3116 (use-local-map map)
3117 (setq ans (read-string prompt "" nil nil))
3118 (setq ans (or ans1 ans2 ans)))
3119 (use-local-map old-map)))))
3120 ;; Naked prompt only
3121 (setq ans (read-string prompt "" nil timestr)))
3122
3123 (if (string-match
3124 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3125 (progn
3126 (setq year (if (match-end 2)
3127 (string-to-number (match-string 2 ans))
3128 (string-to-number (format-time-string "%Y")))
3129 month (string-to-number (match-string 3 ans))
3130 day (string-to-number (match-string 4 ans)))
3131 (if (< year 100) (setq year (+ 2000 year)))
3132 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3133 t t ans))))
3134 (setq tl (parse-time-string ans)
3135 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3136 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3137 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3138 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3139 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3140 second (or (nth 0 tl) 0))
3141 (if (and (boundp 'org-time-was-given)
3142 (nth 2 tl))
3143 (setq org-time-was-given t))
3144 (if (< year 100) (setq year (+ 2000 year)))
3145 (if to-time
3146 (encode-time second minute hour day month year)
3147 (if (or (nth 1 tl) (nth 2 tl))
3148 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3149 (format "%04d-%02d-%02d" year month day)))))
3150
3151 (defun org-eval-in-calendar (form)
3152 "Eval FORM in the calendar window and return to current window.
3153 Also, store the cursor date in variable `ans2'."
3154 (let ((sw (selected-window)))
3155 (select-window (get-buffer-window "*Calendar*"))
3156 (eval form)
3157 (when (calendar-cursor-to-date)
3158 (let* ((date (calendar-cursor-to-date))
3159 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3160 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3161 (select-window sw)))
3162
3163 (defun org-calendar-select ()
3164 "Return to `org-read-date' with the date currently selected.
3165 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3166 (interactive)
3167 (when (calendar-cursor-to-date)
3168 (let* ((date (calendar-cursor-to-date))
3169 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3170 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3171 (if (active-minibuffer-window) (exit-minibuffer))))
3172
3173 (defun org-check-deadlines (ndays)
3174 "Check if there are any deadlines due or past due.
3175 A deadline is considered due if it happens within `org-deadline-warning-days'
3176 days from today's date. If the deadline appears in an entry marked DONE,
3177 it is not shown. The prefix arg NDAYS can be used to test that many
3178 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3179 (interactive "P")
3180 (let* ((org-warn-days
3181 (cond
3182 ((equal ndays '(4)) 100000)
3183 (ndays (prefix-numeric-value ndays))
3184 (t org-deadline-warning-days)))
3185 (case-fold-search nil)
3186 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3187 (callback
3188 (lambda ()
3189 (and (let ((d1 (time-to-days (current-time)))
3190 (d2 (time-to-days
3191 (org-time-string-to-time (match-string 1)))))
3192 (< (- d2 d1) org-warn-days))
3193 (not (org-entry-is-done-p))))))
3194 (message "%d deadlines past-due or due within %d days"
3195 (org-occur regexp callback)
3196 org-warn-days)))
3197
3198 (defun org-evaluate-time-range (&optional to-buffer)
3199 "Evaluate a time range by computing the difference between start and end.
3200 Normally the result is just printed in the echo area, but with prefix arg
3201 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3202 If the time range is actually in a table, the result is inserted into the
3203 next column.
3204 For time difference computation, a year is assumed to be exactly 365
3205 days in order to avoid rounding problems."
3206 (interactive "P")
3207 (save-excursion
3208 (unless (org-at-date-range-p)
3209 (goto-char (point-at-bol))
3210 (re-search-forward org-tr-regexp (point-at-eol) t))
3211 (if (not (org-at-date-range-p))
3212 (error "Not at a time-stamp range, and none found in current line")))
3213 (let* ((ts1 (match-string 1))
3214 (ts2 (match-string 2))
3215 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3216 (match-end (match-end 0))
3217 (time1 (org-time-string-to-time ts1))
3218 (time2 (org-time-string-to-time ts2))
3219 (t1 (time-to-seconds time1))
3220 (t2 (time-to-seconds time2))
3221 (diff (abs (- t2 t1)))
3222 (negative (< (- t2 t1) 0))
3223 ;; (ys (floor (* 365 24 60 60)))
3224 (ds (* 24 60 60))
3225 (hs (* 60 60))
3226 (fy "%dy %dd %02d:%02d")
3227 (fy1 "%dy %dd")
3228 (fd "%dd %02d:%02d")
3229 (fd1 "%dd")
3230 (fh "%02d:%02d")
3231 y d h m align)
3232 ;; FIXME: Should I re-introduce years, make year refer to same date?
3233 ;; This would be the only useful way to have years, actually.
3234 (if havetime
3235 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3236 y 0
3237 d (floor (/ diff ds)) diff (mod diff ds)
3238 h (floor (/ diff hs)) diff (mod diff hs)
3239 m (floor (/ diff 60)))
3240 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3241 y 0
3242 d (floor (+ (/ diff ds) 0.5))
3243 h 0 m 0))
3244 (if (not to-buffer)
3245 (message (org-make-tdiff-string y d h m))
3246 (when (org-at-table-p)
3247 (goto-char match-end)
3248 (setq align t)
3249 (and (looking-at " *|") (goto-char (match-end 0))))
3250 (if (looking-at
3251 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3252 (replace-match ""))
3253 (if negative (insert " -"))
3254 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3255 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3256 (insert " " (format fh h m))))
3257 (if align (org-table-align))
3258 (message "Time difference inserted"))))
3259
3260 (defun org-make-tdiff-string (y d h m)
3261 (let ((fmt "")
3262 (l nil))
3263 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3264 l (push y l)))
3265 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3266 l (push d l)))
3267 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3268 l (push h l)))
3269 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3270 l (push m l)))
3271 (apply 'format fmt (nreverse l))))
3272
3273 (defun org-time-string-to-time (s)
3274 (apply 'encode-time (org-parse-time-string s)))
3275
3276 (defun org-parse-time-string (s &optional nodefault)
3277 "Parse the standard Org-mode time string.
3278 This should be a lot faster than the normal `parse-time-string'.
3279 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3280 hour and minute fields will be nil if not given."
3281 (if (string-match org-ts-regexp1 s)
3282 (list 0
3283 (if (or (match-beginning 8) (not nodefault))
3284 (string-to-number (or (match-string 8 s) "0")))
3285 (if (or (match-beginning 7) (not nodefault))
3286 (string-to-number (or (match-string 7 s) "0")))
3287 (string-to-number (match-string 4 s))
3288 (string-to-number (match-string 3 s))
3289 (string-to-number (match-string 2 s))
3290 nil nil nil)
3291 (make-list 9 0)))
3292
3293 (defun org-timestamp-up (&optional arg)
3294 "Increase the date item at the cursor by one.
3295 If the cursor is on the year, change the year. If it is on the month or
3296 the day, change that.
3297 With prefix ARG, change by that many units."
3298 (interactive "p")
3299 (org-timestamp-change (prefix-numeric-value arg)))
3300
3301 (defun org-timestamp-down (&optional arg)
3302 "Decrease the date item at the cursor by one.
3303 If the cursor is on the year, change the year. If it is on the month or
3304 the day, change that.
3305 With prefix ARG, change by that many units."
3306 (interactive "p")
3307 (org-timestamp-change (- (prefix-numeric-value arg))))
3308
3309 (defun org-timestamp-up-day (&optional arg)
3310 "Increase the date in the time stamp by one day.
3311 With prefix ARG, change that many days."
3312 (interactive "p")
3313 (org-timestamp-change (prefix-numeric-value arg) 'day))
3314
3315 (defun org-timestamp-down-day (&optional arg)
3316 "Decrease the date in the time stamp by one day.
3317 With prefix ARG, change that many days."
3318 (interactive "p")
3319 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3320
3321 (defsubst org-pos-in-match-range (pos n)
3322 (and (match-beginning n)
3323 (<= (match-beginning n) pos)
3324 (>= (match-end n) pos)))
3325
3326 (defun org-at-timestamp-p ()
3327 "Determine if the cursor is at a timestamp."
3328 (interactive)
3329 (let* ((tsr org-ts-regexp2)
3330 (pos (point))
3331 (ans (or (looking-at tsr)
3332 (save-excursion
3333 (skip-chars-backward "^<\n\r\t")
3334 (if (> (point) 1) (backward-char 1))
3335 (and (looking-at tsr)
3336 (> (- (match-end 0) pos) -1))))))
3337 (and (boundp 'org-ts-what)
3338 (setq org-ts-what
3339 (cond
3340 ((org-pos-in-match-range pos 2) 'year)
3341 ((org-pos-in-match-range pos 3) 'month)
3342 ((org-pos-in-match-range pos 7) 'hour)
3343 ((org-pos-in-match-range pos 8) 'minute)
3344 ((or (org-pos-in-match-range pos 4)
3345 (org-pos-in-match-range pos 5)) 'day)
3346 (t 'day))))
3347 ans))
3348
3349 (defun org-timestamp-change (n &optional what)
3350 "Change the date in the time stamp at point.
3351 The date will be changed by N times WHAT. WHAT can be `day', `month',
3352 `year', `minute', `second'. If WHAT is not given, the cursor position
3353 in the timestamp determines what will be changed."
3354 (let ((fmt (car org-time-stamp-formats))
3355 org-ts-what
3356 (pos (point))
3357 ts time time0)
3358 (if (not (org-at-timestamp-p))
3359 (error "Not at a timestamp"))
3360 (setq org-ts-what (or what org-ts-what))
3361 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3362 (- (match-end 0) (match-beginning 0))))
3363 1)
3364 (cdr org-time-stamp-formats)
3365 (car org-time-stamp-formats)))
3366 (setq ts (match-string 0))
3367 (replace-match "")
3368 (setq time0 (org-parse-time-string ts))
3369 (setq time
3370 (apply 'encode-time
3371 (append
3372 (list (or (car time0) 0))
3373 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3374 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3375 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3376 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3377 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3378 (nthcdr 6 time0))))
3379 (if (eq what 'calendar)
3380 (let ((cal-date
3381 (save-excursion
3382 (save-match-data
3383 (set-buffer "*Calendar*")
3384 (calendar-cursor-to-date)))))
3385 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3386 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3387 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3388 (setcar time0 (or (car time0) 0))
3389 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3390 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3391 (setq time (apply 'encode-time time0))))
3392 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3393 (goto-char pos)
3394 ;; Try to recenter the calendar window, if any
3395 (if (and org-calendar-follow-timestamp-change
3396 (get-buffer-window "*Calendar*" t)
3397 (memq org-ts-what '(day month year)))
3398 (org-recenter-calendar (time-to-days time)))))
3399
3400 (defun org-recenter-calendar (date)
3401 "If the calendar is visible, recenter it to DATE."
3402 (let* ((win (selected-window))
3403 (cwin (get-buffer-window "*Calendar*" t)))
3404 (when cwin
3405 (select-window cwin)
3406 (calendar-goto-date (if (listp date) date
3407 (calendar-gregorian-from-absolute date)))
3408 (select-window win))))
3409
3410 (defun org-goto-calendar (&optional arg)
3411 "Go to the Emacs calendar at the current date.
3412 If there is a time stamp in the current line, go to that date.
3413 A prefix ARG can be used force the current date."
3414 (interactive "P")
3415 (let ((tsr org-ts-regexp) diff)
3416 (if (or (org-at-timestamp-p)
3417 (save-excursion
3418 (beginning-of-line 1)
3419 (looking-at (concat ".*" tsr))))
3420 (let ((d1 (time-to-days (current-time)))
3421 (d2 (time-to-days
3422 (org-time-string-to-time (match-string 1)))))
3423 (setq diff (- d2 d1))))
3424 (calendar)
3425 (calendar-goto-today)
3426 (if (and diff (not arg)) (calendar-forward-day diff))))
3427
3428 (defun org-date-from-calendar ()
3429 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3430 If there is already a time stamp at the cursor position, update it."
3431 (interactive)
3432 (org-timestamp-change 0 'calendar))
3433
3434 ;;; Agenda, and Diary Integration
3435
3436 ;;; Define the mode
3437
3438 (defvar org-agenda-mode-map (make-sparse-keymap)
3439 "Keymap for `org-agenda-mode'.")
3440
3441 (defvar org-agenda-menu)
3442 (defvar org-agenda-follow-mode nil)
3443 (defvar org-agenda-buffer-name "*Org Agenda*")
3444 (defvar org-agenda-redo-command nil)
3445 (defvar org-agenda-mode-hook nil)
3446
3447 ;;;###autoload
3448 (defun org-agenda-mode ()
3449 "Mode for time-sorted view on action items in Org-mode files.
3450
3451 The following commands are available:
3452
3453 \\{org-agenda-mode-map}"
3454 (interactive)
3455 (kill-all-local-variables)
3456 (setq major-mode 'org-agenda-mode)
3457 (setq mode-name "Org-Agenda")
3458 (use-local-map org-agenda-mode-map)
3459 (easy-menu-add org-agenda-menu)
3460 (if org-startup-truncated (setq truncate-lines t))
3461 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3462 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3463 (setq org-agenda-follow-mode nil)
3464 (easy-menu-change
3465 '("Agenda") "Agenda Files"
3466 (append
3467 (list
3468 ["Edit File List" (customize-variable 'org-agenda-files) t]
3469 "--")
3470 (mapcar 'org-file-menu-entry org-agenda-files)))
3471 (org-agenda-set-mode-name)
3472 (apply
3473 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3474 org-agenda-mode-hook))
3475
3476 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3477 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3478 (define-key org-agenda-mode-map " " 'org-agenda-show)
3479 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3480 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3481 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3482 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3483 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3484 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3485 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3486 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3487 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3488
3489 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3490 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3491 (while l (define-key org-agenda-mode-map
3492 (int-to-string (pop l)) 'digit-argument)))
3493
3494 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3495 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3496 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3497 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3498 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3499 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3500 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3501 (define-key org-agenda-mode-map "n" 'next-line)
3502 (define-key org-agenda-mode-map "p" 'previous-line)
3503 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3504 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3505 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3506 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3507 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3508 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3509 (eval-after-load "calendar"
3510 '(define-key calendar-mode-map org-calendar-to-agenda-key
3511 'org-calendar-goto-agenda))
3512 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3513 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3514 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3515 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3516 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3517 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3518 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3519 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3520 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3521 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3522 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3523 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3524 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3525
3526 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3527 "Local keymap for agenda entries from Org-mode.")
3528
3529 (define-key org-agenda-keymap
3530 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3531 (define-key org-agenda-keymap
3532 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3533
3534 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3535 '("Agenda"
3536 ("Agenda Files")
3537 "--"
3538 ["Show" org-agenda-show t]
3539 ["Go To (other window)" org-agenda-goto t]
3540 ["Go To (one window)" org-agenda-switch-to t]
3541 ["Follow Mode" org-agenda-follow-mode
3542 :style toggle :selected org-agenda-follow-mode :active t]
3543 "--"
3544 ["Cycle TODO" org-agenda-todo t]
3545 ("Reschedule"
3546 ["Reschedule +1 day" org-agenda-date-later t]
3547 ["Reschedule -1 day" org-agenda-date-earlier t]
3548 "--"
3549 ["Reschedule to ..." org-agenda-date-prompt t])
3550 ("Priority"
3551 ["Set Priority" org-agenda-priority t]
3552 ["Increase Priority" org-agenda-priority-up t]
3553 ["Decrease Priority" org-agenda-priority-down t]
3554 ["Show Priority" org-agenda-show-priority t])
3555 "--"
3556 ["Rebuild buffer" org-agenda-redo t]
3557 ["Goto Today" org-agenda-goto-today t]
3558 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3559 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3560 "--"
3561 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3562 :style radio :selected (equal org-agenda-ndays 1)]
3563 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3564 :style radio :selected (equal org-agenda-ndays 7)]
3565 "--"
3566 ["Include Diary" org-agenda-toggle-diary
3567 :style toggle :selected org-agenda-include-diary :active t]
3568 ["Use Time Grid" org-agenda-toggle-time-grid
3569 :style toggle :selected org-agenda-use-time-grid :active t]
3570 "--"
3571 ["New Diary Entry" org-agenda-diary-entry t]
3572 ("Calendar Commands"
3573 ["Goto Calendar" org-agenda-goto-calendar t]
3574 ["Phases of the Moon" org-agenda-phases-of-moon t]
3575 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3576 ["Holidays" org-agenda-holidays t]
3577 ["Convert" org-agenda-convert-date t])
3578 "--"
3579 ["Quit" org-agenda-quit t]
3580 ["Exit and Release Buffers" org-agenda-exit t]
3581 ))
3582
3583 (defvar org-agenda-markers nil
3584 "List of all currently active markers created by `org-agenda'.")
3585 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3586 "Creation time of the last agenda marker.")
3587
3588 (defun org-agenda-new-marker (&optional pos)
3589 "Return a new agenda marker.
3590 Org-mode keeps a list of these markers and resets them when they are
3591 no longer in use."
3592 (let ((m (copy-marker (or pos (point)))))
3593 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3594 (push m org-agenda-markers)
3595 m))
3596
3597 (defun org-agenda-maybe-reset-markers (&optional force)
3598 "Reset markers created by `org-agenda'. But only if they are old enough."
3599 (if (or force
3600 (> (- (time-to-seconds (current-time))
3601 org-agenda-last-marker-time)
3602 5))
3603 (while org-agenda-markers
3604 (move-marker (pop org-agenda-markers) nil))))
3605
3606 (defvar org-agenda-new-buffers nil
3607 "Buffers created to visit agenda files.")
3608
3609 (defun org-get-agenda-file-buffer (file)
3610 "Get a buffer visiting FILE. If the buffer needs to be created, add
3611 it to the list of buffers which might be released later."
3612 (let ((buf (find-buffer-visiting file)))
3613 (if buf
3614 buf ; just return it
3615 ;; Make a new buffer and remember it
3616 (setq buf (find-file-noselect file))
3617 (if buf (push buf org-agenda-new-buffers))
3618 buf)))
3619
3620 (defun org-release-buffers (blist)
3621 "Release all buffers in list, asking the user for confirmation when needed.
3622 When a buffer is unmodified, it is just killed. When modified, it is saved
3623 \(if the user agrees) and then killed."
3624 (let (buf file)
3625 (while (setq buf (pop blist))
3626 (setq file (buffer-file-name buf))
3627 (when (and (buffer-modified-p buf)
3628 file
3629 (y-or-n-p (format "Save file %s? " file)))
3630 (with-current-buffer buf (save-buffer)))
3631 (kill-buffer buf))))
3632
3633 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3634
3635 (defun org-timeline (&optional include-all)
3636 "Show a time-sorted view of the entries in the current org file.
3637 Only entries with a time stamp of today or later will be listed. With
3638 one \\[universal-argument] prefix argument, past entries will also be listed.
3639 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3640 under the current date.
3641 If the buffer contains an active region, only check the region for
3642 dates."
3643 (interactive "P")
3644 (require 'calendar)
3645 (org-agenda-maybe-reset-markers 'force)
3646 (org-compile-prefix-format org-timeline-prefix-format)
3647 (let* ((dopast include-all)
3648 (dotodo (equal include-all '(16)))
3649 (entry (buffer-file-name))
3650 (org-agenda-files (list (buffer-file-name)))
3651 (date (calendar-current-date))
3652 (win (selected-window))
3653 (pos1 (point))
3654 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3655 (end (if (org-region-active-p) (region-end) (point-max)))
3656 (day-numbers (org-get-all-dates beg end 'no-ranges
3657 t)) ; always include today
3658 (today (time-to-days (current-time)))
3659 (org-respect-restriction t)
3660 (past t)
3661 s e rtn d)
3662 (setq org-agenda-redo-command
3663 (list 'progn
3664 (list 'switch-to-buffer-other-window (current-buffer))
3665 (list 'org-timeline include-all)))
3666 (if (not dopast)
3667 ;; Remove past dates from the list of dates.
3668 (setq day-numbers (delq nil (mapcar (lambda(x)
3669 (if (>= x today) x nil))
3670 day-numbers))))
3671 (switch-to-buffer-other-window
3672 (get-buffer-create org-agenda-buffer-name))
3673 (setq buffer-read-only nil)
3674 (erase-buffer)
3675 (org-agenda-mode) (setq buffer-read-only nil)
3676 (while (setq d (pop day-numbers))
3677 (if (and (>= d today)
3678 dopast
3679 past)
3680 (progn
3681 (setq past nil)
3682 (insert (make-string 79 ?-) "\n")))
3683 (setq date (calendar-gregorian-from-absolute d))
3684 (setq s (point))
3685 (if dotodo
3686 (setq rtn (org-agenda-get-day-entries
3687 entry date :todo :timestamp))
3688 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3689 (if (or rtn (equal d today))
3690 (progn
3691 (insert (calendar-day-name date) " "
3692 (number-to-string (extract-calendar-day date)) " "
3693 (calendar-month-name (extract-calendar-month date)) " "
3694 (number-to-string (extract-calendar-year date)) "\n")
3695 (put-text-property s (1- (point)) 'face
3696 'org-link)
3697 (if (equal d today)
3698 (put-text-property s (1- (point)) 'org-today t))
3699 (insert (org-finalize-agenda-entries rtn) "\n")
3700 (put-text-property s (1- (point)) 'day d))))
3701 (goto-char (point-min))
3702 (setq buffer-read-only t)
3703 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3704 (point-min)))
3705 (when (not org-select-timeline-window)
3706 (select-window win)
3707 (goto-char pos1))))
3708
3709 ;;;###autoload
3710 (defun org-agenda (&optional include-all start-day ndays)
3711 "Produce a weekly view from all files in variable `org-agenda-files'.
3712 The view will be for the current week, but from the overview buffer you
3713 will be able to go to other weeks.
3714 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3715 also be shown, under the current date.
3716 START-DAY defaults to TODAY, or to the most recent match for the weekday
3717 given in `org-agenda-start-on-weekday'.
3718 NDAYS defaults to `org-agenda-ndays'."
3719 (interactive "P")
3720 (org-agenda-maybe-reset-markers 'force)
3721 (org-compile-prefix-format org-agenda-prefix-format)
3722 (require 'calendar)
3723 (let* ((org-agenda-start-on-weekday
3724 (if (or (equal ndays 1)
3725 (and (null ndays) (equal 1 org-agenda-ndays)))
3726 nil org-agenda-start-on-weekday))
3727 (files (copy-sequence org-agenda-files))
3728 (win (selected-window))
3729 (today (time-to-days (current-time)))
3730 (sd (or start-day today))
3731 (start (if (or (null org-agenda-start-on-weekday)
3732 (< org-agenda-ndays 7))
3733 sd
3734 (let* ((nt (calendar-day-of-week
3735 (calendar-gregorian-from-absolute sd)))
3736 (n1 org-agenda-start-on-weekday)
3737 (d (- nt n1)))
3738 (- sd (+ (if (< d 0) 7 0) d)))))
3739 (day-numbers (list start))
3740 (inhibit-redisplay t)
3741 s e rtn rtnall file date d start-pos end-pos todayp nd)
3742 (setq org-agenda-redo-command
3743 (list 'org-agenda include-all start-day ndays))
3744 ;; Make the list of days
3745 (setq ndays (or ndays org-agenda-ndays)
3746 nd ndays)
3747 (while (> ndays 1)
3748 (push (1+ (car day-numbers)) day-numbers)
3749 (setq ndays (1- ndays)))
3750 (setq day-numbers (nreverse day-numbers))
3751 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3752 (progn
3753 (delete-other-windows)
3754 (switch-to-buffer-other-window
3755 (get-buffer-create org-agenda-buffer-name))))
3756 (setq buffer-read-only nil)
3757 (erase-buffer)
3758 (org-agenda-mode) (setq buffer-read-only nil)
3759 (set (make-local-variable 'starting-day) (car day-numbers))
3760 (set (make-local-variable 'include-all-loc) include-all)
3761 (when (and (or include-all org-agenda-include-all-todo)
3762 (member today day-numbers))
3763 (setq files org-agenda-files
3764 rtnall nil)
3765 (while (setq file (pop files))
3766 (catch 'nextfile
3767 (org-check-agenda-file file)
3768 (setq date (calendar-gregorian-from-absolute today)
3769 rtn (org-agenda-get-day-entries
3770 file date :todo))
3771 (setq rtnall (append rtnall rtn))))
3772 (when rtnall
3773 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3774 (add-text-properties (point-min) (1- (point))
3775 (list 'face 'org-link))
3776 (insert (org-finalize-agenda-entries rtnall) "\n")))
3777 (while (setq d (pop day-numbers))
3778 (setq date (calendar-gregorian-from-absolute d)
3779 s (point))
3780 (if (or (setq todayp (= d today))
3781 (and (not start-pos) (= d sd)))
3782 (setq start-pos (point))
3783 (if (and start-pos (not end-pos))
3784 (setq end-pos (point))))
3785 (setq files org-agenda-files
3786 rtnall nil)
3787 (while (setq file (pop files))
3788 (catch 'nextfile
3789 (org-check-agenda-file file)
3790 (setq rtn (org-agenda-get-day-entries file date))
3791 (setq rtnall (append rtnall rtn))))
3792 (if org-agenda-include-diary
3793 (progn
3794 (require 'diary-lib)
3795 (setq rtn (org-get-entries-from-diary date))
3796 (setq rtnall (append rtnall rtn))))
3797 (if (or rtnall org-agenda-show-all-dates)
3798 (progn
3799 (insert (format "%-9s %2d %s %4d\n"
3800 (calendar-day-name date)
3801 (extract-calendar-day date)
3802 (calendar-month-name (extract-calendar-month date))
3803 (extract-calendar-year date)))
3804 (put-text-property s (1- (point)) 'face
3805 'org-link)
3806 (if rtnall (insert
3807 (org-finalize-agenda-entries ;; FIXME: condition needed
3808 (org-agenda-add-time-grid-maybe
3809 rtnall nd todayp))
3810 "\n"))
3811 (put-text-property s (1- (point)) 'day d))))
3812 (goto-char (point-min))
3813 (setq buffer-read-only t)
3814 (if org-fit-agenda-window
3815 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3816 (/ (frame-height) 2)))
3817 (unless (and (pos-visible-in-window-p (point-min))
3818 (pos-visible-in-window-p (point-max)))
3819 (goto-char (1- (point-max)))
3820 (recenter -1)
3821 (if (not (pos-visible-in-window-p (or start-pos 1)))
3822 (progn
3823 (goto-char (or start-pos 1))
3824 (recenter 1))))
3825 (goto-char (or start-pos 1))
3826 (if (not org-select-agenda-window) (select-window win))
3827 (message "")))
3828
3829 (defun org-check-agenda-file (file)
3830 "Make sure FILE exists. If not, ask user what to do."
3831 ;; FIXME: this does not correctly change the menus
3832 ;; Could probably be fixed by explicitly going to the buffer.
3833 (when (not (file-exists-p file))
3834 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3835 file)
3836 (let ((r (downcase (read-char-exclusive))))
3837 (cond
3838 ((equal r ?r)
3839 (org-remove-file file)
3840 (throw 'nextfile t))
3841 (t (error "Abort"))))))
3842
3843 (defun org-agenda-quit ()
3844 "Exit agenda by removing the window or the buffer."
3845 (interactive)
3846 (let ((buf (current-buffer)))
3847 (if (not (one-window-p)) (delete-window))
3848 (kill-buffer buf)
3849 (org-agenda-maybe-reset-markers 'force)))
3850
3851 (defun org-agenda-exit ()
3852 "Exit agenda by removing the window or the buffer.
3853 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3854 Org-mode buffers visited directly by the user will not be touched."
3855 (interactive)
3856 (org-release-buffers org-agenda-new-buffers)
3857 (setq org-agenda-new-buffers nil)
3858 (org-agenda-quit))
3859
3860 (defun org-agenda-redo ()
3861 "Rebuild Agenda."
3862 (interactive)
3863 (eval org-agenda-redo-command))
3864
3865 (defun org-agenda-goto-today ()
3866 "Go to today."
3867 (interactive)
3868 (if (boundp 'starting-day)
3869 (let ((cmd (car org-agenda-redo-command))
3870 (iall (nth 1 org-agenda-redo-command))
3871 (nday (nth 3 org-agenda-redo-command)))
3872 (eval (list cmd iall nil nday)))
3873 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3874 (point-min)))))
3875
3876 (defun org-agenda-later (arg)
3877 "Go forward in time by `org-agenda-ndays' days.
3878 With prefix ARG, go forward that many times `org-agenda-ndays'."
3879 (interactive "p")
3880 (unless (boundp 'starting-day)
3881 (error "Not allowed"))
3882 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3883 (+ starting-day (* arg org-agenda-ndays))))
3884
3885 (defun org-agenda-earlier (arg)
3886 "Go back in time by `org-agenda-ndays' days.
3887 With prefix ARG, go back that many times `org-agenda-ndays'."
3888 (interactive "p")
3889 (unless (boundp 'starting-day)
3890 (error "Not allowed"))
3891 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3892 (- starting-day (* arg org-agenda-ndays))))
3893
3894 (defun org-agenda-week-view ()
3895 "Switch to weekly view for agenda."
3896 (interactive)
3897 (unless (boundp 'starting-day)
3898 (error "Not allowed"))
3899 (setq org-agenda-ndays 7)
3900 (org-agenda include-all-loc
3901 (or (get-text-property (point) 'day)
3902 starting-day))
3903 (org-agenda-set-mode-name)
3904 (message "Switched to week view"))
3905
3906 (defun org-agenda-day-view ()
3907 "Switch to daily view for agenda."
3908 (interactive)
3909 (unless (boundp 'starting-day)
3910 (error "Not allowed"))
3911 (setq org-agenda-ndays 1)
3912 (org-agenda include-all-loc
3913 (or (get-text-property (point) 'day)
3914 starting-day))
3915 (org-agenda-set-mode-name)
3916 (message "Switched to day view"))
3917
3918 (defun org-agenda-next-date-line (&optional arg)
3919 "Jump to the next line indicating a date in agenda buffer."
3920 (interactive "p")
3921 (beginning-of-line 1)
3922 (if (looking-at "^\\S-") (forward-char 1))
3923 (if (not (re-search-forward "^\\S-" nil t arg))
3924 (progn
3925 (backward-char 1)
3926 (error "No next date after this line in this buffer")))
3927 (goto-char (match-beginning 0)))
3928
3929 (defun org-agenda-previous-date-line (&optional arg)
3930 "Jump to the next line indicating a date in agenda buffer."
3931 (interactive "p")
3932 (beginning-of-line 1)
3933 (if (not (re-search-backward "^\\S-" nil t arg))
3934 (error "No previous date before this line in this buffer")))
3935
3936 ;; Initialize the highlight
3937 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3938 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3939 'face 'highlight)
3940
3941 (defun org-highlight (begin end &optional buffer)
3942 "Highlight a region with overlay."
3943 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3944 org-hl begin end (or buffer (current-buffer))))
3945
3946 (defun org-unhighlight ()
3947 "Detach overlay INDEX."
3948 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3949
3950
3951 (defun org-agenda-follow-mode ()
3952 "Toggle follow mode in an agenda buffer."
3953 (interactive)
3954 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3955 (org-agenda-set-mode-name)
3956 (message "Follow mode is %s"
3957 (if org-agenda-follow-mode "on" "off")))
3958
3959 (defun org-agenda-toggle-diary ()
3960 "Toggle diary inclusion in an agenda buffer."
3961 (interactive)
3962 (setq org-agenda-include-diary (not org-agenda-include-diary))
3963 (org-agenda-redo)
3964 (org-agenda-set-mode-name)
3965 (message "Diary inclusion turned %s"
3966 (if org-agenda-include-diary "on" "off")))
3967
3968 (defun org-agenda-toggle-time-grid ()
3969 "Toggle time-grid in an agenda buffer."
3970 (interactive)
3971 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3972 (org-agenda-redo)
3973 (org-agenda-set-mode-name)
3974 (message "Time-grid turned %s"
3975 (if org-agenda-use-time-grid "on" "off")))
3976
3977 (defun org-agenda-set-mode-name ()
3978 "Set the mode name to indicate all the small mode settings."
3979 (setq mode-name
3980 (concat "Org-Agenda"
3981 (if (equal org-agenda-ndays 1) " Day" "")
3982 (if (equal org-agenda-ndays 7) " Week" "")
3983 (if org-agenda-follow-mode " Follow" "")
3984 (if org-agenda-include-diary " Diary" "")
3985 (if org-agenda-use-time-grid " Grid" "")))
3986 (force-mode-line-update))
3987
3988 (defun org-agenda-post-command-hook ()
3989 (and (eolp) (not (bolp)) (backward-char 1))
3990 (if (and org-agenda-follow-mode
3991 (get-text-property (point) 'org-marker))
3992 (org-agenda-show)))
3993
3994 (defvar org-disable-diary nil) ;Dynamically-scoped param.
3995
3996 (defun org-get-entries-from-diary (date)
3997 "Get the (Emacs Calendar) diary entries for DATE."
3998 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
3999 (diary-display-hook '(fancy-diary-display))
4000 (list-diary-entries-hook
4001 (cons 'org-diary-default-entry list-diary-entries-hook))
4002 entries
4003 (org-disable-diary t))
4004 (save-excursion
4005 (save-window-excursion
4006 (list-diary-entries date 1)))
4007 (if (not (get-buffer fancy-diary-buffer))
4008 (setq entries nil)
4009 (with-current-buffer fancy-diary-buffer
4010 (setq buffer-read-only nil)
4011 (if (= (point-max) 1)
4012 ;; No entries
4013 (setq entries nil)
4014 ;; Omit the date and other unnecessary stuff
4015 (org-agenda-cleanup-fancy-diary)
4016 ;; Add prefix to each line and extend the text properties
4017 (if (= (point-max) 1)
4018 (setq entries nil)
4019 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4020 (set-buffer-modified-p nil)
4021 (kill-buffer fancy-diary-buffer)))
4022 (when entries
4023 (setq entries (org-split-string entries "\n"))
4024 (setq entries
4025 (mapcar
4026 (lambda (x)
4027 (setq x (org-format-agenda-item "" x "Diary" 'time))
4028 ;; Extend the text properties to the beginning of the line
4029 (add-text-properties
4030 0 (length x)
4031 (text-properties-at (1- (length x)) x)
4032 x)
4033 x)
4034 entries)))))
4035
4036 (defun org-agenda-cleanup-fancy-diary ()
4037 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
4038 This gets rid of the date, the underline under the date, and
4039 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4040 date. It also removes lines that contain only whitespace."
4041 (goto-char (point-min))
4042 (if (looking-at ".*?:[ \t]*")
4043 (progn
4044 (replace-match "")
4045 (re-search-forward "\n=+$" nil t)
4046 (replace-match "")
4047 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4048 (re-search-forward "\n=+$" nil t)
4049 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4050 (goto-char (point-min))
4051 (while (re-search-forward "^ +\n" nil t)
4052 (replace-match ""))
4053 (goto-char (point-min))
4054 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4055 (replace-match "")))
4056
4057 ;; Advise the add-to-diary-list function to allow org to jump to
4058 ;; diary entries. Wrapped into eval-after-load to avoid loading
4059 ;; advice unnecessarily
4060 (eval-after-load "diary-lib"
4061 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
4062 "Make the position visible."
4063 (if (and org-disable-diary ;; called from org-agenda
4064 (stringp string)
4065 (buffer-file-name))
4066 (add-text-properties
4067 0 (length string)
4068 (list 'mouse-face 'highlight
4069 'keymap org-agenda-keymap
4070 'help-echo
4071 (format
4072 "mouse-2 or RET jump to diary file %s"
4073 (abbreviate-file-name (buffer-file-name)))
4074 'org-agenda-diary-link t
4075 'org-marker (org-agenda-new-marker (point-at-bol)))
4076 string))))
4077
4078 (defun org-diary-default-entry ()
4079 "Add a dummy entry to the diary.
4080 Needed to avoid empty dates which mess up holiday display."
4081 ;; Catch the error if dealing with the new add-to-diary-alist
4082 (condition-case nil
4083 (add-to-diary-list original-date "Org-mode dummy" "")
4084 (error
4085 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
4086
4087 (defun org-add-file (&optional file)
4088 "Add current file to the list of files in variable `org-agenda-files'.
4089 These are the files which are being checked for agenda entries.
4090 Optional argument FILE means, use this file instead of the current.
4091 It is possible (but not recommended) to add this function to the
4092 `org-mode-hook'."
4093 (interactive)
4094 (catch 'exit
4095 (let* ((file (or file (buffer-file-name)
4096 (if (interactive-p)
4097 (error "Buffer is not visiting a file")
4098 (throw 'exit nil))))
4099 (true-file (file-truename file))
4100 (afile (abbreviate-file-name file))
4101 (present (delq nil (mapcar
4102 (lambda (x)
4103 (equal true-file (file-truename x)))
4104 org-agenda-files))))
4105 (if (not present)
4106 (progn
4107 (setq org-agenda-files
4108 (cons afile org-agenda-files))
4109 ;; Make sure custom.el does not end up with Org-mode
4110 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4111 (customize-save-variable 'org-agenda-files org-agenda-files))
4112 (org-install-agenda-files-menu)
4113 (message "Added file: %s" afile))
4114 (message "File was already in list: %s" afile)))))
4115
4116 (defun org-remove-file (&optional file)
4117 "Remove current file from the list of files in variable `org-agenda-files'.
4118 These are the files which are being checked for agenda entries.
4119 Optional argument FILE means, use this file instead of the current."
4120 (interactive)
4121 (let* ((file (or file (buffer-file-name)))
4122 (true-file (file-truename file))
4123 (afile (abbreviate-file-name file))
4124 (files (delq nil (mapcar
4125 (lambda (x)
4126 (if (equal true-file
4127 (file-truename x))
4128 nil x))
4129 org-agenda-files))))
4130 (if (not (= (length files) (length org-agenda-files)))
4131 (progn
4132 (setq org-agenda-files files)
4133 (customize-save-variable 'org-agenda-files org-agenda-files)
4134 (org-install-agenda-files-menu)
4135 (message "Removed file: %s" afile))
4136 (message "File was not in list: %s" afile))))
4137
4138 (defun org-file-menu-entry (file)
4139 (vector file (list 'find-file file) t))
4140
4141 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4142 "Return a list of all relevant day numbers from BEG to END buffer positions.
4143 If NO-RANGES is non-nil, include only the start and end dates of a range,
4144 not every single day in the range. If FORCE-TODAY is non-nil, make
4145 sure that TODAY is included in the list."
4146 (let (dates date day day1 day2 ts1 ts2)
4147 (if force-today
4148 (setq dates (list (time-to-days (current-time)))))
4149 (save-excursion
4150 (goto-char beg)
4151 (while (re-search-forward org-ts-regexp end t)
4152 (setq day (time-to-days (org-time-string-to-time
4153 (substring (match-string 1) 0 10))))
4154 (or (memq day dates) (push day dates)))
4155 (unless no-ranges
4156 (goto-char beg)
4157 (while (re-search-forward org-tr-regexp end t)
4158 (setq ts1 (substring (match-string 1) 0 10)
4159 ts2 (substring (match-string 2) 0 10)
4160 day1 (time-to-days (org-time-string-to-time ts1))
4161 day2 (time-to-days (org-time-string-to-time ts2)))
4162 (while (< (setq day1 (1+ day1)) day2)
4163 (or (memq day1 dates) (push day1 dates)))))
4164 (sort dates '<))))
4165
4166 ;;;###autoload
4167 (defun org-diary (&rest args)
4168 "Return diary information from org-files.
4169 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4170 It accesses org files and extracts information from those files to be
4171 listed in the diary. The function accepts arguments specifying what
4172 items should be listed. The following arguments are allowed:
4173
4174 :timestamp List the headlines of items containing a date stamp or
4175 date range matching the selected date. Deadlines will
4176 also be listed, on the expiration day.
4177
4178 :deadline List any deadlines past due, or due within
4179 `org-deadline-warning-days'. The listing occurs only
4180 in the diary for *today*, not at any other date. If
4181 an entry is marked DONE, it is no longer listed.
4182
4183 :scheduled List all items which are scheduled for the given date.
4184 The diary for *today* also contains items which were
4185 scheduled earlier and are not yet marked DONE.
4186
4187 :todo List all TODO items from the org-file. This may be a
4188 long list - so this is not turned on by default.
4189 Like deadlines, these entries only show up in the
4190 diary for *today*, not at any other date.
4191
4192 The call in the diary file should look like this:
4193
4194 &%%(org-diary) ~/path/to/some/orgfile.org
4195
4196 Use a separate line for each org file to check. Or, if you omit the file name,
4197 all files listed in `org-agenda-files' will be checked automatically:
4198
4199 &%%(org-diary)
4200
4201 If you don't give any arguments (as in the example above), the default
4202 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4203 also be written as
4204
4205 &%%(org-diary :deadline :timestamp :scheduled)
4206
4207 The function expects the lisp variables `entry' and `date' to be provided
4208 by the caller, because this is how the calendar works. Don't use this
4209 function from a program - use `org-agenda-get-day-entries' instead."
4210 (org-agenda-maybe-reset-markers)
4211 (org-compile-prefix-format org-agenda-prefix-format)
4212 (setq args (or args '(:deadline :scheduled :timestamp)))
4213 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4214 (list entry)
4215 org-agenda-files))
4216 file rtn results)
4217 ;; If this is called during org-agenda, don't return any entries to
4218 ;; the calendar. Org Agenda will list these entries itself.
4219 (if org-disable-diary (setq files nil))
4220 (while (setq file (pop files))
4221 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4222 (setq results (append results rtn)))
4223 (concat (org-finalize-agenda-entries results) "\n")))
4224
4225 (defun org-agenda-get-day-entries (file date &rest args)
4226 "Does the work for `org-diary' and `org-agenda'.
4227 FILE is the path to a file to be checked for entries. DATE is date like
4228 the one returned by `calendar-current-date'. ARGS are symbols indicating
4229 which kind of entries should be extracted. For details about these, see
4230 the documentation of `org-diary'."
4231 (setq args (or args '(:deadline :scheduled :timestamp)))
4232 (let* ((org-startup-with-deadline-check nil)
4233 (org-startup-folded nil)
4234 (buffer (if (file-exists-p file)
4235 (org-get-agenda-file-buffer file)
4236 (error "No such file %s" file)))
4237 arg results rtn)
4238 (if (not buffer)
4239 ;; If file does not exist, make sure an error message ends up in diary
4240 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4241 (with-current-buffer buffer
4242 (unless (eq major-mode 'org-mode)
4243 (error "Agenda file %s is not in `org-mode'" file))
4244 (let ((case-fold-search nil))
4245 (save-excursion
4246 (save-restriction
4247 (if org-respect-restriction
4248 (if (org-region-active-p)
4249 ;; Respect a region to restrict search
4250 (narrow-to-region (region-beginning) (region-end)))
4251 ;; If we work for the calendar or many files,
4252 ;; get rid of any restriction
4253 (widen))
4254 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4255 (while (setq arg (pop args))
4256 (cond
4257 ((and (eq arg :todo)
4258 (equal date (calendar-current-date)))
4259 (setq rtn (org-agenda-get-todos))
4260 (setq results (append results rtn)))
4261 ((eq arg :timestamp)
4262 (setq rtn (org-agenda-get-blocks))
4263 (setq results (append results rtn))
4264 (setq rtn (org-agenda-get-timestamps))
4265 (setq results (append results rtn)))
4266 ((eq arg :scheduled)
4267 (setq rtn (org-agenda-get-scheduled))
4268 (setq results (append results rtn)))
4269 ((and (eq arg :deadline)
4270 (equal date (calendar-current-date)))
4271 (setq rtn (org-agenda-get-deadlines))
4272 (setq results (append results rtn))))))))
4273 results))))
4274
4275 (defun org-entry-is-done-p ()
4276 "Is the current entry marked DONE?"
4277 (save-excursion
4278 (and (re-search-backward "[\r\n]\\*" nil t)
4279 (looking-at org-nl-done-regexp))))
4280
4281 (defun org-at-date-range-p ()
4282 "Is the cursor inside a date range?"
4283 (interactive)
4284 (save-excursion
4285 (catch 'exit
4286 (let ((pos (point)))
4287 (skip-chars-backward "^<\r\n")
4288 (skip-chars-backward "<")
4289 (and (looking-at org-tr-regexp)
4290 (>= (match-end 0) pos)
4291 (throw 'exit t))
4292 (skip-chars-backward "^<\r\n")
4293 (skip-chars-backward "<")
4294 (and (looking-at org-tr-regexp)
4295 (>= (match-end 0) pos)
4296 (throw 'exit t)))
4297 nil)))
4298
4299 (defun org-agenda-get-todos ()
4300 "Return the TODO information for agenda display."
4301 (let* ((props (list 'face nil
4302 'done-face 'org-done
4303 'mouse-face 'highlight
4304 'keymap org-agenda-keymap
4305 'help-echo
4306 (format "mouse-2 or RET jump to org file %s"
4307 (abbreviate-file-name (buffer-file-name)))))
4308 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4309 "[^\n\r]*\\)"))
4310 marker priority
4311 ee txt)
4312 (goto-char (point-min))
4313 (while (re-search-forward regexp nil t)
4314 (goto-char (match-beginning 1))
4315 (setq marker (org-agenda-new-marker (point-at-bol))
4316 txt (org-format-agenda-item "" (match-string 1))
4317 priority
4318 (+ (org-get-priority txt)
4319 (if org-todo-kwd-priority-p
4320 (- org-todo-kwd-max-priority -2
4321 (length
4322 (member (match-string 2) org-todo-keywords)))
4323 1)))
4324 (add-text-properties
4325 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4326 'priority priority)
4327 props)
4328 txt)
4329 (push txt ee)
4330 (goto-char (match-end 1)))
4331 (nreverse ee)))
4332
4333 (defconst org-agenda-no-heading-message
4334 "No heading for this item in buffer or region.")
4335
4336 (defun org-agenda-get-timestamps ()
4337 "Return the date stamp information for agenda display."
4338 (let* ((props (list 'face nil
4339 'mouse-face 'highlight
4340 'keymap org-agenda-keymap
4341 'help-echo
4342 (format "mouse-2 or RET jump to org file %s"
4343 (abbreviate-file-name (buffer-file-name)))))
4344 (regexp (regexp-quote
4345 (substring
4346 (format-time-string
4347 (car org-time-stamp-formats)
4348 (apply 'encode-time ; DATE bound by calendar
4349 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4350 0 11)))
4351 marker hdmarker deadlinep scheduledp donep tmp priority
4352 ee txt timestr)
4353 (goto-char (point-min))
4354 (while (re-search-forward regexp nil t)
4355 (if (not (save-match-data (org-at-date-range-p)))
4356 (progn
4357 (setq marker (org-agenda-new-marker (match-beginning 0))
4358 tmp (buffer-substring (max (point-min)
4359 (- (match-beginning 0)
4360 org-ds-keyword-length))
4361 (match-beginning 0))
4362 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4363 deadlinep (string-match org-deadline-regexp tmp)
4364 scheduledp (string-match org-scheduled-regexp tmp)
4365 donep (org-entry-is-done-p))
4366 (if (string-match ">" timestr)
4367 ;; substring should only run to end of time stamp
4368 (setq timestr (substring timestr 0 (match-end 0))))
4369 (save-excursion
4370 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4371 (progn
4372 (goto-char (match-end 1))
4373 (setq hdmarker (org-agenda-new-marker))
4374 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4375 (setq txt (org-format-agenda-item
4376 (format "%s%s"
4377 (if deadlinep "Deadline: " "")
4378 (if scheduledp "Scheduled: " ""))
4379 (match-string 1) nil timestr)))
4380 (setq txt org-agenda-no-heading-message))
4381 (setq priority (org-get-priority txt))
4382 (add-text-properties
4383 0 (length txt) (append (list 'org-marker marker
4384 'org-hd-marker hdmarker) props)
4385 txt)
4386 (if deadlinep
4387 (add-text-properties
4388 0 (length txt)
4389 (list 'face
4390 (if donep 'org-done 'org-warning)
4391 'undone-face 'org-warning
4392 'done-face 'org-done
4393 'priority (+ 100 priority))
4394 txt)
4395 (if scheduledp
4396 (add-text-properties
4397 0 (length txt)
4398 (list 'face 'org-scheduled-today
4399 'undone-face 'org-scheduled-today
4400 'done-face 'org-done
4401 priority (+ 99 priority))
4402 txt)
4403 (add-text-properties
4404 0 (length txt)
4405 (list 'priority priority) txt)))
4406 (push txt ee))
4407 (outline-next-heading))))
4408 (nreverse ee)))
4409
4410 (defun org-agenda-get-deadlines ()
4411 "Return the deadline information for agenda display."
4412 (let* ((wdays org-deadline-warning-days)
4413 (props (list 'mouse-face 'highlight
4414 'keymap org-agenda-keymap
4415 'help-echo
4416 (format "mouse-2 or RET jump to org file %s"
4417 (abbreviate-file-name (buffer-file-name)))))
4418 (regexp org-deadline-time-regexp)
4419 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4420 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4421 d2 diff pos pos1
4422 ee txt head)
4423 (goto-char (point-min))
4424 (while (re-search-forward regexp nil t)
4425 (setq pos (1- (match-beginning 1))
4426 d2 (time-to-days
4427 (org-time-string-to-time (match-string 1)))
4428 diff (- d2 d1))
4429 ;; When to show a deadline in the calendar:
4430 ;; If the expiration is within wdays warning time.
4431 ;; Past-due deadlines are only shown on the current date
4432 (if (and (< diff wdays) todayp (not (= diff 0)))
4433 (save-excursion
4434 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4435 (progn
4436 (goto-char (match-end 0))
4437 (setq pos1 (match-end 1))
4438 (setq head (buffer-substring-no-properties
4439 (point)
4440 (progn (skip-chars-forward "^\r\n")
4441 (point))))
4442 (if (string-match org-looking-at-done-regexp head)
4443 (setq txt nil)
4444 (setq txt (org-format-agenda-item
4445 (format "In %3d d.: " diff) head))))
4446 (setq txt org-agenda-no-heading-message))
4447 (when txt
4448 (add-text-properties
4449 0 (length txt)
4450 (append
4451 (list 'org-marker (org-agenda-new-marker pos)
4452 'org-hd-marker (org-agenda-new-marker pos1)
4453 'priority (+ (- 10 diff) (org-get-priority txt))
4454 'face (cond ((<= diff 0) 'org-warning)
4455 ((<= diff 5) 'org-scheduled-previously)
4456 (t nil))
4457 'undone-face (cond
4458 ((<= diff 0) 'org-warning)
4459 ((<= diff 5) 'org-scheduled-previously)
4460 (t nil))
4461 'done-face 'org-done)
4462 props)
4463 txt)
4464 (push txt ee)))))
4465 ee))
4466
4467 (defun org-agenda-get-scheduled ()
4468 "Return the scheduled information for agenda display."
4469 (let* ((props (list 'face 'org-scheduled-previously
4470 'undone-face 'org-scheduled-previously
4471 'done-face 'org-done
4472 'mouse-face 'highlight
4473 'keymap org-agenda-keymap
4474 'help-echo
4475 (format "mouse-2 or RET jump to org file %s"
4476 (abbreviate-file-name (buffer-file-name)))))
4477 (regexp org-scheduled-time-regexp)
4478 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4479 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4480 d2 diff pos pos1
4481 ee txt head)
4482 (goto-char (point-min))
4483 (while (re-search-forward regexp nil t)
4484 (setq pos (1- (match-beginning 1))
4485 d2 (time-to-days
4486 (org-time-string-to-time (match-string 1)))
4487 diff (- d2 d1))
4488 ;; When to show a scheduled item in the calendar:
4489 ;; If it is on or past the date.
4490 (if (and (< diff 0) todayp)
4491 (save-excursion
4492 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4493 (progn
4494 (goto-char (match-end 0))
4495 (setq pos1 (match-end 1))
4496 (setq head (buffer-substring-no-properties
4497 (point)
4498 (progn (skip-chars-forward "^\r\n") (point))))
4499 (if (string-match org-looking-at-done-regexp head)
4500 (setq txt nil)
4501 (setq txt (org-format-agenda-item
4502 (format "Sched.%2dx: " (- 1 diff)) head))))
4503 (setq txt org-agenda-no-heading-message))
4504 (when txt
4505 (add-text-properties
4506 0 (length txt)
4507 (append (list 'org-marker (org-agenda-new-marker pos)
4508 'org-hd-marker (org-agenda-new-marker pos1)
4509 'priority (+ (- 5 diff) (org-get-priority txt)))
4510 props) txt)
4511 (push txt ee)))))
4512 ee))
4513
4514 (defun org-agenda-get-blocks ()
4515 "Return the date-range information for agenda display."
4516 (let* ((props (list 'face nil
4517 'mouse-face 'highlight
4518 'keymap org-agenda-keymap
4519 'help-echo
4520 (format "mouse-2 or RET jump to org file %s"
4521 (abbreviate-file-name (buffer-file-name)))))
4522 (regexp org-tr-regexp)
4523 (d0 (calendar-absolute-from-gregorian date))
4524 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4525 (goto-char (point-min))
4526 (while (re-search-forward regexp nil t)
4527 (setq timestr (match-string 0)
4528 s1 (match-string 1)
4529 s2 (match-string 2)
4530 d1 (time-to-days (org-time-string-to-time s1))
4531 d2 (time-to-days (org-time-string-to-time s2)))
4532 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4533 ;; Only allow days between the limits, because the normal
4534 ;; date stamps will catch the limits.
4535 (save-excursion
4536 (setq marker (org-agenda-new-marker (point)))
4537 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4538 (progn
4539 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4540 (goto-char (match-end 1))
4541 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4542 (setq txt (org-format-agenda-item
4543 (format (if (= d1 d2) "" "(%d/%d): ")
4544 (1+ (- d0 d1)) (1+ (- d2 d1)))
4545 (match-string 1) nil (if (= d0 d1) timestr))))
4546 (setq txt org-agenda-no-heading-message))
4547 (add-text-properties
4548 0 (length txt) (append (list 'org-marker marker
4549 'org-hd-marker hdmarker
4550 'priority (org-get-priority txt))
4551 props)
4552 txt)
4553 (push txt ee)))
4554 (outline-next-heading))
4555 ;; Sort the entries by expiration date.
4556 (nreverse ee)))
4557
4558
4559
4560 (defconst org-plain-time-of-day-regexp
4561 (concat
4562 "\\(\\<[012]?[0-9]"
4563 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4564 "\\(--?"
4565 "\\(\\<[012]?[0-9]"
4566 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4567 "\\)?")
4568 "Regular expression to match a plain time or time range.
4569 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4570 groups carry important information:
4571 0 the full match
4572 1 the first time, range or not
4573 8 the second time, if it is a range.")
4574
4575 (defconst org-stamp-time-of-day-regexp
4576 (concat
4577 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4578 "\\([012][0-9]:[0-5][0-9]\\)>"
4579 "\\(--?"
4580 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4581 "Regular expression to match a timestamp time or time range.
4582 After a match, the following groups carry important information:
4583 0 the full match
4584 1 date plus weekday, for backreferencing to make sure both times on same day
4585 2 the first time, range or not
4586 4 the second time, if it is a range.")
4587
4588 (defvar org-prefix-has-time nil
4589 "A flag, set by `org-compile-prefix-format'.
4590 The flag is set if the currently compiled format contains a `%t'.")
4591
4592 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4593 "Format TXT to be inserted into the agenda buffer.
4594 In particular, it adds the prefix and corresponding text properties. EXTRA
4595 must be a string and replaces the `%s' specifier in the prefix format.
4596 CATEGORY (string, symbol or nil) may be used to overule the default
4597 category taken from local variable or file name. It will replace the `%c'
4598 specifier in the format. DOTIME, when non-nil, indicates that a
4599 time-of-day should be extracted from TXT for sorting of this entry, and for
4600 the `%t' specifier in the format. When DOTIME is a string, this string is
4601 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4602 only the correctly processes TXT should be returned - this is used by
4603 `org-agenda-change-all-lines'."
4604 (save-match-data
4605 ;; Diary entries sometimes have extra whitespace at the beginning
4606 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4607 (let* ((category (or category
4608 org-category
4609 (if (buffer-file-name)
4610 (file-name-sans-extension
4611 (file-name-nondirectory (buffer-file-name)))
4612 "")))
4613 time ;; needed for the eval of the prefix format
4614 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4615 (time-of-day (and dotime (org-get-time-of-day ts)))
4616 stamp plain s0 s1 s2 rtn)
4617 (when (and dotime time-of-day org-prefix-has-time)
4618 ;; Extract starting and ending time and move them to prefix
4619 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4620 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4621 (setq s0 (match-string 0 ts)
4622 s1 (match-string (if plain 1 2) ts)
4623 s2 (match-string (if plain 8 4) ts))
4624
4625 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4626 ;; them, we might want to remove them there to avoid duplication.
4627 ;; The user can turn this off with a variable.
4628 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4629 (string-match (concat (regexp-quote s0) " *") txt)
4630 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4631 (= (match-beginning 0) 0)
4632 t))
4633 (setq txt (replace-match "" nil nil txt))))
4634 ;; Normalize the time(s) to 24 hour
4635 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4636 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4637
4638 ;; Create the final string
4639 (if noprefix
4640 (setq rtn txt)
4641 ;; Prepare the variables needed in the eval of the compiled format
4642 (setq time (cond (s2 (concat s1 "-" s2))
4643 (s1 (concat s1 "......"))
4644 (t ""))
4645 extra (or extra "")
4646 category (if (symbolp category) (symbol-name category) category))
4647 ;; Evaluate the compiled format
4648 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4649
4650 ;; And finally add the text properties
4651 (add-text-properties
4652 0 (length rtn) (list 'category (downcase category)
4653 'prefix-length (- (length rtn) (length txt))
4654 'time-of-day time-of-day
4655 'dotime dotime)
4656 rtn)
4657 rtn)))
4658
4659 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4660 (catch 'exit
4661 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4662 ((and todayp (member 'today (car org-agenda-time-grid))))
4663 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4664 ((member 'weekly (car org-agenda-time-grid)))
4665 (t (throw 'exit list)))
4666 (let* ((have (delq nil (mapcar
4667 (lambda (x) (get-text-property 1 'time-of-day x))
4668 list)))
4669 (string (nth 1 org-agenda-time-grid))
4670 (gridtimes (nth 2 org-agenda-time-grid))
4671 (req (car org-agenda-time-grid))
4672 (remove (member 'remove-match req))
4673 new time)
4674 (if (and (member 'require-timed req) (not have))
4675 ;; don't show empty grid
4676 (throw 'exit list))
4677 (while (setq time (pop gridtimes))
4678 (unless (and remove (member time have))
4679 (setq time (int-to-string time))
4680 (push (org-format-agenda-item
4681 nil string "" ;; FIXME: put a category?
4682 (concat (substring time 0 -2) ":" (substring time -2)))
4683 new)
4684 (put-text-property
4685 1 (length (car new)) 'face 'org-time-grid (car new))))
4686 (if (member 'time-up org-agenda-sorting-strategy)
4687 (append new list)
4688 (append list new)))))
4689
4690 (defun org-compile-prefix-format (format)
4691 "Compile the prefix format into a Lisp form that can be evaluated.
4692 The resulting form is returned and stored in the variable
4693 `org-prefix-format-compiled'."
4694 (setq org-prefix-has-time nil)
4695 (let ((start 0) varform vars var (s format) c f opt)
4696 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4697 s start)
4698 (setq var (cdr (assoc (match-string 4 s)
4699 '(("c" . category) ("t" . time) ("s" . extra))))
4700 c (or (match-string 3 s) "")
4701 opt (match-beginning 1)
4702 start (1+ (match-beginning 0)))
4703 (if (equal var 'time) (setq org-prefix-has-time t))
4704 (setq f (concat "%" (match-string 2 s) "s"))
4705 (if opt
4706 (setq varform
4707 `(if (equal "" ,var)
4708 ""
4709 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4710 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4711 (setq s (replace-match "%s" t nil s))
4712 (push varform vars))
4713 (setq vars (nreverse vars))
4714 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4715
4716 (defun org-get-time-of-day (s &optional string)
4717 "Check string S for a time of day.
4718 If found, return it as a military time number between 0 and 2400.
4719 If not found, return nil.
4720 The optional STRING argument forces conversion into a 5 character wide string
4721 HH:MM."
4722 (save-match-data
4723 (when
4724 (or
4725 (string-match
4726 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4727 (string-match
4728 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4729 (let* ((t0 (+ (* 100
4730 (+ (string-to-number (match-string 1 s))
4731 (if (and (match-beginning 4)
4732 (equal (downcase (match-string 4 s)) "pm"))
4733 12 0)))
4734 (if (match-beginning 3)
4735 (string-to-number (match-string 3 s))
4736 0)))
4737 (t1 (concat " " (int-to-string t0))))
4738 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4739
4740 (defun org-finalize-agenda-entries (list)
4741 "Sort and concatenate the agenda items."
4742 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4743
4744 (defsubst org-cmp-priority (a b)
4745 "Compare the priorities of strings A and B."
4746 (let ((pa (or (get-text-property 1 'priority a) 0))
4747 (pb (or (get-text-property 1 'priority b) 0)))
4748 (cond ((> pa pb) +1)
4749 ((< pa pb) -1)
4750 (t nil))))
4751
4752 (defsubst org-cmp-category (a b)
4753 "Compare the string values of categories of strings A and B."
4754 (let ((ca (or (get-text-property 1 'category a) ""))
4755 (cb (or (get-text-property 1 'category b) "")))
4756 (cond ((string-lessp ca cb) -1)
4757 ((string-lessp cb ca) +1)
4758 (t nil))))
4759
4760 (defsubst org-cmp-time (a b)
4761 "Compare the time-of-day values of strings A and B."
4762 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4763 (ta (or (get-text-property 1 'time-of-day a) def))
4764 (tb (or (get-text-property 1 'time-of-day b) def)))
4765 (cond ((< ta tb) -1)
4766 ((< tb ta) +1)
4767 (t nil))))
4768
4769 (defun org-entries-lessp (a b)
4770 "Predicate for sorting agenda entries."
4771 ;; The following variables will be used when the form is evaluated.
4772 (let* ((time-up (org-cmp-time a b))
4773 (time-down (if time-up (- time-up) nil))
4774 (priority-up (org-cmp-priority a b))
4775 (priority-down (if priority-up (- priority-up) nil))
4776 (category-up (org-cmp-category a b))
4777 (category-down (if category-up (- category-up) nil))
4778 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4779 (cdr (assoc
4780 (eval (cons 'or org-agenda-sorting-strategy))
4781 '((-1 . t) (1 . nil) (nil . nil))))))
4782
4783 (defun org-agenda-show-priority ()
4784 "Show the priority of the current item.
4785 This priority is composed of the main priority given with the [#A] cookies,
4786 and by additional input from the age of a schedules or deadline entry."
4787 (interactive)
4788 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4789 (message "Priority is %d" (if pri pri -1000))))
4790
4791 (defun org-agenda-goto (&optional highlight)
4792 "Go to the Org-mode file which contains the item at point."
4793 (interactive)
4794 (let* ((marker (or (get-text-property (point) 'org-marker)
4795 (org-agenda-error)))
4796 (buffer (marker-buffer marker))
4797 (pos (marker-position marker)))
4798 (switch-to-buffer-other-window buffer)
4799 (widen)
4800 (goto-char pos)
4801 (when (eq major-mode 'org-mode)
4802 (org-show-hidden-entry)
4803 (save-excursion
4804 (and (outline-next-heading)
4805 (org-flag-heading nil)))) ; show the next heading
4806 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4807
4808 (defun org-agenda-switch-to ()
4809 "Go to the Org-mode file which contains the item at point."
4810 (interactive)
4811 (let* ((marker (or (get-text-property (point) 'org-marker)
4812 (org-agenda-error)))
4813 (buffer (marker-buffer marker))
4814 (pos (marker-position marker)))
4815 (switch-to-buffer buffer)
4816 (delete-other-windows)
4817 (widen)
4818 (goto-char pos)
4819 (when (eq major-mode 'org-mode)
4820 (org-show-hidden-entry)
4821 (save-excursion
4822 (and (outline-next-heading)
4823 (org-flag-heading nil)))))) ; show the next heading
4824
4825 (defun org-agenda-goto-mouse (ev)
4826 "Go to the Org-mode file which contains the item at the mouse click."
4827 (interactive "e")
4828 (mouse-set-point ev)
4829 (org-agenda-goto))
4830
4831 (defun org-agenda-show ()
4832 "Display the Org-mode file which contains the item at point."
4833 (interactive)
4834 (let ((win (selected-window)))
4835 (org-agenda-goto t)
4836 (select-window win)))
4837
4838 (defun org-agenda-recenter (arg)
4839 "Display the Org-mode file which contains the item at point and recenter."
4840 (interactive "P")
4841 (let ((win (selected-window)))
4842 (org-agenda-goto t)
4843 (recenter arg)
4844 (select-window win)))
4845
4846 (defun org-agenda-show-mouse (ev)
4847 "Display the Org-mode file which contains the item at the mouse click."
4848 (interactive "e")
4849 (mouse-set-point ev)
4850 (org-agenda-show))
4851
4852 (defun org-agenda-check-no-diary ()
4853 "Check if the entry is a diary link and abort if yes."
4854 (if (get-text-property (point) 'org-agenda-diary-link)
4855 (org-agenda-error)))
4856
4857 (defun org-agenda-error ()
4858 (error "Command not allowed in this line"))
4859
4860 (defvar org-last-heading-marker (make-marker)
4861 "Marker pointing to the headline that last changed its TODO state
4862 by a remote command from the agenda.")
4863
4864 (defun org-agenda-todo ()
4865 "Cycle TODO state of line at point, also in Org-mode file.
4866 This changes the line at point, all other lines in the agenda referring to
4867 the same tree node, and the headline of the tree node in the Org-mode file."
4868 (interactive)
4869 (org-agenda-check-no-diary)
4870 (let* ((col (current-column))
4871 (marker (or (get-text-property (point) 'org-marker)
4872 (org-agenda-error)))
4873 (buffer (marker-buffer marker))
4874 (pos (marker-position marker))
4875 (hdmarker (get-text-property (point) 'org-hd-marker))
4876 (buffer-read-only nil)
4877 newhead)
4878 (with-current-buffer buffer
4879 (widen)
4880 (goto-char pos)
4881 (org-show-hidden-entry)
4882 (save-excursion
4883 (and (outline-next-heading)
4884 (org-flag-heading nil))) ; show the next heading
4885 (org-todo)
4886 (forward-char 1)
4887 (setq newhead (org-get-heading))
4888 (save-excursion
4889 (org-back-to-heading)
4890 (move-marker org-last-heading-marker (point))))
4891 (beginning-of-line 1)
4892 (save-excursion
4893 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4894 (move-to-column col)))
4895
4896 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4897 "Change all lines in the agenda buffer which match HDMARKER.
4898 The new content of the line will be NEWHEAD (as modified by
4899 `org-format-agenda-item'). HDMARKER is checked with
4900 `equal' against all `org-hd-marker' text properties in the file.
4901 If FIXFACE is non-nil, the face of each item is modified acording to
4902 the new TODO state."
4903 (let* (props m pl undone-face done-face finish new dotime)
4904 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4905 (save-excursion
4906 (goto-char (point-max))
4907 (beginning-of-line 1)
4908 (while (not finish)
4909 (setq finish (bobp))
4910 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4911 (equal m hdmarker))
4912 (setq props (text-properties-at (point))
4913 dotime (get-text-property (point) 'dotime)
4914 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4915 pl (get-text-property (point) 'prefix-length)
4916 undone-face (get-text-property (point) 'undone-face)
4917 done-face (get-text-property (point) 'done-face))
4918 (move-to-column pl)
4919 (if (looking-at ".*")
4920 (progn
4921 (replace-match new t t)
4922 (beginning-of-line 1)
4923 (add-text-properties (point-at-bol) (point-at-eol) props)
4924 (if fixface
4925 (add-text-properties
4926 (point-at-bol) (point-at-eol)
4927 (list 'face
4928 (if org-last-todo-state-is-todo
4929 undone-face done-face))))
4930 (beginning-of-line 1))
4931 (error "Line update did not work")))
4932 (beginning-of-line 0)))))
4933
4934 (defun org-agenda-priority-up ()
4935 "Increase the priority of line at point, also in Org-mode file."
4936 (interactive)
4937 (org-agenda-priority 'up))
4938
4939 (defun org-agenda-priority-down ()
4940 "Decrease the priority of line at point, also in Org-mode file."
4941 (interactive)
4942 (org-agenda-priority 'down))
4943
4944 (defun org-agenda-priority (&optional force-direction)
4945 "Set the priority of line at point, also in Org-mode file.
4946 This changes the line at point, all other lines in the agenda referring to
4947 the same tree node, and the headline of the tree node in the Org-mode file."
4948 (interactive)
4949 (org-agenda-check-no-diary)
4950 (let* ((marker (or (get-text-property (point) 'org-marker)
4951 (org-agenda-error)))
4952 (buffer (marker-buffer marker))
4953 (pos (marker-position marker))
4954 (hdmarker (get-text-property (point) 'org-hd-marker))
4955 (buffer-read-only nil)
4956 newhead)
4957 (with-current-buffer buffer
4958 (widen)
4959 (goto-char pos)
4960 (org-show-hidden-entry)
4961 (save-excursion
4962 (and (outline-next-heading)
4963 (org-flag-heading nil))) ; show the next heading
4964 (funcall 'org-priority force-direction)
4965 (end-of-line 1)
4966 (setq newhead (org-get-heading)))
4967 (org-agenda-change-all-lines newhead hdmarker)
4968 (beginning-of-line 1)))
4969
4970 (defun org-agenda-date-later (arg &optional what)
4971 "Change the date of this item to one day later."
4972 (interactive "p")
4973 (org-agenda-check-no-diary)
4974 (let* ((marker (or (get-text-property (point) 'org-marker)
4975 (org-agenda-error)))
4976 (buffer (marker-buffer marker))
4977 (pos (marker-position marker)))
4978 (with-current-buffer buffer
4979 (widen)
4980 (goto-char pos)
4981 (if (not (org-at-timestamp-p))
4982 (error "Cannot find time stamp"))
4983 (org-timestamp-change arg (or what 'day))
4984 (message "Time stamp changed to %s" org-last-changed-timestamp))))
4985
4986 (defun org-agenda-date-earlier (arg &optional what)
4987 "Change the date of this item to one day earlier."
4988 (interactive "p")
4989 (org-agenda-date-later (- arg) what))
4990
4991 (defun org-agenda-date-prompt (arg)
4992 "Change the date of this item. Date is prompted for, with default today.
4993 The prefix ARG is passed to the `org-time-stamp' command and can therefore
4994 be used to request time specification in the time stamp."
4995 (interactive "P")
4996 (org-agenda-check-no-diary)
4997 (let* ((marker (or (get-text-property (point) 'org-marker)
4998 (org-agenda-error)))
4999 (buffer (marker-buffer marker))
5000 (pos (marker-position marker)))
5001 (with-current-buffer buffer
5002 (widen)
5003 (goto-char pos)
5004 (if (not (org-at-timestamp-p))
5005 (error "Cannot find time stamp"))
5006 (org-time-stamp arg)
5007 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5008
5009 (defun org-get-heading ()
5010 "Return the heading of the current entry, without the stars."
5011 (save-excursion
5012 (if (and (re-search-backward "[\r\n]\\*" nil t)
5013 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5014 (match-string 1)
5015 "")))
5016
5017 (defun org-agenda-diary-entry ()
5018 "Make a diary entry, like the `i' command from the calendar.
5019 All the standard commands work: block, weekly etc."
5020 (interactive)
5021 (require 'diary-lib)
5022 (let* ((char (progn
5023 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5024 (read-char-exclusive)))
5025 (cmd (cdr (assoc char
5026 '((?d . insert-diary-entry)
5027 (?w . insert-weekly-diary-entry)
5028 (?m . insert-monthly-diary-entry)
5029 (?y . insert-yearly-diary-entry)
5030 (?a . insert-anniversary-diary-entry)
5031 (?b . insert-block-diary-entry)
5032 (?c . insert-cyclic-diary-entry)))))
5033 (oldf (symbol-function 'calendar-cursor-to-date))
5034 (point (point))
5035 (mark (or (mark t) (point))))
5036 (unless cmd
5037 (error "No command associated with <%c>" char))
5038 (unless (and (get-text-property point 'day)
5039 (or (not (equal ?b char))
5040 (get-text-property mark 'day)))
5041 (error "Don't know which date to use for diary entry"))
5042 ;; We implement this by hacking the `calendar-cursor-to-date' function
5043 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5044 (let ((calendar-mark-ring
5045 (list (calendar-gregorian-from-absolute
5046 (or (get-text-property mark 'day)
5047 (get-text-property point 'day))))))
5048 (unwind-protect
5049 (progn
5050 (fset 'calendar-cursor-to-date
5051 (lambda (&optional error)
5052 (calendar-gregorian-from-absolute
5053 (get-text-property point 'day))))
5054 (call-interactively cmd))
5055 (fset 'calendar-cursor-to-date oldf)))))
5056
5057
5058 (defun org-agenda-execute-calendar-command (cmd)
5059 "Execute a calendar command from the agenda, with the date associated to
5060 the cursor position."
5061 (require 'diary-lib)
5062 (unless (get-text-property (point) 'day)
5063 (error "Don't know which date to use for calendar command"))
5064 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5065 (point (point))
5066 (date (calendar-gregorian-from-absolute
5067 (get-text-property point 'day)))
5068 (displayed-day (extract-calendar-day date))
5069 (displayed-month (extract-calendar-month date))
5070 (displayed-year (extract-calendar-year date)))
5071 (unwind-protect
5072 (progn
5073 (fset 'calendar-cursor-to-date
5074 (lambda (&optional error)
5075 (calendar-gregorian-from-absolute
5076 (get-text-property point 'day))))
5077 (call-interactively cmd))
5078 (fset 'calendar-cursor-to-date oldf))))
5079
5080 (defun org-agenda-phases-of-moon ()
5081 "Display the phases of the moon for the 3 months around the cursor date."
5082 (interactive)
5083 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5084
5085 (defun org-agenda-holidays ()
5086 "Display the holidays for the 3 months around the cursor date."
5087 (interactive)
5088 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5089
5090 (defun org-agenda-sunrise-sunset (arg)
5091 "Display sunrise and sunset for the cursor date.
5092 Latitude and longitude can be specified with the variables
5093 `calendar-latitude' and `calendar-longitude'. When called with prefix
5094 argument, latitude and longitude will be prompted for."
5095 (interactive "P")
5096 (let ((calendar-longitude (if arg nil calendar-longitude))
5097 (calendar-latitude (if arg nil calendar-latitude))
5098 (calendar-location-name
5099 (if arg "the given coordinates" calendar-location-name)))
5100 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5101
5102 (defun org-agenda-goto-calendar ()
5103 "Open the Emacs calendar with the date at the cursor."
5104 (interactive)
5105 (let* ((day (or (get-text-property (point) 'day)
5106 (error "Don't know which date to open in calendar")))
5107 (date (calendar-gregorian-from-absolute day)))
5108 (calendar)
5109 (calendar-goto-date date)))
5110
5111 (defun org-calendar-goto-agenda ()
5112 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5113 This is a command that has to be installed in `calendar-mode-map'."
5114 (interactive)
5115 (org-agenda nil (calendar-absolute-from-gregorian
5116 (calendar-cursor-to-date))))
5117
5118 (defun org-agenda-convert-date ()
5119 (interactive)
5120 (let ((day (get-text-property (point) 'day))
5121 date s)
5122 (unless day
5123 (error "Don't know which date to convert"))
5124 (setq date (calendar-gregorian-from-absolute day))
5125 (setq s (concat
5126 "Gregorian: " (calendar-date-string date) "\n"
5127 "ISO: " (calendar-iso-date-string date) "\n"
5128 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5129 "Julian: " (calendar-julian-date-string date) "\n"
5130 "Astron. JD: " (calendar-astro-date-string date)
5131 " (Julian date number at noon UTC)\n"
5132 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5133 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5134 "French: " (calendar-french-date-string date) "\n"
5135 "Mayan: " (calendar-mayan-date-string date) "\n"
5136 "Coptic: " (calendar-coptic-date-string date) "\n"
5137 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5138 "Persian: " (calendar-persian-date-string date) "\n"
5139 "Chinese: " (calendar-chinese-date-string date) "\n"))
5140 (with-output-to-temp-buffer "*Dates*"
5141 (princ s))
5142 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5143
5144 ;;; Link Stuff
5145
5146 (defun org-find-file-at-mouse (ev)
5147 "Open file link or URL at mouse."
5148 (interactive "e")
5149 (mouse-set-point ev)
5150 (org-open-at-point 'in-emacs))
5151
5152 (defun org-open-at-mouse (ev)
5153 "Open file link or URL at mouse."
5154 (interactive "e")
5155 (mouse-set-point ev)
5156 (org-open-at-point))
5157
5158 (defun org-open-at-point (&optional in-emacs)
5159 "Open link at or after point.
5160 If there is no link at point, this function will search forward up to
5161 the end of the current subtree.
5162 Normally, files will be opened by an appropriate application. If the
5163 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5164 (interactive "P")
5165 (if (org-at-timestamp-p)
5166 (org-agenda nil (time-to-days (org-time-string-to-time
5167 (substring (match-string 1) 0 10)))
5168 1)
5169 (let (type path line (pos (point)))
5170 (save-excursion
5171 (skip-chars-backward
5172 (concat (if org-allow-space-in-links "^" "^ ")
5173 org-non-link-chars))
5174 (if (re-search-forward
5175 org-link-regexp
5176 (save-excursion
5177 (condition-case nil
5178 (progn (outline-end-of-subtree) (max pos (point)))
5179 (error (end-of-line 1) (point))))
5180 t)
5181 (setq type (match-string 1)
5182 path (match-string 2)))
5183 (unless path
5184 (error "No link found"))
5185 ;; Remove any trailing spaces in path
5186 (if (string-match " +\\'" path)
5187 (setq path (replace-match "" t t path)))
5188
5189 (cond
5190
5191 ((string= type "file")
5192 (if (string-match ":\\([0-9]+\\)\\'" path)
5193 (setq line (string-to-number (match-string 1 path))
5194 path (substring path 0 (match-beginning 0))))
5195 (org-open-file path in-emacs line))
5196
5197 ((string= type "news")
5198 (org-follow-gnus-link path))
5199
5200 ((string= type "bbdb")
5201 (org-follow-bbdb-link path))
5202
5203 ((string= type "gnus")
5204 (let (group article)
5205 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5206 (error "Error in Gnus link"))
5207 (setq group (match-string 1 path)
5208 article (match-string 3 path))
5209 (org-follow-gnus-link group article)))
5210
5211 ((string= type "vm")
5212 (let (folder article)
5213 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5214 (error "Error in VM link"))
5215 (setq folder (match-string 1 path)
5216 article (match-string 3 path))
5217 ;; in-emacs is the prefix arg, will be interpreted as read-only
5218 (org-follow-vm-link folder article in-emacs)))
5219
5220 ((string= type "wl")
5221 (let (folder article)
5222 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5223 (error "Error in Wanderlust link"))
5224 (setq folder (match-string 1 path)
5225 article (match-string 3 path))
5226 (org-follow-wl-link folder article)))
5227
5228 ((string= type "rmail")
5229 (let (folder article)
5230 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5231 (error "Error in RMAIL link"))
5232 (setq folder (match-string 1 path)
5233 article (match-string 3 path))
5234 (org-follow-rmail-link folder article)))
5235
5236 ((string= type "shell")
5237 (let ((cmd path))
5238 (while (string-match "@{" cmd)
5239 (setq cmd (replace-match "<" t t cmd)))
5240 (while (string-match "@}" cmd)
5241 (setq cmd (replace-match ">" t t cmd)))
5242 (if (or (not org-confirm-shell-links)
5243 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5244 (shell-command cmd)
5245 (error "Abort"))))
5246
5247 (t
5248 (browse-url-at-point)))))))
5249
5250 (defun org-follow-bbdb-link (name)
5251 "Follow a BBDB link to NAME."
5252 (require 'bbdb)
5253 (let ((inhibit-redisplay t))
5254 (catch 'exit
5255 ;; Exact match on name
5256 (bbdb-name (concat "\\`" name "\\'") nil)
5257 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5258 ;; Exact match on name
5259 (bbdb-company (concat "\\`" name "\\'") nil)
5260 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5261 ;; Partial match on name
5262 (bbdb-name name nil)
5263 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5264 ;; Partial match on company
5265 (bbdb-company name nil)
5266 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5267 ;; General match including network address and notes
5268 (bbdb name nil)
5269 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5270 (delete-window (get-buffer-window "*BBDB*"))
5271 (error "No matching BBDB record")))))
5272
5273 (defun org-follow-gnus-link (&optional group article)
5274 "Follow a Gnus link to GROUP and ARTICLE."
5275 (require 'gnus)
5276 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5277 (if group (gnus-fetch-group group))
5278 (if article
5279 (or (gnus-summary-goto-article article nil 'force)
5280 (if (fboundp 'gnus-summary-insert-cached-articles)
5281 (progn
5282 (gnus-summary-insert-cached-articles)
5283 (gnus-summary-goto-article article nil 'force))
5284 (message "Message could not be found.")))))
5285
5286 (defun org-follow-vm-link (&optional folder article readonly)
5287 "Follow a VM link to FOLDER and ARTICLE."
5288 (require 'vm)
5289 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5290 ;; ange-ftp or efs or tramp access
5291 (let ((user (or (match-string 1 folder) (user-login-name)))
5292 (host (match-string 2 folder))
5293 (file (match-string 3 folder)))
5294 (cond
5295 ((featurep 'tramp)
5296 ;; use tramp to access the file
5297 (if org-xemacs-p
5298 (setq folder (format "[%s@%s]%s" user host file))
5299 (setq folder (format "/%s@%s:%s" user host file))))
5300 (t
5301 ;; use ange-ftp or efs
5302 (require (if org-xemacs-p 'efs 'ange-ftp))
5303 (setq folder (format "/%s@%s:%s" user host file))))))
5304 (when folder
5305 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5306 (sit-for 0.1)
5307 (when article
5308 (vm-select-folder-buffer)
5309 (widen)
5310 (let ((case-fold-search t))
5311 (goto-char (point-min))
5312 (if (not (re-search-forward
5313 (concat "^" "message-id: *" (regexp-quote article))))
5314 (error "Could not find the specified message in this folder"))
5315 (vm-isearch-update)
5316 (vm-isearch-narrow)
5317 (vm-beginning-of-message)
5318 (vm-summarize)))))
5319
5320 (defun org-follow-wl-link (folder article)
5321 "Follow a Wanderlust link to FOLDER and ARTICLE."
5322 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5323 (if article (wl-summary-jump-to-msg-by-message-id article))
5324 (wl-summary-redisplay))
5325
5326 (defun org-follow-rmail-link (folder article)
5327 "Follow an RMAIL link to FOLDER and ARTICLE."
5328 (let (message-number)
5329 (save-excursion
5330 (save-window-excursion
5331 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5332 (setq message-number
5333 (save-restriction
5334 (widen)
5335 (goto-char (point-max))
5336 (if (re-search-backward
5337 (concat "^Message-ID:\\s-+" (regexp-quote
5338 (or article "")))
5339 nil t)
5340 (rmail-what-message))))))
5341 (if message-number
5342 (progn
5343 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5344 (rmail-show-message message-number)
5345 message-number)
5346 (error "Message not found"))))
5347
5348 (defun org-open-file (path &optional in-emacs line)
5349 "Open the file at PATH.
5350 First, this expands any special file name abbreviations. Then the
5351 configuration variable `org-file-apps' is checked if it contains an
5352 entry for this file type, and if yes, the corresponding command is launched.
5353 If no application is found, Emacs simply visits the file.
5354 With optional argument IN-EMACS, Emacs will visit the file.
5355 If the file does not exist, an error is thrown."
5356 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5357 (dfile (downcase file))
5358 ext cmd apps)
5359 (if (and (not (file-exists-p file))
5360 (not org-open-non-existing-files))
5361 (error "No such file: %s" file))
5362 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5363 (setq ext (match-string 1 dfile))
5364 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5365 (setq ext (match-string 1 dfile))))
5366 (setq apps (append org-file-apps (org-default-apps)))
5367 (if in-emacs
5368 (setq cmd 'emacs)
5369 (setq cmd (or (cdr (assoc ext apps))
5370 (cdr (assoc t apps)))))
5371 (cond
5372 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5373 (setq cmd (format cmd (concat "\"" file "\"")))
5374 (save-window-excursion
5375 (shell-command (concat cmd " & &"))))
5376 ((or (stringp cmd)
5377 (eq cmd 'emacs))
5378 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5379 (if line (goto-line line)))
5380 ((consp cmd)
5381 (eval cmd))
5382 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5383
5384 (defun org-default-apps ()
5385 "Return the default applications for this operating system."
5386 (cond
5387 ((eq system-type 'darwin)
5388 org-file-apps-defaults-macosx)
5389 ((eq system-type 'windows-nt)
5390 org-file-apps-defaults-windowsnt)
5391 ((eq system-type 'linux)
5392 org-file-apps-defaults-linux)
5393 (t org-file-apps-defaults-linux)))
5394
5395 (defun org-expand-file-name (path)
5396 "Replace special path abbreviations and expand the file name."
5397 (expand-file-name path))
5398
5399
5400 (defvar org-insert-link-history nil
5401 "Minibuffer history for links inserted with `org-insert-link'.")
5402
5403 (defvar org-stored-links nil
5404 "Contains the links stored with `org-store-link'.")
5405
5406 ;;;###autoload
5407 (defun org-store-link (arg)
5408 "\\<org-mode-map>Store an org-link to the current location.
5409 This link can later be inserted into an org-buffer with
5410 \\[org-insert-link].
5411 For some link types, a prefix arg is interpreted:
5412 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5413 For file links, arg negates `org-line-numbers-in-file-links'."
5414 (interactive "P")
5415 (let (link cpltxt)
5416 (cond
5417
5418 ((eq major-mode 'bbdb-mode)
5419 (setq cpltxt (concat
5420 "bbdb:"
5421 (or (bbdb-record-name (bbdb-current-record))
5422 (bbdb-record-company (bbdb-current-record))))
5423 link (org-make-link cpltxt)))
5424
5425 ((eq major-mode 'calendar-mode)
5426 (let ((cd (calendar-cursor-to-date)))
5427 (setq link
5428 (format-time-string
5429 (car org-time-stamp-formats)
5430 (apply 'encode-time
5431 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5432 nil nil nil))))))
5433
5434 ((or (eq major-mode 'vm-summary-mode)
5435 (eq major-mode 'vm-presentation-mode))
5436 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5437 (vm-follow-summary-cursor)
5438 (save-excursion
5439 (vm-select-folder-buffer)
5440 (let* ((message (car vm-message-pointer))
5441 (folder (buffer-file-name))
5442 (subject (vm-su-subject message))
5443 (author (vm-su-full-name message))
5444 (message-id (vm-su-message-id message)))
5445 (setq folder (abbreviate-file-name folder))
5446 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5447 folder)
5448 (setq folder (replace-match "" t t folder)))
5449 (setq cpltxt (concat author " on: " subject))
5450 (setq link (concat cpltxt "\n "
5451 (org-make-link
5452 "vm:" folder "#" message-id))))))
5453
5454 ((eq major-mode 'wl-summary-mode)
5455 (let* ((msgnum (wl-summary-message-number))
5456 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5457 msgnum 'message-id))
5458 (wl-message-entity (elmo-msgdb-overview-get-entity
5459 msgnum (wl-summary-buffer-msgdb)))
5460 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5461 (subject "???")) ; FIXME: How to get subject of email?
5462 (setq cpltxt (concat author " on: " subject))
5463 (setq link (concat cpltxt "\n "
5464 (org-make-link
5465 "wl:" wl-summary-buffer-folder-name
5466 "#" message-id)))))
5467
5468 ((eq major-mode 'rmail-mode)
5469 (save-excursion
5470 (save-restriction
5471 (rmail-narrow-to-non-pruned-header)
5472 (let ((folder (buffer-file-name))
5473 (message-id (mail-fetch-field "message-id"))
5474 (author (mail-fetch-field "from"))
5475 (subject (mail-fetch-field "subject")))
5476 (setq cpltxt (concat author " on: " subject))
5477 (setq link (concat cpltxt "\n "
5478 (org-make-link
5479 "rmail:" folder "#" message-id)))))))
5480
5481 ((eq major-mode 'gnus-group-mode)
5482 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5483 (gnus-group-group-name)) ; version
5484 ((fboundp 'gnus-group-name)
5485 (gnus-group-name))
5486 (t "???"))))
5487 (setq cpltxt (concat
5488 (if (org-xor arg org-usenet-links-prefer-google)
5489 "http://groups.google.com/groups?group="
5490 "gnus:")
5491 group)
5492 link (org-make-link cpltxt))))
5493
5494 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5495 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5496 (gnus-summary-beginning-of-article)
5497 (let* ((group (car gnus-article-current))
5498 (article (cdr gnus-article-current))
5499 (header (gnus-summary-article-header article))
5500 (author (mail-header-from header))
5501 (message-id (mail-header-id header))
5502 (date (mail-header-date header))
5503 (subject (gnus-summary-subject-string)))
5504 (setq cpltxt (concat author " on: " subject))
5505 (if (org-xor arg org-usenet-links-prefer-google)
5506 (setq link
5507 (concat
5508 cpltxt "\n "
5509 (format "http://groups.google.com/groups?as_umsgid=%s"
5510 (org-fixup-message-id-for-http message-id))))
5511 (setq link (concat cpltxt "\n"
5512 (org-make-link
5513 "gnus:" group
5514 "#" (number-to-string article)))))))
5515
5516 ((eq major-mode 'w3-mode)
5517 (setq cpltxt (url-view-url t)
5518 link (org-make-link cpltxt)))
5519 ((eq major-mode 'w3m-mode)
5520 (setq cpltxt w3m-current-url
5521 link (org-make-link cpltxt)))
5522
5523 ((buffer-file-name)
5524 ;; Just link to this file here.
5525 (setq cpltxt (concat "file:"
5526 (abbreviate-file-name (buffer-file-name))))
5527 ;; Add the line number?
5528 (if (org-xor org-line-numbers-in-file-links arg)
5529 (setq cpltxt
5530 (concat cpltxt
5531 ":" (int-to-string
5532 (+ (if (bolp) 1 0) (count-lines
5533 (point-min) (point)))))))
5534 (setq link (org-make-link cpltxt)))
5535
5536 ((interactive-p)
5537 (error "Cannot link to a buffer which is not visiting a file"))
5538
5539 (t (setq link nil)))
5540
5541 (if (and (interactive-p) link)
5542 (progn
5543 (setq org-stored-links
5544 (cons (cons (or cpltxt link) link) org-stored-links))
5545 (message "Stored: %s" (or cpltxt link)))
5546 link)))
5547
5548 (defun org-make-link (&rest strings)
5549 "Concatenate STRINGS, format resulting string with `org-link-format'."
5550 (format org-link-format (apply 'concat strings)))
5551
5552 (defun org-xor (a b)
5553 "Exclusive or."
5554 (if a (not b) b))
5555
5556 (defun org-get-header (header)
5557 "Find a HEADER field in the current buffer."
5558 (save-excursion
5559 (goto-char (point-min))
5560 (let ((case-fold-search t) s)
5561 (cond
5562 ((eq header 'from)
5563 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5564 (setq s (match-string 1)))
5565 (while (string-match "\"" s)
5566 (setq s (replace-match "" t t s)))
5567 (if (string-match "[<(].*" s)
5568 (setq s (replace-match "" t t s))))
5569 ((eq header 'message-id)
5570 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5571 (setq s (match-string 1))))
5572 ((eq header 'subject)
5573 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5574 (setq s (match-string 1)))))
5575 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5576 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5577 s)))
5578
5579
5580 (defun org-fixup-message-id-for-http (s)
5581 "Replace special characters in a message id, so it can be used in an http query."
5582 (while (string-match "<" s)
5583 (setq s (replace-match "%3C" t t s)))
5584 (while (string-match ">" s)
5585 (setq s (replace-match "%3E" t t s)))
5586 (while (string-match "@" s)
5587 (setq s (replace-match "%40" t t s)))
5588 s)
5589
5590 (defun org-insert-link (&optional complete-file)
5591 "Insert a link. At the prompt, enter the link.
5592
5593 Completion can be used to select a link previously stored with
5594 `org-store-link'. When the empty string is entered (i.e. if you just
5595 press RET at the prompt), the link defaults to the most recently
5596 stored link. As SPC triggers completion in the minibuffer, you need to
5597 use M-SPC or C-q SPC to force the insertion of a space character.
5598
5599 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5600 selected using completion. The path to the file will be relative to
5601 the current directory if the file is in the current directory or a
5602 subdirectory. Otherwise, the link will be the absolute path as
5603 completed in the minibuffer (i.e. normally ~/path/to/file).
5604
5605 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5606 is in the current directory or below."
5607 (interactive "P")
5608 (let ((link (if complete-file
5609 (read-file-name "File: ")
5610 (completing-read
5611 "Link: " org-stored-links nil nil nil
5612 org-insert-link-history
5613 (or (car (car org-stored-links))))))
5614 linktxt matched)
5615 (if (or (not link) (equal link ""))
5616 (error "No links available"))
5617 (if complete-file
5618 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5619 (cond
5620 ((equal complete-file '(16))
5621 (insert
5622 (org-make-link
5623 "file:" (abbreviate-file-name (expand-file-name link)))))
5624 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5625 (expand-file-name link))
5626 (insert
5627 (org-make-link
5628 "file:" (match-string 1 (expand-file-name link)))))
5629 (t (insert (org-make-link "file:" link)))))
5630 (setq linktxt (cdr (assoc link org-stored-links)))
5631 (if (not org-keep-stored-link-after-insertion)
5632 (setq org-stored-links (delq (assoc link org-stored-links)
5633 org-stored-links)))
5634 (if (not linktxt) (setq link (org-make-link link)))
5635 (let ((lines (org-split-string (or linktxt link) "\n")))
5636 (insert (car lines))
5637 (setq matched (string-match org-link-regexp (car lines)))
5638 (setq lines (cdr lines))
5639 (while lines
5640 (insert "\n")
5641 (if (save-excursion
5642 (beginning-of-line 0)
5643 (looking-at "[ \t]+\\S-"))
5644 (indent-relative))
5645 (setq matched (or matched
5646 (string-match org-link-regexp (car lines))))
5647 (insert (car lines))
5648 (setq lines (cdr lines))))
5649 (unless matched
5650 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5651
5652 ;;; Hooks for remember.el
5653 ;;;###autoload
5654 (defun org-remember-annotation ()
5655 "Return a link to the current location as an annotation for remember.el.
5656 If you are using Org-mode files as target for data storage with
5657 remember.el, then the annotations should include a link compatible with the
5658 conventions in Org-mode. This function returns such a link."
5659 (org-store-link nil))
5660
5661 (defconst org-remember-help
5662 "Select a destination location for the note.
5663 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5664 RET at beg-of-buf -> Append to file as level 2 headline
5665 RET on headline -> Store as sublevel entry to current headline
5666 <left>/<right> -> Before/after current headline, same headings level")
5667
5668 ;;;###autoload
5669 (defun org-remember-handler ()
5670 "Store stuff from remember.el into an org file.
5671 First prompts for an org file. If the user just presses return, the value
5672 of `org-default-notes-file' is used.
5673 Then the command offers the headings tree of the selected file in order to
5674 file the text at a specific location.
5675 You can either immediately press RET to get the note appended to the
5676 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5677 find a better place. Then press RET or <left> or <right> in insert the note.
5678
5679 Key Cursor position Note gets inserted
5680 -----------------------------------------------------------------------------
5681 RET buffer-start as level 2 heading at end of file
5682 RET on headline as sublevel of the heading at cursor
5683 RET no heading at cursor position, level taken from context.
5684 Or use prefix arg to specify level manually.
5685 <left> on headline as same level, before current heading
5686 <right> on headline as same level, after current heading
5687
5688 So the fastest way to store the note is to press RET RET to append it to
5689 the default file. This way your current train of thought is not
5690 interrupted, in accordance with the principles of remember.el. But with
5691 little extra effort, you can push it directly to the correct location.
5692
5693 Before being stored away, the function ensures that the text has a
5694 headline, i.e. a first line that starts with a \"*\". If not, a headline
5695 is constructed from the current date and some additional data.
5696
5697 If the variable `org-adapt-indentation' is non-nil, the entire text is
5698 also indented so that it starts in the same column as the headline
5699 \(i.e. after the stars).
5700
5701 See also the variable `org-reverse-note-order'."
5702 (catch 'quit
5703 (let* ((txt (buffer-substring (point-min) (point-max)))
5704 (fastp current-prefix-arg)
5705 (file (if fastp org-default-notes-file (org-get-org-file)))
5706 (visiting (find-buffer-visiting file))
5707 (org-startup-with-deadline-check nil)
5708 (org-startup-folded nil)
5709 spos level indent reversed)
5710 ;; Modify text so that it becomes a nice subtree which can be inserted
5711 ;; into an org tree.
5712 (let* ((lines (split-string txt "\n"))
5713 (first (car lines))
5714 (lines (cdr lines)))
5715 (if (string-match "^\\*+" first)
5716 ;; Is already a headline
5717 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5718 -1) ?\ ))
5719 ;; We need to add a headline: Use time and first buffer line
5720 (setq lines (cons first lines)
5721 first (concat "* " (current-time-string)
5722 " (" (remember-buffer-desc) ")")
5723 indent " "))
5724 (if org-adapt-indentation
5725 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5726 (setq txt (concat first "\n"
5727 (mapconcat 'identity lines "\n"))))
5728 ;; Find the file
5729 (if (not visiting)
5730 (find-file-noselect file))
5731 (with-current-buffer (get-file-buffer file)
5732 (setq reversed (org-notes-order-reversed-p))
5733 (save-excursion
5734 (save-restriction
5735 (widen)
5736 ;; Ask the User for a location
5737 (setq spos (if fastp 1 (org-get-location
5738 (current-buffer)
5739 org-remember-help)))
5740 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5741 ; not handle this note
5742 (goto-char spos)
5743 (cond ((bobp)
5744 ;; Put it at the start or end, as level 2
5745 (save-restriction
5746 (widen)
5747 (goto-char (if reversed (point-min) (point-max)))
5748 (if (not (bolp)) (newline))
5749 (org-paste-subtree (or current-prefix-arg 2) txt)))
5750 ((and (org-on-heading-p nil) (not current-prefix-arg))
5751 ;; Put it below this entry, at the beg/end of the subtree
5752 (org-back-to-heading)
5753 (setq level (outline-level))
5754 (if reversed
5755 (outline-end-of-heading)
5756 (outline-end-of-subtree))
5757 (if (not (bolp)) (newline))
5758 (beginning-of-line 1)
5759 (org-paste-subtree (1+ level) txt))
5760 (t
5761 ;; Put it right there, with automatic level determined by
5762 ;; org-paste-subtree or from prefix arg
5763 (org-paste-subtree current-prefix-arg txt)))
5764 (when remember-save-after-remembering
5765 (save-buffer)
5766 (if (not visiting) (kill-buffer (current-buffer)))))))))
5767 t) ;; return t to indicate that we took care of this note.
5768
5769 (defun org-get-org-file ()
5770 "Read a filename, with default directory `org-directory'."
5771 (let ((default (or org-default-notes-file remember-data-file)))
5772 (read-file-name (format "File name [%s]: " default)
5773 (file-name-as-directory org-directory)
5774 default)))
5775
5776 (defun org-notes-order-reversed-p ()
5777 "Check if the current file should receive notes in reversed order."
5778 (cond
5779 ((not org-reverse-note-order) nil)
5780 ((eq t org-reverse-note-order) t)
5781 ((not (listp org-reverse-note-order)) nil)
5782 (t (catch 'exit
5783 (let ((all org-reverse-note-order)
5784 entry)
5785 (while (setq entry (pop all))
5786 (if (string-match (car entry) (buffer-file-name))
5787 (throw 'exit (cdr entry))))
5788 nil)))))
5789
5790 ;;; Tables
5791
5792 ;; Watch out: Here we are talking about two different kind of tables.
5793 ;; Most of the code is for the tables created with the Org-mode table editor.
5794 ;; Sometimes, we talk about tables created and edited with the table.el
5795 ;; Emacs package. We call the former org-type tables, and the latter
5796 ;; table.el-type tables.
5797
5798
5799 (defun org-before-change-function (beg end)
5800 "Every change indicates that a table might need an update."
5801 (setq org-table-may-need-update t))
5802
5803 (defconst org-table-line-regexp "^[ \t]*|"
5804 "Detects an org-type table line.")
5805 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5806 "Detects an org-type table line.")
5807 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5808 "Detects a table line marked for automatic recalculation.")
5809 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5810 "Detects a table line marked for automatic recalculation.")
5811 (defconst org-table-hline-regexp "^[ \t]*|-"
5812 "Detects an org-type table hline.")
5813 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5814 "Detects a table-type table hline.")
5815 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5816 "Detects an org-type or table-type table.")
5817 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5818 "Searching from within a table (any type) this finds the first line
5819 outside the table.")
5820 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5821 "Searching from within a table (any type) this finds the first line
5822 outside the table.")
5823
5824 (defun org-table-create-with-table.el ()
5825 "Use the table.el package to insert a new table.
5826 If there is already a table at point, convert between Org-mode tables
5827 and table.el tables."
5828 (interactive)
5829 (require 'table)
5830 (cond
5831 ((org-at-table.el-p)
5832 (if (y-or-n-p "Convert table to Org-mode table? ")
5833 (org-table-convert)))
5834 ((org-at-table-p)
5835 (if (y-or-n-p "Convert table to table.el table? ")
5836 (org-table-convert)))
5837 (t (call-interactively 'table-insert))))
5838
5839 (defun org-table-create (&optional size)
5840 "Query for a size and insert a table skeleton.
5841 SIZE is a string Columns x Rows like for example \"3x2\"."
5842 (interactive "P")
5843 (unless size
5844 (setq size (read-string
5845 (concat "Table size Columns x Rows [e.g. "
5846 org-table-default-size "]: ")
5847 "" nil org-table-default-size)))
5848
5849 (let* ((pos (point))
5850 (indent (make-string (current-column) ?\ ))
5851 (split (org-split-string size " *x *"))
5852 (rows (string-to-number (nth 1 split)))
5853 (columns (string-to-number (car split)))
5854 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5855 "\n")))
5856 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5857 (point-at-bol) (point)))
5858 (beginning-of-line 1)
5859 (newline))
5860 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5861 (dotimes (i rows) (insert line))
5862 (goto-char pos)
5863 (if (> rows 1)
5864 ;; Insert a hline after the first row.
5865 (progn
5866 (end-of-line 1)
5867 (insert "\n|-")
5868 (goto-char pos)))
5869 (org-table-align)))
5870
5871 (defun org-table-convert-region (beg0 end0 nspace)
5872 "Convert region to a table.
5873 The region goes from BEG0 to END0, but these borders will be moved
5874 slightly, to make sure a beginning of line in the first line is included.
5875 When NSPACE is non-nil, it indicates the minimum number of spaces that
5876 separate columns (default: just one space)."
5877 (let* ((beg (min beg0 end0))
5878 (end (max beg0 end0))
5879 (tabsep t)
5880 re)
5881 (goto-char beg)
5882 (beginning-of-line 1)
5883 (setq beg (move-marker (make-marker) (point)))
5884 (goto-char end)
5885 (if (bolp) (backward-char 1) (end-of-line 1))
5886 (setq end (move-marker (make-marker) (point)))
5887 ;; Lets see if this is tab-separated material. If every nonempty line
5888 ;; contains a tab, we will assume that it is tab-separated material
5889 (if nspace
5890 (setq tabsep nil)
5891 (goto-char beg)
5892 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5893 (if nspace (setq tabsep nil))
5894 (if tabsep
5895 (setq re "^\\|\t")
5896 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5897 (max 1 (prefix-numeric-value nspace)))))
5898 (goto-char beg)
5899 (while (re-search-forward re end t)
5900 (replace-match "|" t t))
5901 (goto-char beg)
5902 (insert " ")
5903 (org-table-align)))
5904
5905 (defun org-table-import (file arg)
5906 "Import FILE as a table.
5907 The file is assumed to be tab-separated. Such files can be produced by most
5908 spreadsheet and database applications. If no tabs (at least one per line)
5909 are found, lines will be split on whitespace into fields."
5910 (interactive "f\nP")
5911 (or (bolp) (newline))
5912 (let ((beg (point))
5913 (pm (point-max)))
5914 (insert-file-contents file)
5915 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5916
5917 (defun org-table-export ()
5918 "Export table as a tab-separated file.
5919 Such a file can be imported into a spreadsheet program like Excel."
5920 (interactive)
5921 (let* ((beg (org-table-begin))
5922 (end (org-table-end))
5923 (table (buffer-substring beg end))
5924 (file (read-file-name "Export table to: "))
5925 buf)
5926 (unless (or (not (file-exists-p file))
5927 (y-or-n-p (format "Overwrite file %s? " file)))
5928 (error "Abort"))
5929 (with-current-buffer (find-file-noselect file)
5930 (setq buf (current-buffer))
5931 (erase-buffer)
5932 (fundamental-mode)
5933 (insert table)
5934 (goto-char (point-min))
5935 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5936 (replace-match "" t t)
5937 (end-of-line 1))
5938 (goto-char (point-min))
5939 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5940 (replace-match "" t t)
5941 (goto-char (min (1+ (point)) (point-max))))
5942 (goto-char (point-min))
5943 (while (re-search-forward "^-[-+]*$" nil t)
5944 (replace-match "")
5945 (if (looking-at "\n")
5946 (delete-char 1)))
5947 (goto-char (point-min))
5948 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5949 (replace-match "\t" t t))
5950 (save-buffer))
5951 (kill-buffer buf)))
5952
5953 (defvar org-table-aligned-begin-marker (make-marker)
5954 "Marker at the beginning of the table last aligned.
5955 Used to check if cursor still is in that table, to minimize realignment.")
5956 (defvar org-table-aligned-end-marker (make-marker)
5957 "Marker at the end of the table last aligned.
5958 Used to check if cursor still is in that table, to minimize realignment.")
5959 (defvar org-table-last-alignment nil
5960 "List of flags for flushright alignment, from the last re-alignment.
5961 This is being used to correctly align a single field after TAB or RET.")
5962 ;; FIXME: The following is currently not used.
5963 (defvar org-table-last-column-widths nil
5964 "List of max width of fields in each column.
5965 This is being used to correctly align a single field after TAB or RET.")
5966
5967 (defvar org-last-recalc-line nil)
5968
5969 (defun org-table-align ()
5970 "Align the table at point by aligning all vertical bars."
5971 (interactive)
5972 (let* (
5973 ;; Limits of table
5974 (beg (org-table-begin))
5975 (end (org-table-end))
5976 ;; Current cursor position
5977 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
5978 (colpos (org-table-current-column))
5979 (winstart (window-start))
5980 text lines (new "") lengths l typenums ty fields maxfields i
5981 column
5982 (indent "") cnt frac
5983 rfmt hfmt
5984 (spaces (if (org-in-invisibility-spec-p '(org-table))
5985 org-table-spaces-around-invisible-separators
5986 org-table-spaces-around-separators))
5987 (sp1 (car spaces))
5988 (sp2 (cdr spaces))
5989 (rfmt1 (concat
5990 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5991 (hfmt1 (concat
5992 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5993 emptystrings)
5994 (untabify beg end)
5995 ;; (message "Aligning table...")
5996 ;; Get the rows
5997 (setq lines (org-split-string
5998 (buffer-substring-no-properties beg end) "\n"))
5999 ;; Store the indentation of the first line
6000 (if (string-match "^ *" (car lines))
6001 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6002 ;; Mark the hlines
6003 (setq lines (mapcar (lambda (l)
6004 (if (string-match "^ *|-" l)
6005 nil
6006 (if (string-match "[ \t]+$" l)
6007 (substring l 0 (match-beginning 0))
6008 l)))
6009 lines))
6010 ;; Get the data fields
6011 (setq fields (mapcar
6012 (lambda (l)
6013 (org-split-string l " *| *"))
6014 (delq nil (copy-sequence lines))))
6015 ;; How many fields in the longest line?
6016 (condition-case nil
6017 (setq maxfields (apply 'max (mapcar 'length fields)))
6018 (error
6019 (kill-region beg end)
6020 (org-table-create org-table-default-size)
6021 (error "Empty table - created default table")))
6022 ;; A list of empty string to fill any short rows on output
6023 (setq emptystrings (make-list maxfields ""))
6024 ;; Get the maximum length of a field and the most common datatype
6025 ;; for each column
6026 (setq i -1)
6027 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6028 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6029 ;; maximum length
6030 (push (apply 'max 1 (mapcar 'length column)) lengths)
6031 ;; compute the fraction stepwise, ignoring empty fields
6032 (setq cnt 0 frac 0.0)
6033 (mapcar
6034 (lambda (x)
6035 (if (equal x "")
6036 nil
6037 (setq frac ( / (+ (* frac cnt)
6038 (if (string-match org-table-number-regexp x) 1 0))
6039 (setq cnt (1+ cnt))))))
6040 column)
6041 (push (>= frac org-table-number-fraction) typenums))
6042 (setq lengths (nreverse lengths)
6043 typenums (nreverse typenums))
6044 (setq org-table-last-alignment typenums
6045 org-table-last-column-widths lengths)
6046 ;; Compute the formats needed for output of the table
6047 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6048 (while (setq l (pop lengths))
6049 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6050 (setq rfmt (concat rfmt (format rfmt1 ty l))
6051 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6052 (setq rfmt (concat rfmt "\n")
6053 hfmt (concat (substring hfmt 0 -1) "|\n"))
6054 ;; Produce the new table
6055 ;;(while lines
6056 ;; (setq l (pop lines))
6057 ;; (if l
6058 ;; (setq new (concat new (apply 'format rfmt
6059 ;; (append (pop fields) emptystrings))))
6060 ;; (setq new (concat new hfmt))))
6061 (setq new (mapconcat
6062 (lambda (l)
6063 (if l (apply 'format rfmt
6064 (append (pop fields) emptystrings))
6065 hfmt))
6066 lines ""))
6067 ;; Replace the old one
6068 (delete-region beg end)
6069 (move-marker end nil)
6070 (move-marker org-table-aligned-begin-marker (point))
6071 (insert new)
6072 (move-marker org-table-aligned-end-marker (point))
6073 ;; Try to move to the old location (approximately)
6074 (goto-line linepos)
6075 (set-window-start (selected-window) winstart 'noforce)
6076 (org-table-goto-column colpos)
6077 (setq org-table-may-need-update nil)
6078 (if (org-in-invisibility-spec-p '(org-table))
6079 (org-table-add-invisible-to-vertical-lines))
6080 ))
6081
6082 (defun org-table-begin (&optional table-type)
6083 "Find the beginning of the table and return its position.
6084 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6085 (save-excursion
6086 (if (not (re-search-backward
6087 (if table-type org-table-any-border-regexp
6088 org-table-border-regexp)
6089 nil t))
6090 (error "Can't find beginning of table")
6091 (goto-char (match-beginning 0))
6092 (beginning-of-line 2)
6093 (point))))
6094
6095 (defun org-table-end (&optional table-type)
6096 "Find the end of the table and return its position.
6097 With argument TABLE-TYPE, go to the end of a table.el-type table."
6098 (save-excursion
6099 (if (not (re-search-forward
6100 (if table-type org-table-any-border-regexp
6101 org-table-border-regexp)
6102 nil t))
6103 (goto-char (point-max))
6104 (goto-char (match-beginning 0)))
6105 (point-marker)))
6106
6107 (defun org-table-justify-field-maybe ()
6108 "Justify the current field, text to left, number to right."
6109 (cond
6110 (org-table-may-need-update) ; Realignment will happen anyway, don't bother
6111 ((org-at-table-hline-p)
6112 ;; This is pretty stupid, but I don't know how to deal with hlines
6113 (setq org-table-may-need-update t))
6114 ((or (not (equal (marker-buffer org-table-aligned-begin-marker)
6115 (current-buffer)))
6116 (< (point) org-table-aligned-begin-marker)
6117 (>= (point) org-table-aligned-end-marker))
6118 ;; This is not the same table, force a full re-align
6119 (setq org-table-may-need-update t))
6120 (t ;; realign the current field, based on previous full realign
6121 (let* ((pos (point)) s org-table-may-need-update
6122 (col (org-table-current-column))
6123 (num (nth (1- col) org-table-last-alignment))
6124 l f n o)
6125 (when (> col 0)
6126 (skip-chars-backward "^|\n")
6127 (if (looking-at " *\\([^|\n]*?\\) *|")
6128 (progn
6129 (setq s (match-string 1)
6130 o (match-string 0)
6131 l (max 1 (- (match-end 0) (match-beginning 0) 3)))
6132 (setq f (format (if num " %%%ds |" " %%-%ds |") l)
6133 n (format f s t t))
6134 (or (equal n o) (replace-match n)))
6135 (setq org-table-may-need-update t))
6136 (goto-char pos))))))
6137
6138 (defun org-table-next-field ()
6139 "Go to the next field in the current table.
6140 Before doing so, re-align the table if necessary."
6141 (interactive)
6142 (org-table-maybe-eval-formula)
6143 (org-table-maybe-recalculate-line)
6144 (if (and org-table-automatic-realign
6145 org-table-may-need-update)
6146 (org-table-align))
6147 (if (org-at-table-hline-p)
6148 (end-of-line 1))
6149 (condition-case nil
6150 (progn
6151 (re-search-forward "|" (org-table-end))
6152 (if (looking-at "[ \t]*$")
6153 (re-search-forward "|" (org-table-end)))
6154 (if (looking-at "-")
6155 (progn
6156 (beginning-of-line 0)
6157 (org-table-insert-row 'below))
6158 (if (looking-at " ") (forward-char 1))))
6159 (error
6160 (org-table-insert-row 'below))))
6161
6162 (defun org-table-previous-field ()
6163 "Go to the previous field in the table.
6164 Before doing so, re-align the table if necessary."
6165 (interactive)
6166 (org-table-justify-field-maybe)
6167 (org-table-maybe-recalculate-line)
6168 (if (and org-table-automatic-realign
6169 org-table-may-need-update)
6170 (org-table-align))
6171 (if (org-at-table-hline-p)
6172 (end-of-line 1))
6173 (re-search-backward "|" (org-table-begin))
6174 (re-search-backward "|" (org-table-begin))
6175 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6176 (re-search-backward "|" (org-table-begin)))
6177 (if (looking-at "| ?")
6178 (goto-char (match-end 0))))
6179
6180 (defun org-table-next-row ()
6181 "Go to the next row (same column) in the current table.
6182 Before doing so, re-align the table if necessary."
6183 (interactive)
6184 (org-table-maybe-eval-formula)
6185 (org-table-maybe-recalculate-line)
6186 (if (or (looking-at "[ \t]*$")
6187 (save-excursion (skip-chars-backward " \t") (bolp)))
6188 (newline)
6189 (if (and org-table-automatic-realign
6190 org-table-may-need-update)
6191 (org-table-align))
6192 (let ((col (org-table-current-column)))
6193 (beginning-of-line 2)
6194 (if (or (not (org-at-table-p))
6195 (org-at-table-hline-p))
6196 (progn
6197 (beginning-of-line 0)
6198 (org-table-insert-row 'below)))
6199 (org-table-goto-column col)
6200 (skip-chars-backward "^|\n\r")
6201 (if (looking-at " ") (forward-char 1)))))
6202
6203 (defun org-table-copy-down (n)
6204 "Copy a field down in the current column.
6205 If the field at the cursor is empty, copy into it the content of the nearest
6206 non-empty field above. With argument N, use the Nth non-empty field.
6207 If the current field is not empty, it is copied down to the next row, and
6208 the cursor is moved with it. Therefore, repeating this command causes the
6209 column to be filled row-by-row.
6210 If the variable `org-table-copy-increment' is non-nil and the field is an
6211 integer, it will be incremented while copying."
6212 (interactive "p")
6213 (let* ((colpos (org-table-current-column))
6214 (field (org-table-get-field))
6215 (non-empty (string-match "[^ \t]" field))
6216 (beg (org-table-begin))
6217 txt)
6218 (org-table-check-inside-data-field)
6219 (if non-empty
6220 (progn
6221 (setq txt (org-trim field))
6222 (org-table-next-row)
6223 (org-table-blank-field))
6224 (save-excursion
6225 (setq txt
6226 (catch 'exit
6227 (while (progn (beginning-of-line 1)
6228 (re-search-backward org-table-dataline-regexp
6229 beg t))
6230 (org-table-goto-column colpos t)
6231 (if (and (looking-at
6232 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6233 (= (setq n (1- n)) 0))
6234 (throw 'exit (match-string 1))))))))
6235 (if txt
6236 (progn
6237 (if (and org-table-copy-increment
6238 (string-match "^[0-9]+$" txt))
6239 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6240 (insert txt)
6241 (org-table-maybe-recalculate-line)
6242 (org-table-align))
6243 (error "No non-empty field found"))))
6244
6245 (defun org-table-check-inside-data-field ()
6246 "Is point inside a table data field?
6247 I.e. not on a hline or before the first or after the last column?"
6248 (if (or (not (org-at-table-p))
6249 (= (org-table-current-column) 0)
6250 (org-at-table-hline-p)
6251 (looking-at "[ \t]*$"))
6252 (error "Not in table data field")))
6253
6254 (defvar org-table-clip nil
6255 "Clipboard for table regions.")
6256
6257 (defun org-table-blank-field ()
6258 "Blank the current table field or active region."
6259 (interactive)
6260 (org-table-check-inside-data-field)
6261 (if (and (interactive-p) (org-region-active-p))
6262 (let (org-table-clip)
6263 (org-table-cut-region (region-beginning) (region-end)))
6264 (skip-chars-backward "^|")
6265 (backward-char 1)
6266 (if (looking-at "|[^|\n]+")
6267 (let* ((pos (match-beginning 0))
6268 (match (match-string 0))
6269 (len (length match)))
6270 (replace-match (concat "|" (make-string (1- len) ?\ )))
6271 (goto-char (+ 2 pos))
6272 (substring match 1)))))
6273
6274 (defun org-table-get-field (&optional n replace)
6275 "Return the value of the field in column N of current row.
6276 N defaults to current field.
6277 If REPLACE is a string, replace field with this value. The return value
6278 is always the old value."
6279 (and n (org-table-goto-column n))
6280 (skip-chars-backward "^|\n")
6281 (backward-char 1)
6282 (if (looking-at "|[^|\r\n]*")
6283 (let* ((pos (match-beginning 0))
6284 (val (buffer-substring (1+ pos) (match-end 0))))
6285 (if replace
6286 (replace-match (concat "|" replace)))
6287 (goto-char (min (point-at-eol) (+ 2 pos)))
6288 val)
6289 (forward-char 1) ""))
6290
6291 (defun org-table-current-column ()
6292 "Find out which column we are in.
6293 When called interactively, column is also displayed in echo area."
6294 (interactive)
6295 (if (interactive-p) (org-table-check-inside-data-field))
6296 (save-excursion
6297 (let ((cnt 0) (pos (point)))
6298 (beginning-of-line 1)
6299 (while (search-forward "|" pos t)
6300 (setq cnt (1+ cnt)))
6301 (if (interactive-p) (message "This is table column %d" cnt))
6302 cnt)))
6303
6304 (defun org-table-goto-column (n &optional on-delim force)
6305 "Move the cursor to the Nth column in the current table line.
6306 With optional argument ON-DELIM, stop with point before the left delimiter
6307 of the field.
6308 If there are less than N fields, just go to after the last delimiter.
6309 However, when FORCE is non-nil, create new columns if necessary."
6310 (let ((pos (point-at-eol)))
6311 (beginning-of-line 1)
6312 (when (> n 0)
6313 (while (and (> (setq n (1- n)) -1)
6314 (or (search-forward "|" pos t)
6315 (and force
6316 (progn (end-of-line 1)
6317 (skip-chars-backward "^|")
6318 (insert " | "))))))
6319 ; (backward-char 2) t)))))
6320 (when (and force (not (looking-at ".*|")))
6321 (save-excursion (end-of-line 1) (insert " | ")))
6322 (if on-delim
6323 (backward-char 1)
6324 (if (looking-at " ") (forward-char 1))))))
6325
6326 (defun org-at-table-p (&optional table-type)
6327 "Return t if the cursor is inside an org-type table.
6328 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6329 (if org-enable-table-editor
6330 (save-excursion
6331 (beginning-of-line 1)
6332 (looking-at (if table-type org-table-any-line-regexp
6333 org-table-line-regexp)))
6334 nil))
6335
6336 (defun org-table-recognize-table.el ()
6337 "If there is a table.el table nearby, recognize it and move into it."
6338 (if org-table-tab-recognizes-table.el
6339 (if (org-at-table.el-p)
6340 (progn
6341 (beginning-of-line 1)
6342 (if (looking-at org-table-dataline-regexp)
6343 nil
6344 (if (looking-at org-table1-hline-regexp)
6345 (progn
6346 (beginning-of-line 2)
6347 (if (looking-at org-table-any-border-regexp)
6348 (beginning-of-line -1)))))
6349 (if (re-search-forward "|" (org-table-end t) t)
6350 (progn
6351 (require 'table)
6352 (if (table--at-cell-p (point))
6353 t
6354 (message "recognizing table.el table...")
6355 (table-recognize-table)
6356 (message "recognizing table.el table...done")))
6357 (error "This should not happen..."))
6358 t)
6359 nil)
6360 nil))
6361
6362 (defun org-at-table.el-p ()
6363 "Return t if the cursor is inside a table.el-type table."
6364 (save-excursion
6365 (if (org-at-table-p 'any)
6366 (progn
6367 (goto-char (org-table-begin 'any))
6368 (looking-at org-table1-hline-regexp))
6369 nil)))
6370
6371 (defun org-at-table-hline-p ()
6372 "Return t if the cursor is inside a hline in a table."
6373 (if org-enable-table-editor
6374 (save-excursion
6375 (beginning-of-line 1)
6376 (looking-at org-table-hline-regexp))
6377 nil))
6378
6379 (defun org-table-insert-column ()
6380 "Insert a new column into the table."
6381 (interactive)
6382 (if (not (org-at-table-p))
6383 (error "Not at a table"))
6384 (org-table-find-dataline)
6385 (let* ((col (max 1 (org-table-current-column)))
6386 (beg (org-table-begin))
6387 (end (org-table-end))
6388 ;; Current cursor position
6389 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6390 (colpos col))
6391 (goto-char beg)
6392 (while (< (point) end)
6393 (if (org-at-table-hline-p)
6394 nil
6395 (org-table-goto-column col t)
6396 (insert "| "))
6397 (beginning-of-line 2))
6398 (move-marker end nil)
6399 (goto-line linepos)
6400 (org-table-goto-column colpos)
6401 (org-table-align)
6402 (org-table-modify-formulas 'insert col)))
6403
6404 (defun org-table-find-dataline ()
6405 "Find a dataline in the current table, which is needed for column commands."
6406 (if (and (org-at-table-p)
6407 (not (org-at-table-hline-p)))
6408 t
6409 (let ((col (current-column))
6410 (end (org-table-end)))
6411 (move-to-column col)
6412 (while (and (< (point) end)
6413 (or (not (= (current-column) col))
6414 (org-at-table-hline-p)))
6415 (beginning-of-line 2)
6416 (move-to-column col))
6417 (if (and (org-at-table-p)
6418 (not (org-at-table-hline-p)))
6419 t
6420 (error
6421 "Please position cursor in a data line for column operations")))))
6422
6423 (defun org-table-delete-column ()
6424 "Delete a column into the table."
6425 (interactive)
6426 (if (not (org-at-table-p))
6427 (error "Not at a table"))
6428 (org-table-find-dataline)
6429 (org-table-check-inside-data-field)
6430 (let* ((col (org-table-current-column))
6431 (beg (org-table-begin))
6432 (end (org-table-end))
6433 ;; Current cursor position
6434 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6435 (colpos col))
6436 (goto-char beg)
6437 (while (< (point) end)
6438 (if (org-at-table-hline-p)
6439 nil
6440 (org-table-goto-column col t)
6441 (and (looking-at "|[^|\n]+|")
6442 (replace-match "|")))
6443 (beginning-of-line 2))
6444 (move-marker end nil)
6445 (goto-line linepos)
6446 (org-table-goto-column colpos)
6447 (org-table-align)
6448 (org-table-modify-formulas 'remove col)))
6449
6450 (defun org-table-move-column-right ()
6451 "Move column to the right."
6452 (interactive)
6453 (org-table-move-column nil))
6454 (defun org-table-move-column-left ()
6455 "Move column to the left."
6456 (interactive)
6457 (org-table-move-column 'left))
6458
6459 (defun org-table-move-column (&optional left)
6460 "Move the current column to the right. With arg LEFT, move to the left."
6461 (interactive "P")
6462 (if (not (org-at-table-p))
6463 (error "Not at a table"))
6464 (org-table-find-dataline)
6465 (org-table-check-inside-data-field)
6466 (let* ((col (org-table-current-column))
6467 (col1 (if left (1- col) col))
6468 (beg (org-table-begin))
6469 (end (org-table-end))
6470 ;; Current cursor position
6471 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6472 (colpos (if left (1- col) (1+ col))))
6473 (if (and left (= col 1))
6474 (error "Cannot move column further left"))
6475 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6476 (error "Cannot move column further right"))
6477 (goto-char beg)
6478 (while (< (point) end)
6479 (if (org-at-table-hline-p)
6480 nil
6481 (org-table-goto-column col1 t)
6482 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6483 (replace-match "|\\2|\\1|")))
6484 (beginning-of-line 2))
6485 (move-marker end nil)
6486 (goto-line linepos)
6487 (org-table-goto-column colpos)
6488 (org-table-align)
6489 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6490
6491 (defun org-table-move-row-down ()
6492 "Move table row down."
6493 (interactive)
6494 (org-table-move-row nil))
6495 (defun org-table-move-row-up ()
6496 "Move table row up."
6497 (interactive)
6498 (org-table-move-row 'up))
6499
6500 (defun org-table-move-row (&optional up)
6501 "Move the current table line down. With arg UP, move it up."
6502 (interactive "P")
6503 (let ((col (current-column))
6504 (pos (point))
6505 (tonew (if up 0 2))
6506 txt)
6507 (beginning-of-line tonew)
6508 (if (not (org-at-table-p))
6509 (progn
6510 (goto-char pos)
6511 (error "Cannot move row further")))
6512 (goto-char pos)
6513 (beginning-of-line 1)
6514 (setq pos (point))
6515 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6516 (delete-region (point) (1+ (point-at-eol)))
6517 (beginning-of-line tonew)
6518 (insert txt)
6519 (beginning-of-line 0)
6520 (move-to-column col)))
6521
6522 (defun org-table-insert-row (&optional arg)
6523 "Insert a new row above the current line into the table.
6524 With prefix ARG, insert below the current line."
6525 (interactive "P")
6526 (if (not (org-at-table-p))
6527 (error "Not at a table"))
6528 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6529 new)
6530 (if (string-match "^[ \t]*|-" line)
6531 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6532 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6533 ;; Fix the first field if necessary
6534 (setq new (concat new))
6535 (if (string-match "^[ \t]*| *[#$] *|" line)
6536 (setq new (replace-match (match-string 0 line) t t new)))
6537 (beginning-of-line (if arg 2 1))
6538 (let (org-table-may-need-update)
6539 (insert-before-markers new)
6540 (insert-before-markers "\n"))
6541 (beginning-of-line 0)
6542 (re-search-forward "| ?" (point-at-eol) t)
6543 (and org-table-may-need-update (org-table-align))))
6544
6545 (defun org-table-insert-hline (&optional arg)
6546 "Insert a horizontal-line below the current line into the table.
6547 With prefix ARG, insert above the current line."
6548 (interactive "P")
6549 (if (not (org-at-table-p))
6550 (error "Not at a table"))
6551 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6552 (col (current-column))
6553 start)
6554 (if (string-match "^[ \t]*|-" line)
6555 (setq line
6556 (mapcar (lambda (x) (if (member x '(?| ?+))
6557 (prog1 (if start ?+ ?|) (setq start t))
6558 (if start ?- ?\ )))
6559 line))
6560 (setq line
6561 (mapcar (lambda (x) (if (equal x ?|)
6562 (prog1 (if start ?+ ?|) (setq start t))
6563 (if start ?- ?\ )))
6564 line)))
6565 (beginning-of-line (if arg 1 2))
6566 (apply 'insert line)
6567 (if (equal (char-before (point)) ?+)
6568 (progn (backward-delete-char 1) (insert "|")))
6569 (insert "\n")
6570 (beginning-of-line 0)
6571 (move-to-column col)))
6572
6573 (defun org-table-kill-row ()
6574 "Delete the current row or horizontal line from the table."
6575 (interactive)
6576 (if (not (org-at-table-p))
6577 (error "Not at a table"))
6578 (let ((col (current-column)))
6579 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6580 (if (not (org-at-table-p)) (beginning-of-line 0))
6581 (move-to-column col)))
6582
6583
6584 (defun org-table-cut-region (beg end)
6585 "Copy region in table to the clipboard and blank all relevant fields."
6586 (interactive "r")
6587 (org-table-copy-region beg end 'cut))
6588
6589 (defun org-table-copy-region (beg end &optional cut)
6590 "Copy rectangular region in table to clipboard.
6591 A special clipboard is used which can only be accessed
6592 with `org-table-paste-rectangle'."
6593 (interactive "rP")
6594 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6595 region cols
6596 (rpl (if cut " " nil)))
6597 (goto-char beg)
6598 (org-table-check-inside-data-field)
6599 (setq l01 (count-lines (point-min) (point))
6600 c01 (org-table-current-column))
6601 (goto-char end)
6602 (org-table-check-inside-data-field)
6603 (setq l02 (count-lines (point-min) (point))
6604 c02 (org-table-current-column))
6605 (setq l1 (min l01 l02) l2 (max l01 l02)
6606 c1 (min c01 c02) c2 (max c01 c02))
6607 (catch 'exit
6608 (while t
6609 (catch 'nextline
6610 (if (> l1 l2) (throw 'exit t))
6611 (goto-line l1)
6612 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6613 (setq cols nil ic1 c1 ic2 c2)
6614 (while (< ic1 (1+ ic2))
6615 (push (org-table-get-field ic1 rpl) cols)
6616 (setq ic1 (1+ ic1)))
6617 (push (nreverse cols) region)
6618 (setq l1 (1+ l1)))))
6619 (setq org-table-clip (nreverse region))
6620 (if cut (org-table-align))
6621 org-table-clip))
6622
6623 (defun org-table-paste-rectangle ()
6624 "Paste a rectangular region into a table.
6625 The upper right corner ends up in the current field. All involved fields
6626 will be overwritten. If the rectangle does not fit into the present table,
6627 the table is enlarged as needed. The process ignores horizontal separator
6628 lines."
6629 (interactive)
6630 (unless (and org-table-clip (listp org-table-clip))
6631 (error "First cut/copy a region to paste!"))
6632 (org-table-check-inside-data-field)
6633 (let* ((clip org-table-clip)
6634 (line (count-lines (point-min) (point)))
6635 (col (org-table-current-column))
6636 (org-enable-table-editor t)
6637 (org-table-automatic-realign nil)
6638 c cols field)
6639 (while (setq cols (pop clip))
6640 (while (org-at-table-hline-p) (beginning-of-line 2))
6641 (if (not (org-at-table-p))
6642 (progn (end-of-line 0) (org-table-next-field)))
6643 (setq c col)
6644 (while (setq field (pop cols))
6645 (org-table-goto-column c nil 'force)
6646 (org-table-get-field nil field)
6647 (setq c (1+ c)))
6648 (beginning-of-line 2))
6649 (goto-line line)
6650 (org-table-goto-column col)
6651 (org-table-align)))
6652
6653 (defun org-table-convert ()
6654 "Convert from `org-mode' table to table.el and back.
6655 Obviously, this only works within limits. When an Org-mode table is
6656 converted to table.el, all horizontal separator lines get lost, because
6657 table.el uses these as cell boundaries and has no notion of horizontal lines.
6658 A table.el table can be converted to an Org-mode table only if it does not
6659 do row or column spanning. Multiline cells will become multiple cells.
6660 Beware, Org-mode does not test if the table can be successfully converted - it
6661 blindly applies a recipe that works for simple tables."
6662 (interactive)
6663 (require 'table)
6664 (if (org-at-table.el-p)
6665 ;; convert to Org-mode table
6666 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6667 (end (move-marker (make-marker) (org-table-end t))))
6668 (table-unrecognize-region beg end)
6669 (goto-char beg)
6670 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6671 (replace-match ""))
6672 (goto-char beg))
6673 (if (org-at-table-p)
6674 ;; convert to table.el table
6675 (let ((beg (move-marker (make-marker) (org-table-begin)))
6676 (end (move-marker (make-marker) (org-table-end))))
6677 ;; first, get rid of all horizontal lines
6678 (goto-char beg)
6679 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6680 (replace-match ""))
6681 ;; insert a hline before first
6682 (goto-char beg)
6683 (org-table-insert-hline 'above)
6684 ;; insert a hline after each line
6685 (while (progn (beginning-of-line 2) (< (point) end))
6686 (org-table-insert-hline))
6687 (goto-char beg)
6688 (setq end (move-marker end (org-table-end)))
6689 ;; replace "+" at beginning and ending of hlines
6690 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6691 (replace-match "\\1+-"))
6692 (goto-char beg)
6693 (while (re-search-forward "-|[ \t]*$" end t)
6694 (replace-match "-+"))
6695 (goto-char beg)))))
6696
6697 (defun org-table-wrap-region (arg)
6698 "Wrap several fields in a column like a paragraph.
6699 This is useful if you'd like to spread the contents of a field over several
6700 lines, in order to keep the table compact.
6701
6702 If there is an active region, and both point and mark are in the same column,
6703 the text in the column is wrapped to minimum width for the given number of
6704 lines. Generally, this makes the table more compact. A prefix ARG may be
6705 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6706 formats the selected text to two lines. If the region was longer than 2
6707 lines, the remaining lines remain empty. A negative prefix argument reduces
6708 the current number of lines by that amount. The wrapped text is pasted back
6709 into the table. If you formatted it to more lines than it was before, fields
6710 further down in the table get overwritten - so you might need to make space in
6711 the table first.
6712
6713 If there is no region, the current field is split at the cursor position and
6714 the text fragment to the right of the cursor is prepended to the field one
6715 line down.
6716
6717 If there is no region, but you specify a prefix ARG, the current field gets
6718 blank, and the content is appended to the field above."
6719 (interactive "P")
6720 (org-table-check-inside-data-field)
6721 (if (org-region-active-p)
6722 ;; There is a region: fill as a paragraph
6723 (let ((beg (region-beginning))
6724 nlines)
6725 (org-table-cut-region (region-beginning) (region-end))
6726 (if (> (length (car org-table-clip)) 1)
6727 (error "Region must be limited to single column"))
6728 (setq nlines (if arg
6729 (if (< arg 1)
6730 (+ (length org-table-clip) arg)
6731 arg)
6732 (length org-table-clip)))
6733 (setq org-table-clip
6734 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6735 nil nlines)))
6736 (goto-char beg)
6737 (org-table-paste-rectangle))
6738 ;; No region, split the current field at point
6739 (if arg
6740 ;; combine with field above
6741 (let ((s (org-table-blank-field))
6742 (col (org-table-current-column)))
6743 (beginning-of-line 0)
6744 (while (org-at-table-hline-p) (beginning-of-line 0))
6745 (org-table-goto-column col)
6746 (skip-chars-forward "^|")
6747 (skip-chars-backward " ")
6748 (insert " " (org-trim s))
6749 (org-table-align))
6750 ;; split field
6751 (when (looking-at "\\([^|]+\\)+|")
6752 (let ((s (match-string 1)))
6753 (replace-match " |")
6754 (goto-char (match-beginning 0))
6755 (org-table-next-row)
6756 (insert (org-trim s) " ")
6757 (org-table-align))))))
6758
6759 (defun org-trim (s)
6760 "Remove whitespace at beginning and end of string."
6761 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6762 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6763 s)
6764
6765 (defun org-wrap (string &optional width lines)
6766 "Wrap string to either a number of lines, or a width in characters.
6767 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6768 that costs. If there is a word longer than WIDTH, the text is actually
6769 wrapped to the length of that word.
6770 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6771 many lines, whatever width that takes.
6772 The return value is a list of lines, without newlines at the end."
6773 (let* ((words (org-split-string string "[ \t\n]+"))
6774 (maxword (apply 'max (mapcar 'length words)))
6775 w ll)
6776 (cond (width
6777 (org-do-wrap words (max maxword width)))
6778 (lines
6779 (setq w maxword)
6780 (setq ll (org-do-wrap words maxword))
6781 (if (<= (length ll) lines)
6782 ll
6783 (setq ll words)
6784 (while (> (length ll) lines)
6785 (setq w (1+ w))
6786 (setq ll (org-do-wrap words w)))
6787 ll))
6788 (t (error "Cannot wrap this")))))
6789
6790
6791 (defun org-do-wrap (words width)
6792 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6793 (let (lines line)
6794 (while words
6795 (setq line (pop words))
6796 (while (and words (< (+ (length line) (length (car words))) width))
6797 (setq line (concat line " " (pop words))))
6798 (setq lines (push line lines)))
6799 (nreverse lines)))
6800
6801 ;; FIXME: I think I can make this more efficient
6802 (defun org-split-string (string &optional separators)
6803 "Splits STRING into substrings at SEPARATORS.
6804 No empty strings are returned if there are matches at the beginning
6805 and end of string."
6806 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6807 (start 0)
6808 notfirst
6809 (list nil))
6810 (while (and (string-match rexp string
6811 (if (and notfirst
6812 (= start (match-beginning 0))
6813 (< start (length string)))
6814 (1+ start) start))
6815 (< (match-beginning 0) (length string)))
6816 (setq notfirst t)
6817 (or (eq (match-beginning 0) 0)
6818 (and (eq (match-beginning 0) (match-end 0))
6819 (eq (match-beginning 0) start))
6820 (setq list
6821 (cons (substring string start (match-beginning 0))
6822 list)))
6823 (setq start (match-end 0)))
6824 (or (eq start (length string))
6825 (setq list
6826 (cons (substring string start)
6827 list)))
6828 (nreverse list)))
6829
6830 (defun org-table-add-invisible-to-vertical-lines ()
6831 "Add an `invisible' property to vertical lines of current table."
6832 (interactive)
6833 (let* ((beg (org-table-begin))
6834 (end (org-table-end))
6835 (end1))
6836 (save-excursion
6837 (goto-char beg)
6838 (while (< (point) end)
6839 (setq end1 (point-at-eol))
6840 (if (looking-at org-table-dataline-regexp)
6841 (while (re-search-forward "|" end1 t)
6842 (add-text-properties (1- (point)) (point)
6843 '(invisible org-table)))
6844 (while (re-search-forward "[+|]" end1 t)
6845 (add-text-properties (1- (point)) (point)
6846 '(invisible org-table))))
6847 (beginning-of-line 2)))))
6848
6849 (defun org-table-toggle-vline-visibility (&optional arg)
6850 "Toggle the visibility of table vertical lines.
6851 The effect is immediate and on all tables in the file.
6852 With prefix ARG, make lines invisible when ARG is positive, make lines
6853 visible when ARG is not positive."
6854 (interactive "P")
6855 (let ((action (cond
6856 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6857 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6858 (t (if (org-in-invisibility-spec-p '(org-table))
6859 'off
6860 'on)))))
6861 (if (eq action 'off)
6862 (progn
6863 (org-remove-from-invisibility-spec '(org-table))
6864 (org-table-map-tables 'org-table-align)
6865 (message "Vertical table lines visible")
6866 (if (org-at-table-p)
6867 (org-table-align)))
6868 (org-add-to-invisibility-spec '(org-table))
6869 (org-table-map-tables 'org-table-align)
6870 (message "Vertical table lines invisible"))
6871 (redraw-frame (selected-frame))))
6872
6873 (defun org-table-map-tables (function)
6874 "Apply FUNCTION to the start of all tables in the buffer."
6875 (save-excursion
6876 (save-restriction
6877 (widen)
6878 (goto-char (point-min))
6879 (while (re-search-forward org-table-any-line-regexp nil t)
6880 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6881 (beginning-of-line 1)
6882 (if (looking-at org-table-line-regexp)
6883 (save-excursion (funcall function)))
6884 (re-search-forward org-table-any-border-regexp nil 1)))))
6885
6886 (defun org-table-sum (&optional beg end nlast)
6887 "Sum numbers in region of current table column.
6888 The result will be displayed in the echo area, and will be available
6889 as kill to be inserted with \\[yank].
6890
6891 If there is an active region, it is interpreted as a rectangle and all
6892 numbers in that rectangle will be summed. If there is no active
6893 region and point is located in a table column, sum all numbers in that
6894 column.
6895
6896 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6897 numbers are assumed to be times as well (in decimal hours) and the
6898 numbers are added as such.
6899
6900 If NLAST is a number, only the NLAST fields will actually be summed."
6901 (interactive)
6902 (save-excursion
6903 (let (col (timecnt 0) diff h m s org-table-clip)
6904 (cond
6905 ((and beg end)) ; beg and end given explicitly
6906 ((org-region-active-p)
6907 (setq beg (region-beginning) end (region-end)))
6908 (t
6909 (setq col (org-table-current-column))
6910 (goto-char (org-table-begin))
6911 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6912 (error "No table data"))
6913 (org-table-goto-column col)
6914 ;not needed? (skip-chars-backward "^|")
6915 (setq beg (point))
6916 (goto-char (org-table-end))
6917 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6918 (error "No table data"))
6919 (org-table-goto-column col)
6920 ;not needed? (skip-chars-forward "^|")
6921 (setq end (point))))
6922 (let* ((items (apply 'append (org-table-copy-region beg end)))
6923 (items1 (cond ((not nlast) items)
6924 ((>= nlast (length items)) items)
6925 (t (setq items (reverse items))
6926 (setcdr (nthcdr (1- nlast) items) nil)
6927 (nreverse items))))
6928 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6929 items1)))
6930 (res (apply '+ numbers))
6931 (sres (if (= timecnt 0)
6932 (format "%g" res)
6933 (setq diff (* 3600 res)
6934 h (floor (/ diff 3600)) diff (mod diff 3600)
6935 m (floor (/ diff 60)) diff (mod diff 60)
6936 s diff)
6937 (format "%d:%02d:%02d" h m s))))
6938 (kill-new sres)
6939 (if (interactive-p)
6940 (message (substitute-command-keys
6941 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6942 (length numbers) sres))))
6943 sres))))
6944
6945 (defun org-table-get-number-for-summing (s)
6946 (let (n)
6947 (if (string-match "^ *|? *" s)
6948 (setq s (replace-match "" nil nil s)))
6949 (if (string-match " *|? *$" s)
6950 (setq s (replace-match "" nil nil s)))
6951 (setq n (string-to-number s))
6952 (cond
6953 ((and (string-match "0" s)
6954 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6955 ((string-match "\\`[ \t]+\\'" s) nil)
6956 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6957 (let ((h (string-to-number (or (match-string 1 s) "0")))
6958 (m (string-to-number (or (match-string 2 s) "0")))
6959 (s (string-to-number (or (match-string 4 s) "0"))))
6960 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6961 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6962 ((equal n 0) nil)
6963 (t n))))
6964
6965 (defvar org-table-formula-history nil)
6966
6967 (defun org-table-get-formula (&optional equation)
6968 "Read a formula from the minibuffer, offer stored formula as default."
6969 (let* ((col (org-table-current-column))
6970 (stored-list (org-table-get-stored-formulas))
6971 (stored (cdr (assoc col stored-list)))
6972 (eq (cond
6973 ((and stored equation (string-match "^ *= *$" equation))
6974 stored)
6975 ((stringp equation)
6976 equation)
6977 (t (read-string
6978 "Formula: " (or stored "") 'org-table-formula-history
6979 stored)))))
6980 (if (not (string-match "\\S-" eq))
6981 (error "Empty formula"))
6982 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
6983 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
6984 (if stored
6985 (setcdr (assoc col stored-list) eq)
6986 (setq stored-list (cons (cons col eq) stored-list)))
6987 (if (not (equal stored eq))
6988 (org-table-store-formulas stored-list))
6989 eq))
6990
6991 (defun org-table-store-formulas (alist)
6992 "Store the list of formulas below the current table."
6993 (setq alist (sort alist (lambda (a b) (< (car a) (car b)))))
6994 (save-excursion
6995 (goto-char (org-table-end))
6996 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
6997 (delete-region (point) (match-end 0)))
6998 (insert "#+TBLFM: "
6999 (mapconcat (lambda (x)
7000 (concat "$" (int-to-string (car x)) "=" (cdr x)))
7001 alist "::")
7002 "\n")))
7003
7004 (defun org-table-get-stored-formulas ()
7005 "Return an alist with the stored formulas directly after current table."
7006 (interactive)
7007 (let (col eq eq-alist strings string)
7008 (save-excursion
7009 (goto-char (org-table-end))
7010 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7011 (setq strings (org-split-string (match-string 2) " *:: *"))
7012 (while (setq string (pop strings))
7013 (if (string-match "\\$\\([0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7014 (setq col (string-to-number (match-string 1 string))
7015 eq (match-string 2 string)
7016 eq-alist (cons (cons col eq) eq-alist))))))
7017 eq-alist))
7018
7019 (defun org-table-modify-formulas (action &rest columns)
7020 "Modify the formulas stored below the current table.
7021 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7022 expected, for the other action only a single column number is needed."
7023 (let ((list (org-table-get-stored-formulas))
7024 (nmax (length (org-split-string (buffer-substring (point-at-bol) (point-at-eol))
7025 "|")))
7026 col col1 col2)
7027 (cond
7028 ((null list)) ; No action needed if there are no stored formulas
7029 ((eq action 'remove)
7030 (setq col (car columns))
7031 (org-table-replace-in-formulas list col "INVALID")
7032 (if (assoc col list) (setq list (delq (assoc col list) list)))
7033 (loop for i from (1+ col) upto nmax by 1 do
7034 (org-table-replace-in-formulas list i (1- i))
7035 (if (assoc i list) (setcar (assoc i list) (1- i)))))
7036 ((eq action 'insert)
7037 (setq col (car columns))
7038 (loop for i from nmax downto col by 1 do
7039 (org-table-replace-in-formulas list i (1+ i))
7040 (if (assoc i list) (setcar (assoc i list) (1+ i)))))
7041 ((eq action 'swap)
7042 (setq col1 (car columns) col2 (nth 1 columns))
7043 (org-table-replace-in-formulas list col1 "Z")
7044 (org-table-replace-in-formulas list col2 col1)
7045 (org-table-replace-in-formulas list "Z" col2)
7046 (if (assoc col1 list) (setcar (assoc col1 list) "Z"))
7047 (if (assoc col2 list) (setcar (assoc col2 list) col1))
7048 (if (assoc "Z" list) (setcar (assoc "Z" list) col2)))
7049 (t (error "Invalid action in `org-table-modify-formulas'")))
7050 (if list (org-table-store-formulas list))))
7051
7052 (defun org-table-replace-in-formulas (list s1 s2)
7053 (let (elt re s)
7054 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7055 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7056 re (concat (regexp-quote s1) "\\>"))
7057 (while (setq elt (pop list))
7058 (setq s (cdr elt))
7059 (while (string-match re s)
7060 (setq s (replace-match s2 t t s)))
7061 (setcdr elt s))))
7062
7063 (defvar org-table-column-names nil
7064 "Alist with column names, derived from the `!' line.")
7065 (defvar org-table-column-name-regexp nil
7066 "Regular expression matching the current column names.")
7067 (defvar org-table-local-parameters nil
7068 "Alist with parameter names, derived from the `$' line.")
7069
7070 (defun org-table-get-specials ()
7071 "Get the column names and local parameters for this table."
7072 (save-excursion
7073 (let ((beg (org-table-begin)) (end (org-table-end))
7074 names name fields field cnt)
7075 (setq org-table-column-names nil
7076 org-table-local-parameters nil)
7077 (goto-char beg)
7078 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7079 (setq names (org-split-string (match-string 1) " *| *")
7080 cnt 1)
7081 (while (setq name (pop names))
7082 (setq cnt (1+ cnt))
7083 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7084 (push (cons name (int-to-string cnt)) org-table-column-names))))
7085 (setq org-table-column-names (nreverse org-table-column-names))
7086 (setq org-table-column-name-regexp
7087 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7088 (goto-char beg)
7089 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7090 (setq fields (org-split-string (match-string 1) " *| *"))
7091 (while (setq field (pop fields))
7092 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\) *= *\\(.*\\)" field)
7093 (push (cons (match-string 1 field) (match-string 2 field))
7094 org-table-local-parameters)))))))
7095
7096 (defun org-this-word ()
7097 ;; Get the current word
7098 (save-excursion
7099 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7100 (end (progn (skip-chars-forward "^ \t\n") (point))))
7101 (buffer-substring-no-properties beg end))))
7102
7103 (defun org-table-maybe-eval-formula ()
7104 "Check if the current field starts with \"=\" and evaluate the formula."
7105 ;; We already know we are in a table. Get field will only return a formula
7106 ;; when appropriate. It might return a separator line, but no problem.
7107 (when org-table-formula-evaluate-inline
7108 (let* ((field (org-trim (or (org-table-get-field) "")))
7109 (dfield (downcase field))
7110 col bolpos nlast)
7111 (when (equal (string-to-char field) ?=)
7112 (if (string-match "^\\(=sum[vh]?\\)\\([0-9]+\\)$" dfield)
7113 (setq nlast (1+ (string-to-number (match-string 2 dfield)))
7114 dfield (match-string 1 dfield)))
7115 (cond
7116 ((equal dfield "=sumh")
7117 (org-table-get-field
7118 nil (org-table-sum
7119 (save-excursion (org-table-goto-column 1) (point))
7120 (point) nlast)))
7121 ((member dfield '("=sum" "=sumv"))
7122 (setq col (org-table-current-column)
7123 bolpos (point-at-bol))
7124 (org-table-get-field
7125 nil (org-table-sum
7126 (save-excursion
7127 (goto-char (org-table-begin))
7128 (if (re-search-forward org-table-dataline-regexp bolpos t)
7129 (progn
7130 (goto-char (match-beginning 0))
7131 (org-table-goto-column col)
7132 (point))
7133 (error "No datalines above current")))
7134 (point) nlast)))
7135 ((and (string-match "^ *=" field)
7136 (fboundp 'calc-eval))
7137 (org-table-eval-formula nil field)))))))
7138
7139 (defvar org-last-recalc-undo-list nil)
7140 (defcustom org-table-allow-line-recalculation t
7141 "FIXME:"
7142 :group 'org-table
7143 :type 'boolean)
7144
7145 (defvar org-recalc-commands nil
7146 "List of commands triggering the recalculation of a line.
7147 Will be filled automatically during use.")
7148
7149 (defvar org-recalc-marks
7150 '((" " . "Unmarked: no special line, no automatic recalculation")
7151 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7152 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7153 ("!" . "Column name definition line. Reference in formula as $name.")
7154 ("$" . "Parameter definition line name=value. Reference in formula as $name.")))
7155
7156 (defun org-table-rotate-recalc-marks (&optional newchar)
7157 "Rotate the recalculation mark in the first column.
7158 If in any row, the first field is not consistent with a mark,
7159 insert a new column for the makers.
7160 When there is an active region, change all the lines in the region,
7161 after prompting for the marking character.
7162 After each change, a message will be displayed indication the meaning
7163 of the new mark."
7164 (interactive)
7165 (unless (org-at-table-p) (error "Not at a table"))
7166 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7167 (beg (org-table-begin))
7168 (end (org-table-end))
7169 (l (org-current-line))
7170 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7171 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7172 (have-col
7173 (save-excursion
7174 (goto-char beg)
7175 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*| \t][^|]*|" end t))))
7176 (col (org-table-current-column))
7177 (forcenew (car (assoc newchar org-recalc-marks)))
7178 epos new)
7179 (if l1 (setq newchar (char-to-string (read-char-exclusive "Change region to what mark? Type # * ! $ or SPC: "))
7180 forcenew (car (assoc newchar org-recalc-marks))))
7181 (if (and newchar (not forcenew))
7182 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7183 newchar))
7184 (if l1 (goto-line l1))
7185 (save-excursion
7186 (beginning-of-line 1)
7187 (unless (looking-at org-table-dataline-regexp)
7188 (error "Not at a table data line")))
7189 (unless have-col
7190 (org-table-goto-column 1)
7191 (org-table-insert-column)
7192 (org-table-goto-column (1+ col)))
7193 (setq epos (point-at-eol))
7194 (save-excursion
7195 (beginning-of-line 1)
7196 (org-table-get-field
7197 1 (if (looking-at "^[ \t]*| *\\([#!$* ]\\) *|")
7198 (concat " "
7199 (setq new (or forcenew
7200 (cadr (member (match-string 1) marks))))
7201 " ")
7202 " # ")))
7203 (if (and l1 l2)
7204 (progn
7205 (goto-line l1)
7206 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7207 (and (looking-at org-table-dataline-regexp)
7208 (org-table-get-field 1 (concat " " new " "))))
7209 (goto-line l1)))
7210 (if (not (= epos (point-at-eol))) (org-table-align))
7211 (goto-line l)
7212 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7213
7214 (defun org-table-maybe-recalculate-line ()
7215 "Recompute the current line if marked for it, and if we haven't just done it."
7216 (interactive)
7217 (and org-table-allow-line-recalculation
7218 (not (and (memq last-command org-recalc-commands)
7219 (equal org-last-recalc-line (org-current-line))))
7220 (save-excursion (beginning-of-line 1)
7221 (looking-at org-table-auto-recalculate-regexp))
7222 (fboundp 'calc-eval)
7223 (org-table-recalculate) t))
7224
7225 (defvar org-table-formula-debug nil
7226 "Non-nil means, debug table formulas.
7227 When nil, simply write \"#ERROR\" in corrupted fields.")
7228
7229 (defvar modes)
7230 (defsubst org-set-calc-mode (var value)
7231 (setcar (or (cdr (memq var modes)) (cons nil nil)) value))
7232
7233 (defun org-table-eval-formula (&optional ndown equation
7234 suppress-align suppress-const
7235 suppress-store)
7236 "Replace the table field value at the cursor by the result of a calculation.
7237
7238 This function makes use of Dave Gillespie's calc package, in my view the
7239 most exciting program ever written for GNU Emacs. So you need to have calc
7240 installed in order to use this function.
7241
7242 In a table, this command replaces the value in the current field with the
7243 result of a formula. While nowhere near the computation options of a
7244 spreadsheet program, this is still very useful. There is no automatic
7245 updating of a calculated field, but the table will remember the last
7246 formula for each column. The command needs to be applied again after
7247 changing input fields.
7248
7249 When called, the command first prompts for a formula, which is read in the
7250 minibuffer. Previously entered formulas are available through the history
7251 list, and the last used formula for each column is offered as a default.
7252 These stored formulas are adapted correctly when moving, inserting, or
7253 deleting columns with the corresponding commands.
7254
7255 The formula can be any algebraic expression understood by the calc package.
7256 Before evaluation, variable substitution takes place: \"$\" is replaced by
7257 the field the cursor is currently in, and $1..$n reference the fields in
7258 the current row. Values from a *different* row can *not* be referenced
7259 here, so the command supports only horizontal computing. The formula can
7260 contain an optional printf format specifier after a semicolon, to reformat
7261 the result.
7262
7263 A few examples for formulas:
7264 $1+$2 Sum of first and second field
7265 $1+$2;%.2f Same, and format result to two digits after dec.point
7266 exp($2)+exp($1) Math functions can be used
7267 $;%.1f Reformat current cell to 1 digit after dec.point
7268 ($3-32)*5/9 Degrees F -> C conversion
7269
7270 When called with a raw \\[universal-argument] prefix, the formula is applied to the current
7271 field, and to the same same column in all following rows, until reaching a
7272 horizontal line or the end of the table. When the command is called with a
7273 numeric prefix argument (like M-3 or C-7 or \\[universal-argument] 24), the formula is applied
7274 to the current row, and to the following n-1 rows (but not beyond a
7275 separator line).
7276
7277 This function can also be called from Lisp programs and offers two additional
7278 Arguments: EQUATION can be the formula to apply. If this argument is given,
7279 the user will not be prompted. SUPPRESS-ALIGN is used to speed-up
7280 recursive calls by by-passing unnecessary aligns. SUPPRESS-CONST suppresses
7281 the interpretation of constants in the formula. SUPPRESS-STORE means the
7282 formula should not be stored, either because it is already stored, or because
7283 it is a modified equation that should not overwrite the stored one."
7284 (interactive "P")
7285 (setq ndown (if (equal ndown '(4)) 10000 (prefix-numeric-value ndown)))
7286 (require 'calc)
7287 (org-table-check-inside-data-field)
7288 (org-table-get-specials)
7289 (let* (fields
7290 (org-table-automatic-realign nil)
7291 (case-fold-search nil)
7292 (down (> ndown 1))
7293 (formula (if (and equation suppress-store)
7294 equation
7295 (org-table-get-formula equation)))
7296 (n0 (org-table-current-column))
7297 (modes (copy-sequence org-calc-default-modes))
7298 n form fmt x ev orig c)
7299 ;; Parse the format
7300 (if (string-match ";" formula)
7301 (let ((tmp (org-split-string formula ";")))
7302 (setq formula (car tmp) fmt (or (nth 1 tmp) ""))
7303 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7304 (setq c (string-to-char (match-string 1 fmt))
7305 n (string-to-number (or (match-string 1 fmt) "")))
7306 (if (= c ?p) (org-set-calc-mode 'calc-internal-prec n)
7307 (org-set-calc-mode 'calc-float-format
7308 (list (cdr (assoc c '((?n. float) (?f. fix)
7309 (?s. sci) (?e. eng))))
7310 n)))
7311 (setq fmt (replace-match "" t t fmt)))
7312 (when (string-match "[DR]" fmt)
7313 (org-set-calc-mode 'calc-angle-mode
7314 (if (equal (match-string 0 fmt) "D")
7315 'deg 'rad))
7316 (setq fmt (replace-match "" t t fmt)))
7317 (when (string-match "F" fmt)
7318 (org-set-calc-mode 'calc-prefer-frac t)
7319 (setq fmt (replace-match "" t t fmt)))
7320 (when (string-match "S" fmt)
7321 (org-set-calc-mode 'calc-symbolic-mode t)
7322 (setq fmt (replace-match "" t t fmt)))
7323 (unless (string-match "\\S-" fmt)
7324 (setq fmt nil))))
7325 (if (and (not suppress-const) org-table-formula-use-constants)
7326 (setq formula (org-table-formula-substitute-names formula)))
7327 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7328 (while (> ndown 0)
7329 (setq fields (org-split-string
7330 (buffer-substring
7331 (point-at-bol) (point-at-eol)) " *| *"))
7332 (if org-table-formula-numbers-only
7333 (setq fields (mapcar
7334 (lambda (x) (number-to-string (string-to-number x)))
7335 fields)))
7336 (setq ndown (1- ndown))
7337 (setq form (copy-sequence formula))
7338 (while (string-match "\\$\\([0-9]+\\)?" form)
7339 (setq n (if (match-beginning 1)
7340 (string-to-int (match-string 1 form))
7341 n0)
7342 x (nth (1- n) fields))
7343 (unless x (error "Invalid field specifier \"%s\""
7344 (match-string 0 form)))
7345 (if (equal x "") (setq x "0"))
7346 (setq form (replace-match (concat "(" x ")") t t form)))
7347 (setq ev (calc-eval (cons form modes)
7348 (if org-table-formula-numbers-only 'num)))
7349
7350 (when org-table-formula-debug
7351 (with-output-to-temp-buffer "*Help*"
7352 (princ (format "Substitution history of formula
7353 Orig: %s
7354 $xyz-> %s
7355 $1-> %s\n" orig formula form))
7356 (if (listp ev)
7357 (princ (format " %s^\nError: %s"
7358 (make-string (car ev) ?\-) (nth 1 ev)))
7359 (princ (format "Result: %s" ev))))
7360 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7361 (unless (and (interactive-p) (not ndown))
7362 (unless (let (inhibit-redisplay)
7363 (y-or-n-p "Debugging Formula. Continue to next? "))
7364 (org-table-align)
7365 (error "Abort"))
7366 (delete-window (get-buffer-window "*Help*"))
7367 (message "")))
7368 (if (listp ev)
7369 (setq fmt nil ev "#ERROR"))
7370 (org-table-blank-field)
7371 (if fmt
7372 (insert (format fmt (string-to-number ev)))
7373 (insert ev))
7374 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7375 (call-interactively 'org-return)
7376 (setq ndown 0)))
7377 (or suppress-align (org-table-align))))
7378
7379 (defun org-table-recalculate (&optional all noalign)
7380 "Recalculate the current table line by applying all stored formulas."
7381 (interactive "P")
7382 (or (memq this-command org-recalc-commands)
7383 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7384 (unless (org-at-table-p) (error "Not at a table"))
7385 (org-table-get-specials)
7386 (let* ((eqlist (sort (org-table-get-stored-formulas)
7387 (lambda (a b) (< (car a) (car b)))))
7388 (inhibit-redisplay t)
7389 (line-re org-table-dataline-regexp)
7390 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7391 (thiscol (org-table-current-column))
7392 beg end entry eql (cnt 0))
7393 ;; Insert constants in all formulas
7394 (setq eqlist
7395 (mapcar (lambda (x)
7396 (setcdr x (org-table-formula-substitute-names (cdr x)))
7397 x)
7398 eqlist))
7399 (if all
7400 (progn
7401 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7402 (goto-char (setq beg (org-table-begin)))
7403 (if (re-search-forward org-table-recalculate-regexp end t)
7404 (setq line-re org-table-recalculate-regexp)
7405 (if (and (re-search-forward org-table-dataline-regexp end t)
7406 (re-search-forward org-table-hline-regexp end t)
7407 (re-search-forward org-table-dataline-regexp end t))
7408 (setq beg (match-beginning 0))
7409 nil))) ;; just leave beg where it is
7410 (setq beg (point-at-bol)
7411 end (move-marker (make-marker) (1+ (point-at-eol)))))
7412 (goto-char beg)
7413 (and all (message "Re-applying formulas to full table..."))
7414 (while (re-search-forward line-re end t)
7415 (unless (string-match "^ *[!$] *$" (org-table-get-field 1))
7416 ;; Unprotected line, recalculate
7417 (and all (message "Re-applying formulas to full table...(line %d)"
7418 (setq cnt (1+ cnt))))
7419 (setq org-last-recalc-line (org-current-line))
7420 (setq eql eqlist)
7421 (while (setq entry (pop eql))
7422 (goto-line org-last-recalc-line)
7423 (org-table-goto-column (car entry) nil 'force)
7424 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7425 (goto-line thisline)
7426 (org-table-goto-column thiscol)
7427 (or noalign (org-table-align)
7428 (and all (message "Re-applying formulas to %d lines...done" cnt)))))
7429
7430 (defun org-table-formula-substitute-names (f)
7431 "Replace $const with values in string F."
7432 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7433 ;; First, check for column names
7434 (while (setq start (string-match org-table-column-name-regexp f start))
7435 (setq start (1+ start))
7436 (setq a (assoc (match-string 1 f) org-table-column-names))
7437 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7438 ;; Expand ranges to vectors
7439 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7440 (setq n1 (string-to-number (match-string 1 f))
7441 n2 (string-to-number (match-string 2 f))
7442 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7443 s (concat "[($" (number-to-string (1- nn1)) ")"))
7444 (loop for i from nn1 upto nn2 do
7445 (setq s (concat s ",($" (int-to-string i) ")")))
7446 (setq s (concat s "]"))
7447 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7448 (setq f (replace-match s t t f)))
7449 ;; Parameters and constants
7450 (setq start 0)
7451 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7452 (setq start (1+ start))
7453 (if (setq a (save-match-data
7454 (org-table-get-constant (match-string 1 f))))
7455 (setq f (replace-match (concat "(" a ")") t t f))))
7456 (if org-table-formula-debug
7457 (put-text-property 0 (length f) :orig-formula f1 f))
7458 f))
7459
7460 (defun org-table-get-constant (const)
7461 "Find the value for a parameter or constant in a formula.
7462 Parameters get priority."
7463 (or (cdr (assoc const org-table-local-parameters))
7464 (cdr (assoc const org-table-formula-constants))
7465 (and (fboundp 'constants-get) (constants-get const))
7466 "#UNDEFINED_NAME"))
7467
7468 ;;; The orgtbl minor mode
7469
7470 ;; Define a minor mode which can be used in other modes in order to
7471 ;; integrate the org-mode table editor.
7472
7473 ;; This is really a hack, because the org-mode table editor uses several
7474 ;; keys which normally belong to the major mode, for example the TAB and
7475 ;; RET keys. Here is how it works: The minor mode defines all the keys
7476 ;; necessary to operate the table editor, but wraps the commands into a
7477 ;; function which tests if the cursor is currently inside a table. If that
7478 ;; is the case, the table editor command is executed. However, when any of
7479 ;; those keys is used outside a table, the function uses `key-binding' to
7480 ;; look up if the key has an associated command in another currently active
7481 ;; keymap (minor modes, major mode, global), and executes that command.
7482 ;; There might be problems if any of the keys used by the table editor is
7483 ;; otherwise used as a prefix key.
7484
7485 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7486 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7487 ;; addresses this by checking explicitly for both bindings.
7488
7489 ;; The optimized version (see variable `orgtbl-optimized') takes over
7490 ;; all keys which are bound to `self-insert-command' in the *global map*.
7491 ;; Some modes bind other commands to simple characters, for example
7492 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7493 ;; active, this binding is ignored inside tables and replaced with a
7494 ;; modified self-insert.
7495
7496 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7497 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7498 In the optimized version, the table editor takes over all simple keys that
7499 normally just insert a character. In tables, the characters are inserted
7500 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7501 for empty fields). Outside tables, the correct binding of the keys is
7502 restored.
7503
7504 The default for this option is t if the optimized version is also used in
7505 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7506 this variable requires a restart of Emacs to become effective."
7507 :group 'org-table
7508 :type 'boolean)
7509
7510 (defvar orgtbl-mode nil
7511 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7512 table editor in arbitrary modes.")
7513 (make-variable-buffer-local 'orgtbl-mode)
7514
7515 (defvar orgtbl-mode-map (make-sparse-keymap)
7516 "Keymap for `orgtbl-mode'.")
7517
7518 ;;;###autoload
7519 (defun turn-on-orgtbl ()
7520 "Unconditionally turn on `orgtbl-mode'."
7521 (orgtbl-mode 1))
7522
7523 ;;;###autoload
7524 (defun orgtbl-mode (&optional arg)
7525 "The `org-mode' table editor as a minor mode for use in other modes."
7526 (interactive)
7527 (if (eq major-mode 'org-mode)
7528 ;; Exit without error, in case some hook functions calls this
7529 ;; by accident in org-mode.
7530 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7531 (setq orgtbl-mode
7532 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7533 (if orgtbl-mode
7534 (progn
7535 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7536 ;; Make sure we are first in minor-mode-map-alist
7537 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7538 (and c (setq minor-mode-map-alist
7539 (cons c (delq c minor-mode-map-alist)))))
7540 (set (make-local-variable (quote org-table-may-need-update)) t)
7541 (make-local-hook (quote before-change-functions))
7542 (add-hook 'before-change-functions 'org-before-change-function
7543 nil 'local)
7544 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7545 auto-fill-inhibit-regexp)
7546 (set (make-local-variable 'auto-fill-inhibit-regexp)
7547 (if auto-fill-inhibit-regexp
7548 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7549 "[ \t]*|"))
7550 (easy-menu-add orgtbl-mode-menu)
7551 (run-hooks 'orgtbl-mode-hook))
7552 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7553 (remove-hook 'before-change-functions 'org-before-change-function t)
7554 (easy-menu-remove orgtbl-mode-menu)
7555 (force-mode-line-update 'all))))
7556
7557 ;; Install it as a minor mode.
7558 (put 'orgtbl-mode :included t)
7559 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7560 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7561
7562 (defun orgtbl-make-binding (fun n &rest keys)
7563 "Create a function for binding in the table minor mode.
7564 FUN is the command to call inside a table. N is used to create a unique
7565 command name. KEYS are keys that should be checked in for a command
7566 to execute outside of tables."
7567 (eval
7568 (list 'defun
7569 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7570 '(arg)
7571 (concat "In tables, run `" (symbol-name fun) "'.\n"
7572 "Outside of tables, run the binding of `"
7573 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7574 "'.")
7575 '(interactive "p")
7576 (list 'if
7577 '(org-at-table-p)
7578 (list 'call-interactively (list 'quote fun))
7579 (list 'let '(orgtbl-mode)
7580 (list 'call-interactively
7581 (append '(or)
7582 (mapcar (lambda (k)
7583 (list 'key-binding k))
7584 keys)
7585 '('orgtbl-error))))))))
7586
7587 (defun orgtbl-error ()
7588 "Error when there is no default binding for a table key."
7589 (interactive)
7590 (error "This key has no function outside tables"))
7591
7592 (defun orgtbl-setup ()
7593 "Setup orgtbl keymaps."
7594 (let ((nfunc 0)
7595 (bindings
7596 (list
7597 '([(meta shift left)] org-table-delete-column)
7598 '([(meta left)] org-table-move-column-left)
7599 '([(meta right)] org-table-move-column-right)
7600 '([(meta shift right)] org-table-insert-column)
7601 '([(meta shift up)] org-table-kill-row)
7602 '([(meta shift down)] org-table-insert-row)
7603 '([(meta up)] org-table-move-row-up)
7604 '([(meta down)] org-table-move-row-down)
7605 '("\C-c\C-w" org-table-cut-region)
7606 '("\C-c\M-w" org-table-copy-region)
7607 '("\C-c\C-y" org-table-paste-rectangle)
7608 '("\C-c-" org-table-insert-hline)
7609 '([(shift tab)] org-table-previous-field)
7610 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7611 '("\C-m" org-table-next-row)
7612 (list (org-key 'S-return) 'org-table-copy-down)
7613 '([(meta return)] org-table-wrap-region)
7614 '("\C-c\C-q" org-table-wrap-region)
7615 '("\C-c?" org-table-current-column)
7616 '("\C-c " org-table-blank-field)
7617 '("\C-c+" org-table-sum)
7618 '("\C-c|" org-table-toggle-vline-visibility)
7619 '("\C-c=" org-table-eval-formula)
7620 '("\C-c*" org-table-recalculate)
7621 '([(control ?#)] org-table-rotate-recalc-marks)))
7622 elt key fun cmd)
7623 (while (setq elt (pop bindings))
7624 (setq nfunc (1+ nfunc))
7625 (setq key (car elt)
7626 fun (nth 1 elt)
7627 cmd (orgtbl-make-binding fun nfunc key))
7628 (define-key orgtbl-mode-map key cmd))
7629 ;; Special treatment needed for TAB and RET
7630 (define-key orgtbl-mode-map [(return)]
7631 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7632 (define-key orgtbl-mode-map "\C-m"
7633 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7634 (define-key orgtbl-mode-map [(tab)]
7635 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7636 (define-key orgtbl-mode-map "\C-i"
7637 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7638 (when orgtbl-optimized
7639 ;; If the user wants maximum table support, we need to hijack
7640 ;; some standard editing functions
7641 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7642 orgtbl-mode-map global-map)
7643 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7644 orgtbl-mode-map global-map)
7645 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7646 orgtbl-mode-map global-map)
7647 (define-key org-mode-map "|" 'self-insert-command))
7648 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7649 '("OrgTbl"
7650 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7651 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7652 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7653 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7654 "--"
7655 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7656 ["Copy Field from Above"
7657 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7658 "--"
7659 ("Column"
7660 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7661 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7662 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7663 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7664 ("Row"
7665 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7666 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7667 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7668 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7669 "--"
7670 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7671 ("Rectangle"
7672 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7673 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7674 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7675 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7676 "--"
7677 ["Eval Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7678 ["Eval Formula Down " (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7679 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7680 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7681 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7682 ["Sum Column/Rectangle" org-table-sum
7683 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7684 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7685 ["Debug Formulas"
7686 (setq org-table-formula-debug (not org-table-formula-debug))
7687 :style toggle :selected org-table-formula-debug]
7688 ))
7689 t)
7690
7691 (defun orgtbl-tab ()
7692 "Justification and field motion for `orgtbl-mode'."
7693 (interactive)
7694 (org-table-justify-field-maybe)
7695 (org-table-next-field))
7696
7697 (defun orgtbl-ret ()
7698 "Justification and field motion for `orgtbl-mode'."
7699 (interactive)
7700 (org-table-justify-field-maybe)
7701 (org-table-next-row))
7702
7703 (defun orgtbl-self-insert-command (N)
7704 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7705 If the cursor is in a table looking at whitespace, the whitespace is
7706 overwritten, and the table is not marked as requiring realignment."
7707 (interactive "p")
7708 (if (and (org-at-table-p)
7709 (eq N 1)
7710 (looking-at "[^|\n]* +|"))
7711 (let (org-table-may-need-update)
7712 (goto-char (1- (match-end 0)))
7713 (delete-backward-char 1)
7714 (goto-char (match-beginning 0))
7715 (self-insert-command N))
7716 (setq org-table-may-need-update t)
7717 (let (orgtbl-mode)
7718 (call-interactively (key-binding (vector last-input-event))))))
7719
7720 (defun orgtbl-delete-backward-char (N)
7721 "Like `delete-backward-char', insert whitespace at field end in tables.
7722 When deleting backwards, in tables this function will insert whitespace in
7723 front of the next \"|\" separator, to keep the table aligned. The table will
7724 still be marked for re-alignment, because a narrow field may lead to a
7725 reduced column width."
7726 (interactive "p")
7727 (if (and (org-at-table-p)
7728 (eq N 1)
7729 (string-match "|" (buffer-substring (point-at-bol) (point)))
7730 (looking-at ".*?|"))
7731 (let ((pos (point)))
7732 (backward-delete-char N)
7733 (skip-chars-forward "^|")
7734 (insert " ")
7735 (goto-char (1- pos)))
7736 (delete-backward-char N)))
7737
7738 (defun orgtbl-delete-char (N)
7739 "Like `delete-char', but insert whitespace at field end in tables.
7740 When deleting characters, in tables this function will insert whitespace in
7741 front of the next \"|\" separator, to keep the table aligned. The table
7742 will still be marked for re-alignment, because a narrow field may lead to
7743 a reduced column width."
7744 (interactive "p")
7745 (if (and (org-at-table-p)
7746 (not (bolp))
7747 (not (= (char-after) ?|))
7748 (eq N 1))
7749 (if (looking-at ".*?|")
7750 (let ((pos (point)))
7751 (replace-match (concat
7752 (substring (match-string 0) 1 -1)
7753 " |"))
7754 (goto-char pos)))
7755 (delete-char N)))
7756
7757 ;;; Exporting
7758
7759 (defconst org-level-max 20)
7760
7761 (defun org-export-find-first-heading-line (list)
7762 "Remove all lines from LIST which are before the first headline."
7763 (let ((orig-list list)
7764 (re (concat "^" outline-regexp)))
7765 (while (and list
7766 (not (string-match re (car list))))
7767 (pop list))
7768 (or list orig-list)))
7769
7770 (defun org-skip-comments (lines)
7771 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
7772 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
7773 (re2 "^\\(\\*+\\)[ \t\n\r]")
7774 rtn line level)
7775 (while (setq line (pop lines))
7776 (cond
7777 ((and (string-match re1 line)
7778 (setq level (- (match-end 1) (match-beginning 1))))
7779 ;; Beginning of a COMMENT subtree. Skip it.
7780 (while (and (setq line (pop lines))
7781 (or (not (string-match re2 line))
7782 (> (- (match-end 1) (match-beginning 1)) level))))
7783 (setq lines (cons line lines)))
7784 ((string-match "^#" line)
7785 ;; an ordinary comment line
7786 )
7787 (t (setq rtn (cons line rtn)))))
7788 (nreverse rtn)))
7789
7790 ;; ASCII
7791
7792 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
7793 "Characters for underlining headings in ASCII export.")
7794
7795 (defconst org-html-entities
7796 '(("nbsp")
7797 ("iexcl")
7798 ("cent")
7799 ("pound")
7800 ("curren")
7801 ("yen")
7802 ("brvbar")
7803 ("sect")
7804 ("uml")
7805 ("copy")
7806 ("ordf")
7807 ("laquo")
7808 ("not")
7809 ("shy")
7810 ("reg")
7811 ("macr")
7812 ("deg")
7813 ("plusmn")
7814 ("sup2")
7815 ("sup3")
7816 ("acute")
7817 ("micro")
7818 ("para")
7819 ("middot")
7820 ("odot"."o")
7821 ("star"."*")
7822 ("cedil")
7823 ("sup1")
7824 ("ordm")
7825 ("raquo")
7826 ("frac14")
7827 ("frac12")
7828 ("frac34")
7829 ("iquest")
7830 ("Agrave")
7831 ("Aacute")
7832 ("Acirc")
7833 ("Atilde")
7834 ("Auml")
7835 ("Aring") ("AA"."&Aring;")
7836 ("AElig")
7837 ("Ccedil")
7838 ("Egrave")
7839 ("Eacute")
7840 ("Ecirc")
7841 ("Euml")
7842 ("Igrave")
7843 ("Iacute")
7844 ("Icirc")
7845 ("Iuml")
7846 ("ETH")
7847 ("Ntilde")
7848 ("Ograve")
7849 ("Oacute")
7850 ("Ocirc")
7851 ("Otilde")
7852 ("Ouml")
7853 ("times")
7854 ("Oslash")
7855 ("Ugrave")
7856 ("Uacute")
7857 ("Ucirc")
7858 ("Uuml")
7859 ("Yacute")
7860 ("THORN")
7861 ("szlig")
7862 ("agrave")
7863 ("aacute")
7864 ("acirc")
7865 ("atilde")
7866 ("auml")
7867 ("aring")
7868 ("aelig")
7869 ("ccedil")
7870 ("egrave")
7871 ("eacute")
7872 ("ecirc")
7873 ("euml")
7874 ("igrave")
7875 ("iacute")
7876 ("icirc")
7877 ("iuml")
7878 ("eth")
7879 ("ntilde")
7880 ("ograve")
7881 ("oacute")
7882 ("ocirc")
7883 ("otilde")
7884 ("ouml")
7885 ("divide")
7886 ("oslash")
7887 ("ugrave")
7888 ("uacute")
7889 ("ucirc")
7890 ("uuml")
7891 ("yacute")
7892 ("thorn")
7893 ("yuml")
7894 ("fnof")
7895 ("Alpha")
7896 ("Beta")
7897 ("Gamma")
7898 ("Delta")
7899 ("Epsilon")
7900 ("Zeta")
7901 ("Eta")
7902 ("Theta")
7903 ("Iota")
7904 ("Kappa")
7905 ("Lambda")
7906 ("Mu")
7907 ("Nu")
7908 ("Xi")
7909 ("Omicron")
7910 ("Pi")
7911 ("Rho")
7912 ("Sigma")
7913 ("Tau")
7914 ("Upsilon")
7915 ("Phi")
7916 ("Chi")
7917 ("Psi")
7918 ("Omega")
7919 ("alpha")
7920 ("beta")
7921 ("gamma")
7922 ("delta")
7923 ("epsilon")
7924 ("varepsilon"."&epsilon;")
7925 ("zeta")
7926 ("eta")
7927 ("theta")
7928 ("iota")
7929 ("kappa")
7930 ("lambda")
7931 ("mu")
7932 ("nu")
7933 ("xi")
7934 ("omicron")
7935 ("pi")
7936 ("rho")
7937 ("sigmaf") ("varsigma"."&sigmaf;")
7938 ("sigma")
7939 ("tau")
7940 ("upsilon")
7941 ("phi")
7942 ("chi")
7943 ("psi")
7944 ("omega")
7945 ("thetasym") ("vartheta"."&thetasym;")
7946 ("upsih")
7947 ("piv")
7948 ("bull") ("bullet"."&bull;")
7949 ("hellip") ("dots"."&hellip;")
7950 ("prime")
7951 ("Prime")
7952 ("oline")
7953 ("frasl")
7954 ("weierp")
7955 ("image")
7956 ("real")
7957 ("trade")
7958 ("alefsym")
7959 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
7960 ("uarr") ("uparrow"."&uarr;")
7961 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
7962 ("darr")("downarrow"."&darr;")
7963 ("harr") ("leftrightarrow"."&harr;")
7964 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
7965 ("lArr") ("Leftarrow"."&lArr;")
7966 ("uArr") ("Uparrow"."&uArr;")
7967 ("rArr") ("Rightarrow"."&rArr;")
7968 ("dArr") ("Downarrow"."&dArr;")
7969 ("hArr") ("Leftrightarrow"."&hArr;")
7970 ("forall")
7971 ("part") ("partial"."&part;")
7972 ("exist") ("exists"."&exist;")
7973 ("empty") ("emptyset"."&empty;")
7974 ("nabla")
7975 ("isin") ("in"."&isin;")
7976 ("notin")
7977 ("ni")
7978 ("prod")
7979 ("sum")
7980 ("minus")
7981 ("lowast") ("ast"."&lowast;")
7982 ("radic")
7983 ("prop") ("proptp"."&prop;")
7984 ("infin") ("infty"."&infin;")
7985 ("ang") ("angle"."&ang;")
7986 ("and") ("vee"."&and;")
7987 ("or") ("wedge"."&or;")
7988 ("cap")
7989 ("cup")
7990 ("int")
7991 ("there4")
7992 ("sim")
7993 ("cong") ("simeq"."&cong;")
7994 ("asymp")("approx"."&asymp;")
7995 ("ne") ("neq"."&ne;")
7996 ("equiv")
7997 ("le")
7998 ("ge")
7999 ("sub") ("subset"."&sub;")
8000 ("sup") ("supset"."&sup;")
8001 ("nsub")
8002 ("sube")
8003 ("supe")
8004 ("oplus")
8005 ("otimes")
8006 ("perp")
8007 ("sdot") ("cdot"."&sdot;")
8008 ("lceil")
8009 ("rceil")
8010 ("lfloor")
8011 ("rfloor")
8012 ("lang")
8013 ("rang")
8014 ("loz") ("Diamond"."&loz;")
8015 ("spades") ("spadesuit"."&spades;")
8016 ("clubs") ("clubsuit"."&clubs;")
8017 ("hearts") ("diamondsuit"."&hearts;")
8018 ("diams") ("diamondsuit"."&diams;")
8019 ("quot")
8020 ("amp")
8021 ("lt")
8022 ("gt")
8023 ("OElig")
8024 ("oelig")
8025 ("Scaron")
8026 ("scaron")
8027 ("Yuml")
8028 ("circ")
8029 ("tilde")
8030 ("ensp")
8031 ("emsp")
8032 ("thinsp")
8033 ("zwnj")
8034 ("zwj")
8035 ("lrm")
8036 ("rlm")
8037 ("ndash")
8038 ("mdash")
8039 ("lsquo")
8040 ("rsquo")
8041 ("sbquo")
8042 ("ldquo")
8043 ("rdquo")
8044 ("bdquo")
8045 ("dagger")
8046 ("Dagger")
8047 ("permil")
8048 ("lsaquo")
8049 ("rsaquo")
8050 ("euro")
8051
8052 ("arccos"."arccos")
8053 ("arcsin"."arcsin")
8054 ("arctan"."arctan")
8055 ("arg"."arg")
8056 ("cos"."cos")
8057 ("cosh"."cosh")
8058 ("cot"."cot")
8059 ("coth"."coth")
8060 ("csc"."csc")
8061 ("deg"."deg")
8062 ("det"."det")
8063 ("dim"."dim")
8064 ("exp"."exp")
8065 ("gcd"."gcd")
8066 ("hom"."hom")
8067 ("inf"."inf")
8068 ("ker"."ker")
8069 ("lg"."lg")
8070 ("lim"."lim")
8071 ("liminf"."liminf")
8072 ("limsup"."limsup")
8073 ("ln"."ln")
8074 ("log"."log")
8075 ("max"."max")
8076 ("min"."min")
8077 ("Pr"."Pr")
8078 ("sec"."sec")
8079 ("sin"."sin")
8080 ("sinh"."sinh")
8081 ("sup"."sup")
8082 ("tan"."tan")
8083 ("tanh"."tanh")
8084 )
8085 "Entities for TeX->HTML translation.
8086 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8087 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8088 In that case, \"\\ent\" will be translated to \"&other;\".
8089 The list contains HTML entities for Latin-1, Greek and other symbols.
8090 It is supplemented by a number of commonly used TeX macros with appropriate
8091 translations. There is currently no way for users to extend this.")
8092
8093 (defvar org-last-level nil) ; dynamically scoped variable
8094
8095 (defun org-export-as-ascii (arg)
8096 "Export the outline as a pretty ASCII file.
8097 If there is an active region, export only the region.
8098 The prefix ARG specifies how many levels of the outline should become
8099 underlined headlines. The default is 3."
8100 (interactive "P")
8101 (setq-default org-todo-line-regexp org-todo-line-regexp)
8102 (let* ((region
8103 (buffer-substring
8104 (if (org-region-active-p) (region-beginning) (point-min))
8105 (if (org-region-active-p) (region-end) (point-max))))
8106 (lines (org-export-find-first-heading-line
8107 (org-skip-comments (org-split-string region "[\r\n]"))))
8108 (org-startup-with-deadline-check nil)
8109 (level 0) line txt
8110 (umax nil)
8111 (case-fold-search nil)
8112 (filename (concat (file-name-sans-extension (buffer-file-name))
8113 ".txt"))
8114 (buffer (find-file-noselect filename))
8115 (levels-open (make-vector org-level-max nil))
8116 (date (format-time-string "%Y/%m/%d" (current-time)))
8117 (time (format-time-string "%X" (current-time)))
8118 (author user-full-name)
8119 (title (buffer-name))
8120 (options nil)
8121 (email user-mail-address)
8122 (language org-export-default-language)
8123 (text nil)
8124 (todo nil)
8125 (lang-words nil))
8126
8127 (setq org-last-level 1)
8128 (org-init-section-numbers)
8129
8130 (find-file-noselect filename)
8131
8132 ;; Search for the export key lines
8133 (org-parse-key-lines)
8134
8135 (setq lang-words (or (assoc language org-export-language-setup)
8136 (assoc "en" org-export-language-setup)))
8137 (if org-export-ascii-show-new-buffer
8138 (switch-to-buffer-other-window buffer)
8139 (set-buffer buffer))
8140 (erase-buffer)
8141 (fundamental-mode)
8142 (if options (org-parse-export-options options))
8143 (setq umax (if arg (prefix-numeric-value arg)
8144 org-export-headline-levels))
8145
8146 ;; File header
8147 (if title (org-insert-centered title ?=))
8148 (insert "\n")
8149 (if (or author email)
8150 (insert (concat (nth 1 lang-words) ": " (or author "")
8151 (if email (concat " <" email ">") "")
8152 "\n")))
8153 (if (and date time)
8154 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8155 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8156
8157 (insert "\n\n")
8158
8159 (if org-export-with-toc
8160 (progn
8161 (insert (nth 3 lang-words) "\n"
8162 (make-string (length (nth 3 lang-words)) ?=) "\n")
8163 (mapcar '(lambda (line)
8164 (if (string-match org-todo-line-regexp
8165 line)
8166 ;; This is a headline
8167 (progn
8168 (setq level (- (match-end 1) (match-beginning 1))
8169 txt (match-string 3 line)
8170 todo
8171 (or (and (match-beginning 2)
8172 (not (equal (match-string 2 line)
8173 org-done-string)))
8174 ; TODO, not DONE
8175 (and (= level umax)
8176 (org-search-todo-below
8177 line lines level))))
8178 (setq txt (org-html-expand-for-ascii txt))
8179
8180 (if org-export-with-section-numbers
8181 (setq txt (concat (org-section-number level)
8182 " " txt)))
8183 (if (<= level umax)
8184 (progn
8185 (insert
8186 (make-string (* (1- level) 4) ?\ )
8187 (format (if todo "%s (*)\n" "%s\n") txt))
8188 (setq org-last-level level))
8189 ))))
8190 lines)))
8191
8192 (org-init-section-numbers)
8193 (while (setq line (pop lines))
8194 ;; Remove the quoted HTML tags.
8195 (setq line (org-html-expand-for-ascii line))
8196 (cond
8197 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8198 ;; a Headline
8199 (setq level (- (match-end 1) (match-beginning 1))
8200 txt (match-string 2 line))
8201 (org-ascii-level-start level txt umax))
8202 (t (insert line "\n"))))
8203 (normal-mode)
8204 (save-buffer)
8205 (goto-char (point-min))))
8206
8207 (defun org-search-todo-below (line lines level)
8208 "Search the subtree below LINE for any TODO entries."
8209 (let ((rest (cdr (memq line lines)))
8210 (re org-todo-line-regexp)
8211 line lv todo)
8212 (catch 'exit
8213 (while (setq line (pop rest))
8214 (if (string-match re line)
8215 (progn
8216 (setq lv (- (match-end 1) (match-beginning 1))
8217 todo (and (match-beginning 2)
8218 (not (equal (match-string 2 line)
8219 org-done-string))))
8220 ; TODO, not DONE
8221 (if (<= lv level) (throw 'exit nil))
8222 (if todo (throw 'exit t))))))))
8223
8224 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8225 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8226 (defun org-html-expand-for-ascii (line)
8227 "Handle quoted HTML for ASCII export."
8228 (if org-export-html-expand
8229 (while (string-match "@<[^<>\n]*>" line)
8230 ;; We just remove the tags for now.
8231 (setq line (replace-match "" nil nil line))))
8232 line)
8233
8234 (defun org-insert-centered (s &optional underline)
8235 "Insert the string S centered and underline it with character UNDERLINE."
8236 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8237 (insert (make-string ind ?\ ) s "\n")
8238 (if underline
8239 (insert (make-string ind ?\ )
8240 (make-string (length s) underline)
8241 "\n"))))
8242
8243 (defun org-ascii-level-start (level title umax)
8244 "Insert a new level in ASCII export."
8245 (let (char)
8246 (if (> level umax)
8247 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8248 (if (or (not (equal (char-before) ?\n))
8249 (not (equal (char-before (1- (point))) ?\n)))
8250 (insert "\n"))
8251 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8252 (if org-export-with-section-numbers
8253 (setq title (concat (org-section-number level) " " title)))
8254 (insert title "\n" (make-string (string-width title) char) "\n"))))
8255
8256 (defun org-export-copy-visible ()
8257 "Copy the visible part of the buffer to another buffer, for printing.
8258 Also removes the first line of the buffer if it specifies a mode,
8259 and all options lines."
8260 (interactive)
8261 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8262 ".txt"))
8263 (buffer (find-file-noselect filename))
8264 (ore (concat
8265 (org-make-options-regexp
8266 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8267 "STARTUP" "ARCHIVE"
8268 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8269 (if org-noutline-p "\\(\n\\|$\\)" "")))
8270 s e)
8271 (with-current-buffer buffer
8272 (erase-buffer)
8273 (text-mode))
8274 (save-excursion
8275 (setq s (goto-char (point-min)))
8276 (while (not (= (point) (point-max)))
8277 (goto-char (org-find-invisible))
8278 (append-to-buffer buffer s (point))
8279 (setq s (goto-char (org-find-visible)))))
8280 (switch-to-buffer-other-window buffer)
8281 (newline)
8282 (goto-char (point-min))
8283 (if (looking-at ".*-\\*- mode:.*\n")
8284 (replace-match ""))
8285 (while (re-search-forward ore nil t)
8286 (replace-match ""))
8287 (goto-char (point-min))))
8288
8289 (defun org-find-visible ()
8290 (if (featurep 'noutline)
8291 (let ((s (point)))
8292 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8293 (get-char-property s 'invisible)))
8294 s)
8295 (skip-chars-forward "^\n")
8296 (point)))
8297 (defun org-find-invisible ()
8298 (if (featurep 'noutline)
8299 (let ((s (point)))
8300 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8301 (not (get-char-property s 'invisible))))
8302 s)
8303 (skip-chars-forward "^\r")
8304 (point)))
8305
8306 ;; HTML
8307
8308 (defun org-get-current-options ()
8309 "Return a string with current options as keyword options.
8310 Does include HTML export options as well as TODO and CATEGORY stuff."
8311 (format
8312 "#+TITLE: %s
8313 #+AUTHOR: %s
8314 #+EMAIL: %s
8315 #+LANGUAGE: %s
8316 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8317 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8318 #+CATEGORY: %s
8319 #+SEQ_TODO: %s
8320 #+TYP_TODO: %s
8321 #+STARTUP: %s %s
8322 #+ARCHIVE: %s
8323 "
8324 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8325 org-export-headline-levels
8326 org-export-with-section-numbers
8327 org-export-with-toc
8328 org-export-preserve-breaks
8329 org-export-html-expand
8330 org-export-with-fixed-width
8331 org-export-with-tables
8332 org-export-with-sub-superscripts
8333 org-export-with-emphasize
8334 org-export-with-TeX-macros
8335 (file-name-nondirectory (buffer-file-name))
8336 (if (equal org-todo-interpretation 'sequence)
8337 (mapconcat 'identity org-todo-keywords " ")
8338 "TODO FEEDBACK VERIFY DONE")
8339 (if (equal org-todo-interpretation 'type)
8340 (mapconcat 'identity org-todo-keywords " ")
8341 "Me Jason Marie DONE")
8342 (cdr (assoc org-startup-folded
8343 '((nil . "nofold")(t . "fold")(content . "content"))))
8344 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8345 org-archive-location
8346 ))
8347
8348 (defun org-insert-export-options-template ()
8349 "Insert into the buffer a template with information for exporting."
8350 (interactive)
8351 (if (not (bolp)) (newline))
8352 (let ((s (org-get-current-options)))
8353 (and (string-match "#\\+CATEGORY" s)
8354 (setq s (substring s 0 (match-beginning 0))))
8355 (insert s)))
8356
8357 (defun org-toggle-fixed-width-section (arg)
8358 "Toggle the fixed-width indicator at the beginning of lines in the region.
8359 If there is no active region, only acts on the current line.
8360 If the first non-white character in the first line of the region is a
8361 vertical bar \"|\", then the command removes the bar from all lines in
8362 the region. If the first character is not a bar, the command adds a
8363 bar to all lines, in the column given by the beginning of the region.
8364
8365 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8366 (interactive "P")
8367 (let* ((cc 0)
8368 (regionp (org-region-active-p))
8369 (beg (if regionp (region-beginning) (point)))
8370 (end (if regionp (region-end)))
8371 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8372 (re "[ \t]*\\(:\\)")
8373 off)
8374 (save-excursion
8375 (goto-char beg)
8376 (setq cc (current-column))
8377 (beginning-of-line 1)
8378 (setq off (looking-at re))
8379 (while (> nlines 0)
8380 (setq nlines (1- nlines))
8381 (beginning-of-line 1)
8382 (cond
8383 (arg
8384 (move-to-column cc t)
8385 (insert ":\n")
8386 (forward-line -1))
8387 ((and off (looking-at re))
8388 (replace-match "" t t nil 1))
8389 ((not off) (move-to-column cc t) (insert ":")))
8390 (forward-line 1)))))
8391
8392 (defun org-export-as-html-and-open (arg)
8393 "Export the outline as HTML and immediately open it with a browser.
8394 If there is an active region, export only the region.
8395 The prefix ARG specifies how many levels of the outline should become
8396 headlines. The default is 3. Lower levels will become bulleted lists."
8397 (interactive "P")
8398 (org-export-as-html arg 'hidden)
8399 (org-open-file (buffer-file-name)))
8400
8401 (defun org-export-as-html-batch ()
8402 "Call `org-export-as-html', may be used in batch processing as
8403 emacs --batch
8404 --load=$HOME/lib/emacs/org.el
8405 --eval \"(setq org-export-headline-levels 2)\"
8406 --visit=MyFile --funcall org-export-as-html-batch"
8407 (org-export-as-html org-export-headline-levels 'hidden))
8408
8409 (defun org-export-as-html (arg &optional hidden)
8410 "Export the outline as a pretty HTML file.
8411 If there is an active region, export only the region.
8412 The prefix ARG specifies how many levels of the outline should become
8413 headlines. The default is 3. Lower levels will become bulleted lists."
8414 (interactive "P")
8415 (setq-default org-todo-line-regexp org-todo-line-regexp)
8416 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8417 (setq-default org-done-string org-done-string)
8418 (let* ((region-p (org-region-active-p))
8419 (region
8420 (buffer-substring
8421 (if region-p (region-beginning) (point-min))
8422 (if region-p (region-end) (point-max))))
8423 (all_lines
8424 (org-skip-comments (org-split-string region "[\r\n]")))
8425 (lines (org-export-find-first-heading-line all_lines))
8426 (level 0) (line "") (origline "") txt todo
8427 (umax nil)
8428 (filename (concat (file-name-sans-extension (buffer-file-name))
8429 ".html"))
8430 (buffer (find-file-noselect filename))
8431 (levels-open (make-vector org-level-max nil))
8432 (date (format-time-string "%Y/%m/%d" (current-time)))
8433 (time (format-time-string "%X" (current-time)))
8434 (author user-full-name)
8435 (title (buffer-name))
8436 (options nil)
8437 (email user-mail-address)
8438 (language org-export-default-language)
8439 (text nil)
8440 (lang-words nil)
8441 (head-count 0) cnt
8442 (start 0)
8443 table-open type
8444 table-buffer table-orig-buffer
8445 )
8446 (message "Exporting...")
8447
8448 (setq org-last-level 1)
8449 (org-init-section-numbers)
8450
8451 ;; Search for the export key lines
8452 (org-parse-key-lines)
8453 (setq lang-words (or (assoc language org-export-language-setup)
8454 (assoc "en" org-export-language-setup)))
8455
8456 ;; Switch to the output buffer
8457 (if (or hidden (not org-export-html-show-new-buffer))
8458 (set-buffer buffer)
8459 (switch-to-buffer-other-window buffer))
8460 (erase-buffer)
8461 (fundamental-mode)
8462 (let ((case-fold-search nil))
8463 (if options (org-parse-export-options options))
8464 (setq umax (if arg (prefix-numeric-value arg)
8465 org-export-headline-levels))
8466
8467 ;; File header
8468 (insert (format
8469 "<html lang=\"%s\"><head>
8470 <title>%s</title>
8471 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8472 <meta name=generator content=\"Org-mode\">
8473 <meta name=generated content=\"%s %s\">
8474 <meta name=author content=\"%s\">
8475 </head><body>
8476 "
8477 language (org-html-expand title) date time author))
8478 (if title (insert (concat "<H1 align=\"center\">"
8479 (org-html-expand title) "</H1>\n")))
8480 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8481 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
8482 email "&gt;</a>\n")))
8483 (if (or author email) (insert "<br>\n"))
8484 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8485 date " " time "<br>\n")))
8486 (if text (insert (concat "<p>\n" (org-html-expand text))))
8487 (if org-export-with-toc
8488 (progn
8489 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8490 (insert "<ul>\n")
8491 (mapcar '(lambda (line)
8492 (if (string-match org-todo-line-regexp line)
8493 ;; This is a headline
8494 (progn
8495 (setq level (- (match-end 1) (match-beginning 1))
8496 txt (save-match-data
8497 (org-html-expand
8498 (match-string 3 line)))
8499 todo
8500 (or (and (match-beginning 2)
8501 (not (equal (match-string 2 line)
8502 org-done-string)))
8503 ; TODO, not DONE
8504 (and (= level umax)
8505 (org-search-todo-below
8506 line lines level))))
8507 (if org-export-with-section-numbers
8508 (setq txt (concat (org-section-number level)
8509 " " txt)))
8510 (if (<= level umax)
8511 (progn
8512 (setq head-count (+ head-count 1))
8513 (if (> level org-last-level)
8514 (progn
8515 (setq cnt (- level org-last-level))
8516 (while (>= (setq cnt (1- cnt)) 0)
8517 (insert "<ul>"))
8518 (insert "\n")))
8519 (if (< level org-last-level)
8520 (progn
8521 (setq cnt (- org-last-level level))
8522 (while (>= (setq cnt (1- cnt)) 0)
8523 (insert "</ul>"))
8524 (insert "\n")))
8525 (insert
8526 (format
8527 (if todo
8528 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8529 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8530 head-count txt))
8531 (setq org-last-level level))
8532 ))))
8533 lines)
8534 (while (> org-last-level 0)
8535 (setq org-last-level (1- org-last-level))
8536 (insert "</ul>\n"))
8537 ))
8538 (setq head-count 0)
8539 (org-init-section-numbers)
8540 (while (setq line (pop lines) origline line)
8541 ;; Protect the links
8542 (setq start 0)
8543 (while (string-match org-link-maybe-angles-regexp line start)
8544 (setq start (match-end 0))
8545 (setq line (replace-match
8546 (concat "\000" (match-string 1 line) "\000")
8547 t t line)))
8548
8549 ;; replace "<" and ">" by "&lt;" and "&gt;"
8550 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
8551 (setq line (org-html-expand line))
8552
8553 ;; Verbatim lines
8554 (if (and org-export-with-fixed-width
8555 (string-match "^[ \t]*:\\(.*\\)" line))
8556 (progn
8557 (let ((l (match-string 1 line)))
8558 (while (string-match " " l)
8559 (setq l (replace-match "&nbsp;" t t l)))
8560 (insert "\n<span style='font-family:Courier'>"
8561 l "</span>"
8562 (if (and lines
8563 (not (string-match "^[ \t]+\\(:.*\\)"
8564 (car lines))))
8565 "<br>\n" "\n"))))
8566 (setq start 0)
8567 (while (string-match org-protected-link-regexp line start)
8568 (setq start (- (match-end 0) 2))
8569 (setq type (match-string 1 line))
8570 (cond
8571 ((member type '("http" "https" "ftp" "mailto" "news"))
8572 ;; standard URL
8573 (setq line (replace-match
8574 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
8575 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8576 nil nil line)))
8577 ((string= type "file")
8578 ;; FILE link
8579 (let* ((filename (match-string 2 line))
8580 (abs-p (file-name-absolute-p filename))
8581 (thefile (if abs-p (expand-file-name filename) filename))
8582 (thefile (save-match-data
8583 (if (string-match ":[0-9]+$" thefile)
8584 (replace-match "" t t thefile)
8585 thefile)))
8586 (file-is-image-p
8587 (save-match-data
8588 (string-match (org-image-file-name-regexp) thefile))))
8589 (setq line (replace-match
8590 (if (and org-export-html-inline-images
8591 file-is-image-p)
8592 (concat "<img src=\"" thefile "\"/>")
8593 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8594 nil nil line))))
8595
8596 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8597 (setq line (replace-match
8598 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
8599
8600 ;; TODO items
8601 (if (and (string-match org-todo-line-regexp line)
8602 (match-beginning 2))
8603 (if (equal (match-string 2 line) org-done-string)
8604 (setq line (replace-match
8605 "<span style='color:green'>\\2</span>"
8606 nil nil line 2))
8607 (setq line (replace-match "<span style='color:red'>\\2</span>"
8608 nil nil line 2))))
8609
8610 ;; DEADLINES
8611 (if (string-match org-deadline-line-regexp line)
8612 (progn
8613 (if (save-match-data
8614 (string-match "<a href"
8615 (substring line 0 (match-beginning 0))))
8616 nil ; Don't do the replacement - it is inside a link
8617 (setq line (replace-match "<span style='color:red'>\\&</span>"
8618 nil nil line 1)))))
8619
8620 (cond
8621 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8622 ;; This is a headline
8623 (setq level (- (match-end 1) (match-beginning 1))
8624 txt (match-string 2 line))
8625 (if (<= level umax) (setq head-count (+ head-count 1)))
8626 (org-html-level-start level txt umax
8627 (and org-export-with-toc (<= level umax))
8628 head-count))
8629
8630 ((and org-export-with-tables
8631 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8632 (if (not table-open)
8633 ;; New table starts
8634 (setq table-open t table-buffer nil table-orig-buffer nil))
8635 ;; Accumulate lines
8636 (setq table-buffer (cons line table-buffer)
8637 table-orig-buffer (cons origline table-orig-buffer))
8638 (when (or (not lines)
8639 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8640 (car lines))))
8641 (setq table-open nil
8642 table-buffer (nreverse table-buffer)
8643 table-orig-buffer (nreverse table-orig-buffer))
8644 (insert (org-format-table-html table-buffer table-orig-buffer))))
8645 (t
8646 ;; Normal lines
8647 ;; Lines starting with "-", and empty lines make new paragraph.
8648 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8649 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8650 ))
8651 (if org-export-html-with-timestamp
8652 (insert org-export-html-html-helper-timestamp))
8653 (insert "</body>\n</html>\n")
8654 (normal-mode)
8655 (save-buffer)
8656 (goto-char (point-min)))))
8657
8658 (defun org-format-table-html (lines olines)
8659 "Find out which HTML converter to use and return the HTML code."
8660 (if (string-match "^[ \t]*|" (car lines))
8661 ;; A normal org table
8662 (org-format-org-table-html lines)
8663 ;; Table made by table.el - test for spanning
8664 (let* ((hlines (delq nil (mapcar
8665 (lambda (x)
8666 (if (string-match "^[ \t]*\\+-" x) x
8667 nil))
8668 lines)))
8669 (first (car hlines))
8670 (ll (and (string-match "\\S-+" first)
8671 (match-string 0 first)))
8672 (re (concat "^[ \t]*" (regexp-quote ll)))
8673 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8674 hlines))))
8675 (if (and (not spanning)
8676 (not org-export-prefer-native-exporter-for-tables))
8677 ;; We can use my own converter with HTML conversions
8678 (org-format-table-table-html lines)
8679 ;; Need to use the code generator in table.el, with the original text.
8680 (org-format-table-table-html-using-table-generate-source olines)))))
8681
8682 (defun org-format-org-table-html (lines)
8683 "Format a table into HTML."
8684 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8685 (setq lines (nreverse lines))
8686 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8687 (setq lines (nreverse lines))
8688 (let ((head (and org-export-highlight-first-table-line
8689 (delq nil (mapcar
8690 (lambda (x) (string-match "^[ \t]*|-" x))
8691 (cdr lines)))))
8692 line fields html)
8693 (setq html (concat org-export-html-table-tag "\n"))
8694 (while (setq line (pop lines))
8695 (catch 'next-line
8696 (if (string-match "^[ \t]*|-" line)
8697 (progn
8698 (setq head nil) ;; head ends here, first time around
8699 ;; ignore this line
8700 (throw 'next-line t)))
8701 ;; Break the line into fields
8702 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8703 (setq html (concat
8704 html
8705 "<tr>"
8706 (mapconcat (lambda (x)
8707 (if head
8708 (concat "<th>" x "</th>")
8709 (concat "<td valign=\"top\">" x "</td>")))
8710 fields "")
8711 "</tr>\n"))))
8712 (setq html (concat html "</table>\n"))
8713 html))
8714
8715 (defun org-fake-empty-table-line (line)
8716 "Replace everything except \"|\" with spaces."
8717 (let ((i (length line))
8718 (newstr (copy-sequence line)))
8719 (while (> i 0)
8720 (setq i (1- i))
8721 (if (not (eq (aref newstr i) ?|))
8722 (aset newstr i ?\ )))
8723 newstr))
8724
8725 (defun org-format-table-table-html (lines)
8726 "Format a table generated by table.el into HTML.
8727 This conversion does *not* use `table-generate-source' from table.el.
8728 This has the advantage that Org-mode's HTML conversions can be used.
8729 But it has the disadvantage, that no cell- or row-spanning is allowed."
8730 (let (line field-buffer
8731 (head org-export-highlight-first-table-line)
8732 fields html empty)
8733 (setq html (concat org-export-html-table-tag "\n"))
8734 (while (setq line (pop lines))
8735 (setq empty "&nbsp")
8736 (catch 'next-line
8737 (if (string-match "^[ \t]*\\+-" line)
8738 (progn
8739 (if field-buffer
8740 (progn
8741 (setq html (concat
8742 html
8743 "<tr>"
8744 (mapconcat
8745 (lambda (x)
8746 (if (equal x "") (setq x empty))
8747 (if head
8748 (concat "<th valign=\"top\">" x
8749 "</th>\n")
8750 (concat "<td valign=\"top\">" x
8751 "</td>\n")))
8752 field-buffer "\n")
8753 "</tr>\n"))
8754 (setq head nil)
8755 (setq field-buffer nil)))
8756 ;; Ignore this line
8757 (throw 'next-line t)))
8758 ;; Break the line into fields and store the fields
8759 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8760 (if field-buffer
8761 (setq field-buffer (mapcar
8762 (lambda (x)
8763 (concat x "<br>" (pop fields)))
8764 field-buffer))
8765 (setq field-buffer fields))))
8766 (setq html (concat html "</table>\n"))
8767 html))
8768
8769 (defun org-format-table-table-html-using-table-generate-source (lines)
8770 "Format a table into HTML, using `table-generate-source' from table.el.
8771 This has the advantage that cell- or row-spanning is allowed.
8772 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
8773 (require 'table)
8774 (with-current-buffer (get-buffer-create " org-tmp1 ")
8775 (erase-buffer)
8776 (insert (mapconcat 'identity lines "\n"))
8777 (goto-char (point-min))
8778 (if (not (re-search-forward "|[^+]" nil t))
8779 (error "Error processing table"))
8780 (table-recognize-table)
8781 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
8782 (table-generate-source 'html " org-tmp2 ")
8783 (set-buffer " org-tmp2 ")
8784 (buffer-substring (point-min) (point-max))))
8785
8786 (defun org-html-expand (string)
8787 "Prepare STRING for HTML export. Applies all active conversions."
8788 ;; First check if there is a link in the line - if yes, apply conversions
8789 ;; only before the start of the link.
8790 (let* ((m (string-match org-link-regexp string))
8791 (s (if m (substring string 0 m) string))
8792 (r (if m (substring string m) "")))
8793 ;; convert < to &lt; and > to &gt;
8794 (while (string-match "<" s)
8795 (setq s (replace-match "&lt;" t t s)))
8796 (while (string-match ">" s)
8797 (setq s (replace-match "&gt;" t t s)))
8798 (if org-export-html-expand
8799 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
8800 (setq s (replace-match "<\\1>" nil nil s))))
8801 (if org-export-with-emphasize
8802 (setq s (org-export-html-convert-emphasize s)))
8803 (if org-export-with-sub-superscripts
8804 (setq s (org-export-html-convert-sub-super s)))
8805 (if org-export-with-TeX-macros
8806 (let ((start 0) wd ass)
8807 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
8808 (setq wd (match-string 1 s))
8809 (if (setq ass (assoc wd org-html-entities))
8810 (setq s (replace-match (or (cdr ass)
8811 (concat "&" (car ass) ";"))
8812 t t s))
8813 (setq start (+ start (length wd)))))))
8814 (concat s r)))
8815
8816 (defun org-create-multibrace-regexp (left right n)
8817 "Create a regular expression which will match a balanced sexp.
8818 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
8819 as single character strings.
8820 The regexp returned will match the entire expression including the
8821 delimiters. It will also define a single group which contains the
8822 match except for the outermost delimiters. The maximum depth of
8823 stacked delimiters is N. Escaping delimiters is not possible."
8824 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
8825 (or "\\|")
8826 (re nothing)
8827 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
8828 (while (> n 1)
8829 (setq n (1- n)
8830 re (concat re or next)
8831 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
8832 (concat left "\\(" re "\\)" right)))
8833
8834 (defvar org-match-substring-regexp
8835 (concat
8836 "\\([^\\]\\)\\([_^]\\)\\("
8837 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
8838 "\\|"
8839 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
8840 "\\|"
8841 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
8842 "The regular expression matching a sub- or superscript.")
8843
8844 (defun org-export-html-convert-sub-super (string)
8845 "Convert sub- and superscripts in STRING to HTML."
8846 (let (key c)
8847 (while (string-match org-match-substring-regexp string)
8848 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
8849 (setq c (or (match-string 8 string)
8850 (match-string 6 string)
8851 (match-string 5 string)))
8852 (setq string (replace-match
8853 (concat (match-string 1 string)
8854 "<" key ">" c "</" key ">")
8855 t t string)))
8856 (while (string-match "\\\\\\([_^]\\)" string)
8857 (setq string (replace-match (match-string 1 string) t t string))))
8858 string)
8859
8860 (defun org-export-html-convert-emphasize (string)
8861 (while (string-match
8862 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
8863 string)
8864 (setq string (replace-match
8865 (concat "<b>" (match-string 3 string) "</b>")
8866 t t string 2)))
8867 (while (string-match
8868 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
8869 string)
8870 (setq string (replace-match
8871 (concat "<i>" (match-string 3 string) "</i>")
8872 t t string 2)))
8873 (while (string-match
8874 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
8875 string)
8876 (setq string (replace-match
8877 (concat "<u>" (match-string 3 string) "</u>")
8878 t t string 2)))
8879 string)
8880
8881 (defun org-parse-key-lines ()
8882 "Find the special key lines with the information for exporters."
8883 (save-excursion
8884 (goto-char 0)
8885 (let ((re (org-make-options-regexp
8886 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
8887 key)
8888 (while (re-search-forward re nil t)
8889 (setq key (match-string 1))
8890 (cond ((string-equal key "TITLE")
8891 (setq title (match-string 2)))
8892 ((string-equal key "AUTHOR")
8893 (setq author (match-string 2)))
8894 ((string-equal key "EMAIL")
8895 (setq email (match-string 2)))
8896 ((string-equal key "LANGUAGE")
8897 (setq language (match-string 2)))
8898 ((string-equal key "TEXT")
8899 (setq text (concat text "\n" (match-string 2))))
8900 ((string-equal key "OPTIONS")
8901 (setq options (match-string 2))))))))
8902
8903 (defun org-parse-export-options (s)
8904 "Parse the export options line."
8905 (let ((op '(("H" . org-export-headline-levels)
8906 ("num" . org-export-with-section-numbers)
8907 ("toc" . org-export-with-toc)
8908 ("\\n" . org-export-preserve-breaks)
8909 ("@" . org-export-html-expand)
8910 (":" . org-export-with-fixed-width)
8911 ("|" . org-export-with-tables)
8912 ("^" . org-export-with-sub-superscripts)
8913 ("*" . org-export-with-emphasize)
8914 ("TeX" . org-export-with-TeX-macros)))
8915 o)
8916 (while (setq o (pop op))
8917 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
8918 s)
8919 (set (make-local-variable (cdr o))
8920 (car (read-from-string (match-string 1 s))))))))
8921
8922 (defun org-html-level-start (level title umax with-toc head-count)
8923 "Insert a new level in HTML export."
8924 (let ((l (1+ (max level umax))))
8925 (while (<= l org-level-max)
8926 (if (aref levels-open (1- l))
8927 (progn
8928 (org-html-level-close l)
8929 (aset levels-open (1- l) nil)))
8930 (setq l (1+ l)))
8931 (if (> level umax)
8932 (progn
8933 (if (aref levels-open (1- level))
8934 (insert "<li>" title "<p>\n")
8935 (aset levels-open (1- level) t)
8936 (insert "<ul><li>" title "<p>\n")))
8937 (if org-export-with-section-numbers
8938 (setq title (concat (org-section-number level) " " title)))
8939 (setq level (+ level 1))
8940 (if with-toc
8941 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
8942 level head-count title level))
8943 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
8944
8945 (defun org-html-level-close (&rest args)
8946 "Terminate one level in HTML export."
8947 (insert "</ul>"))
8948
8949
8950 ;; Variable holding the vector with section numbers
8951 (defvar org-section-numbers (make-vector org-level-max 0))
8952
8953 (defun org-init-section-numbers ()
8954 "Initialize the vector for the section numbers."
8955 (let* ((level -1)
8956 (numbers (nreverse (org-split-string "" "\\.")))
8957 (depth (1- (length org-section-numbers)))
8958 (i depth) number-string)
8959 (while (>= i 0)
8960 (if (> i level)
8961 (aset org-section-numbers i 0)
8962 (setq number-string (or (car numbers) "0"))
8963 (if (string-match "\\`[A-Z]\\'" number-string)
8964 (aset org-section-numbers i
8965 (- (string-to-char number-string) ?A -1))
8966 (aset org-section-numbers i (string-to-int number-string)))
8967 (pop numbers))
8968 (setq i (1- i)))))
8969
8970 (defun org-section-number (&optional level)
8971 "Return a string with the current section number.
8972 When LEVEL is non-nil, increase section numbers on that level."
8973 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
8974 (when level
8975 (when (> level -1)
8976 (aset org-section-numbers
8977 level (1+ (aref org-section-numbers level))))
8978 (setq idx (1+ level))
8979 (while (<= idx depth)
8980 (if (not (= idx 1))
8981 (aset org-section-numbers idx 0))
8982 (setq idx (1+ idx))))
8983 (setq idx 0)
8984 (while (<= idx depth)
8985 (setq n (aref org-section-numbers idx))
8986 (setq string (concat string (if (not (string= string "")) "." "")
8987 (int-to-string n)))
8988 (setq idx (1+ idx)))
8989 (save-match-data
8990 (if (string-match "\\`\\([@0]\\.\\)+" string)
8991 (setq string (replace-match "" nil nil string)))
8992 (if (string-match "\\(\\.0\\)+\\'" string)
8993 (setq string (replace-match "" nil nil string))))
8994 string))
8995
8996
8997 ;;; Key bindings
8998
8999 ;; - Bindings in Org-mode map are currently
9000 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9001 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9002 ;; e (?) useful from outline-mode
9003 ;; i k @ expendable from outline-mode
9004 ;; 0123456789 ! %^& ()_{} " `' free
9005
9006 (define-key org-mode-map "\C-i" 'org-cycle)
9007 (define-key org-mode-map [(meta tab)] 'org-complete)
9008 (define-key org-mode-map "\M-\C-i" 'org-complete)
9009 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9010 (define-key org-mode-map [(meta left)] 'org-metaleft)
9011 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9012 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9013 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9014 (define-key org-mode-map [(meta right)] 'org-metaright)
9015 (define-key org-mode-map [(meta up)] 'org-metaup)
9016 (define-key org-mode-map [(meta down)] 'org-metadown)
9017 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9018 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9019 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9020 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9021 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9022 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9023 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9024 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9025 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9026 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9027 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9028 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9029 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9030 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9031 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9032 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9033 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9034 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9035 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9036 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9037 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9038 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9039 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9040 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9041 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9042 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9043 (define-key org-mode-map "\C-c[" 'org-add-file)
9044 (define-key org-mode-map "\C-c]" 'org-remove-file)
9045 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9046 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9047 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9048 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9049 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9050 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9051 ;; The following line is e.g. necessary for German keyboards under Suse Linux
9052 (unless org-xemacs-p
9053 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9054 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9055 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9056 (define-key org-mode-map "\C-m" 'org-return)
9057 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9058 (define-key org-mode-map [(meta return)] 'org-meta-return)
9059 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9060 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9061 (define-key org-mode-map "\C-c+" 'org-table-sum)
9062 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9063 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9064 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9065 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9066 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9067 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9068 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9069 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9070 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9071 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9072 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9073 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9074 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9075 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9076 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9077 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9078
9079 (defsubst org-table-p () (org-at-table-p))
9080
9081 (defun org-self-insert-command (N)
9082 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9083 If the cursor is in a table looking at whitespace, the whitespace is
9084 overwritten, and the table is not marked as requiring realignment."
9085 (interactive "p")
9086 (if (and (org-table-p)
9087 (eq N 1)
9088 (looking-at "[^|\n]* +|"))
9089 (let (org-table-may-need-update)
9090 (goto-char (1- (match-end 0)))
9091 (delete-backward-char 1)
9092 (goto-char (match-beginning 0))
9093 (self-insert-command N))
9094 (setq org-table-may-need-update t)
9095 (self-insert-command N)))
9096
9097 ;; FIXME:
9098 ;; The following two functions might still be optimized to trigger
9099 ;; re-alignment less frequently.
9100
9101 (defun org-delete-backward-char (N)
9102 "Like `delete-backward-char', insert whitespace at field end in tables.
9103 When deleting backwards, in tables this function will insert whitespace in
9104 front of the next \"|\" separator, to keep the table aligned. The table will
9105 still be marked for re-alignment, because a narrow field may lead to a
9106 reduced column width."
9107 (interactive "p")
9108 (if (and (org-table-p)
9109 (eq N 1)
9110 (string-match "|" (buffer-substring (point-at-bol) (point)))
9111 (looking-at ".*?|"))
9112 (let ((pos (point)))
9113 (backward-delete-char N)
9114 (skip-chars-forward "^|")
9115 (insert " ")
9116 (goto-char (1- pos)))
9117 (backward-delete-char N)))
9118
9119 (defun org-delete-char (N)
9120 "Like `delete-char', but insert whitespace at field end in tables.
9121 When deleting characters, in tables this function will insert whitespace in
9122 front of the next \"|\" separator, to keep the table aligned. The table
9123 will still be marked for re-alignment, because a narrow field may lead to
9124 a reduced column width."
9125 (interactive "p")
9126 (if (and (org-table-p)
9127 (not (bolp))
9128 (not (= (char-after) ?|))
9129 (eq N 1))
9130 (if (looking-at ".*?|")
9131 (let ((pos (point)))
9132 (replace-match (concat
9133 (substring (match-string 0) 1 -1)
9134 " |"))
9135 (goto-char pos)))
9136 (delete-char N)))
9137
9138 ;; How to do this: Measure non-white length of current string
9139 ;; If equal to column width, we should realign.
9140
9141 (when (eq org-enable-table-editor 'optimized)
9142 ;; If the user wants maximum table support, we need to hijack
9143 ;; some standard editing functions
9144 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9145 org-mode-map global-map)
9146 (substitute-key-definition 'delete-char 'org-delete-char
9147 org-mode-map global-map)
9148 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9149 org-mode-map global-map)
9150 (define-key org-mode-map "|" 'self-insert-command))
9151
9152 (defun org-shiftcursor-error ()
9153 "Throw an error because Shift-Cursor command was applied in wrong context."
9154 (error "This command is only active in tables and on headlines"))
9155
9156 (defun org-shifttab ()
9157 "Call `(org-cycle t)' or `org-table-previous-field'."
9158 (interactive)
9159 (cond
9160 ((org-at-table-p) (org-table-previous-field))
9161 (t (org-cycle '(4)))))
9162
9163 (defun org-shiftmetaleft ()
9164 "Call `org-promote-subtree' or `org-table-delete-column'."
9165 (interactive)
9166 (cond
9167 ((org-at-table-p) (org-table-delete-column))
9168 ((org-on-heading-p) (org-promote-subtree))
9169 (t (org-shiftcursor-error))))
9170
9171 (defun org-shiftmetaright ()
9172 "Call `org-demote-subtree' or `org-table-insert-column'."
9173 (interactive)
9174 (cond
9175 ((org-at-table-p) (org-table-insert-column))
9176 ((org-on-heading-p) (org-demote-subtree))
9177 (t (org-shiftcursor-error))))
9178
9179 (defun org-shiftmetaup (&optional arg)
9180 "Call `org-move-subtree-up' or `org-table-kill-row'."
9181 (interactive "P")
9182 (cond
9183 ((org-at-table-p) (org-table-kill-row))
9184 ((org-on-heading-p) (org-move-subtree-up arg))
9185 (t (org-shiftcursor-error))))
9186 (defun org-shiftmetadown (&optional arg)
9187 "Call `org-move-subtree-down' or `org-table-insert-row'."
9188 (interactive "P")
9189 (cond
9190 ((org-at-table-p) (org-table-insert-row arg))
9191 ((org-on-heading-p) (org-move-subtree-down arg))
9192 (t (org-shiftcursor-error))))
9193
9194 (defun org-metaleft (&optional arg)
9195 "Call `org-do-promote' or `org-table-move-column' to left."
9196 (interactive "P")
9197 (cond
9198 ((org-at-table-p) (org-table-move-column 'left))
9199 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9200 (t (backward-word (prefix-numeric-value arg)))))
9201
9202 (defun org-metaright (&optional arg)
9203 "Call `org-do-demote' or `org-table-move-column' to right."
9204 (interactive "P")
9205 (cond
9206 ((org-at-table-p) (org-table-move-column nil))
9207 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9208 (t (forward-word (prefix-numeric-value arg)))))
9209
9210 (defun org-metaup (&optional arg)
9211 "Call `org-move-subtree-up' or `org-table-move-row' up."
9212 (interactive "P")
9213 (cond
9214 ((org-at-table-p) (org-table-move-row 'up))
9215 ((org-on-heading-p) (org-move-subtree-up arg))
9216 (t (org-shiftcursor-error))))
9217
9218 (defun org-metadown (&optional arg)
9219 "Call `org-move-subtree-down' or `org-table-move-row' down."
9220 (interactive "P")
9221 (cond
9222 ((org-at-table-p) (org-table-move-row nil))
9223 ((org-on-heading-p) (org-move-subtree-down arg))
9224 (t (org-shiftcursor-error))))
9225
9226 (defun org-shiftup (&optional arg)
9227 "Call `org-timestamp-up' or `org-priority-up'."
9228 (interactive "P")
9229 (cond
9230 ((org-at-timestamp-p) (org-timestamp-up arg))
9231 (t (org-priority-up))))
9232
9233 (defun org-shiftdown (&optional arg)
9234 "Call `org-timestamp-down' or `org-priority-down'."
9235 (interactive "P")
9236 (cond
9237 ((org-at-timestamp-p) (org-timestamp-down arg))
9238 (t (org-priority-down))))
9239
9240 (defun org-copy-special ()
9241 "Call either `org-table-copy' or `org-copy-subtree'."
9242 (interactive)
9243 (call-interactively
9244 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9245
9246 (defun org-cut-special ()
9247 "Call either `org-table-copy' or `org-cut-subtree'."
9248 (interactive)
9249 (call-interactively
9250 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9251
9252 (defun org-paste-special (arg)
9253 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9254 (interactive "P")
9255 (if (org-at-table-p)
9256 (org-table-paste-rectangle)
9257 (org-paste-subtree arg)))
9258
9259 (defun org-ctrl-c-ctrl-c (&optional arg)
9260 "Call realign table, or recognize a table.el table, or update keywords.
9261 When the cursor is inside a table created by the table.el package,
9262 activate that table. Otherwise, if the cursor is at a normal table
9263 created with org.el, re-align that table. This command works even if
9264 the automatic table editor has been turned off.
9265 If the cursor is in one of the special #+KEYWORD lines, this triggers
9266 scanning the buffer for these lines and updating the information."
9267 (interactive "P")
9268 (let ((org-enable-table-editor t))
9269 (cond
9270 ((org-at-table.el-p)
9271 (require 'table)
9272 (beginning-of-line 1)
9273 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9274 (table-recognize-table))
9275 ((org-at-table-p)
9276 (org-table-maybe-eval-formula)
9277 (if arg
9278 (org-table-recalculate t)
9279 (org-table-maybe-recalculate-line))
9280 (org-table-align))
9281 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9282 (cond
9283 ((equal (match-string 1) "TBLFM")
9284 ;; Recalculate the table before this line
9285 (save-excursion
9286 (beginning-of-line 1)
9287 (skip-chars-backward " \r\n\t")
9288 (if (org-at-table-p) (org-table-recalculate t))))
9289 (t
9290 (let ((org-inhibit-startup t)) (org-mode)))))
9291 ((org-region-active-p)
9292 (org-table-convert-region (region-beginning) (region-end) arg))
9293 ((and (region-beginning) (region-end))
9294 (if (y-or-n-p "Convert inactive region to table? ")
9295 (org-table-convert-region (region-beginning) (region-end) arg)
9296 (error "Abort")))
9297 (t (error "No table at point, and no region to make one")))))
9298
9299 (defun org-return ()
9300 "Call `org-table-next-row' or `newline'."
9301 (interactive)
9302 (cond
9303 ((org-at-table-p)
9304 (org-table-justify-field-maybe)
9305 (org-table-next-row))
9306 (t (newline))))
9307
9308 (defun org-meta-return (&optional arg)
9309 "Call `org-insert-heading' or `org-table-wrap-region'."
9310 (interactive "P")
9311 (cond
9312 ((org-at-table-p)
9313 (org-table-wrap-region arg))
9314 (t (org-insert-heading))))
9315
9316 ;;; Menu entries
9317
9318 ;; Define the Org-mode menus
9319 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9320 '("Tbl"
9321 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9322 ["Next Field" org-cycle (org-at-table-p)]
9323 ["Previous Field" org-shifttab (org-at-table-p)]
9324 ["Next Row" org-return (org-at-table-p)]
9325 "--"
9326 ["Blank Field" org-table-blank-field (org-at-table-p)]
9327 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9328 "--"
9329 ("Column"
9330 ["Move Column Left" org-metaleft (org-at-table-p)]
9331 ["Move Column Right" org-metaright (org-at-table-p)]
9332 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9333 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9334 ("Row"
9335 ["Move Row Up" org-metaup (org-at-table-p)]
9336 ["Move Row Down" org-metadown (org-at-table-p)]
9337 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9338 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9339 "--"
9340 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9341 ("Rectangle"
9342 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9343 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9344 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9345 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9346 "--"
9347 ("Calculate"
9348 ["Eval Formula" org-table-eval-formula (org-at-table-p)]
9349 ["Eval Formula Down" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9350 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9351 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9352 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9353 ["Sum Column/Rectangle" org-table-sum
9354 (or (org-at-table-p) (org-region-active-p))]
9355 ["Which Column?" org-table-current-column (org-at-table-p)])
9356 ["Debug Formulas"
9357 (setq org-table-formula-debug (not org-table-formula-debug))
9358 :style toggle :selected org-table-formula-debug]
9359 "--"
9360 ["Invisible Vlines" org-table-toggle-vline-visibility
9361 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9362 "--"
9363 ["Create" org-table-create (and (not (org-at-table-p))
9364 org-enable-table-editor)]
9365 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9366 ["Import from File" org-table-import (not (org-at-table-p))]
9367 ["Export to File" org-table-export (org-at-table-p)]
9368 "--"
9369 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9370
9371 (easy-menu-define org-org-menu org-mode-map "Org menu"
9372 '("Org"
9373 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9374 ["Sparse Tree" org-occur t]
9375 ["Show All" show-all t]
9376 "--"
9377 ["New Heading" org-insert-heading t]
9378 ("Navigate Headings"
9379 ["Up" outline-up-heading t]
9380 ["Next" outline-next-visible-heading t]
9381 ["Previous" outline-previous-visible-heading t]
9382 ["Next Same Level" outline-forward-same-level t]
9383 ["Previous Same Level" outline-backward-same-level t]
9384 "--"
9385 ["Jump" org-goto t])
9386 ("Edit Structure"
9387 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9388 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9389 "--"
9390 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9391 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9392 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9393 "--"
9394 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9395 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9396 ["Demote Heading" org-metaright (not (org-at-table-p))]
9397 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9398 "--"
9399 ["Archive Subtree" org-archive-subtree t])
9400 "--"
9401 ("TODO Lists"
9402 ["TODO/DONE/-" org-todo t]
9403 ["Show TODO Tree" org-show-todo-tree t]
9404 "--"
9405 ["Set Priority" org-priority t]
9406 ["Priority Up" org-shiftup t]
9407 ["Priority Down" org-shiftdown t])
9408 ("Dates and Scheduling"
9409 ["Timestamp" org-time-stamp t]
9410 ("Change Date"
9411 ["1 Day Later" org-timestamp-up-day t]
9412 ["1 Day Earlier" org-timestamp-down-day t]
9413 ["1 ... Later" org-shiftup t]
9414 ["1 ... Earlier" org-shiftdown t])
9415 ["Compute Time Range" org-evaluate-time-range t]
9416 ["Schedule Item" org-schedule t]
9417 ["Deadline" org-deadline t]
9418 "--"
9419 ["Goto Calendar" org-goto-calendar t]
9420 ["Date from Calendar" org-date-from-calendar t])
9421 "--"
9422 ("Timeline/Agenda"
9423 ["Show TODO Tree this File" org-show-todo-tree t]
9424 ["Check Deadlines this File" org-check-deadlines t]
9425 ["Timeline Current File" org-timeline t]
9426 "--"
9427 ["Agenda" org-agenda t])
9428 ("File List for Agenda")
9429 "--"
9430 ("Hyperlinks"
9431 ["Store Link (Global)" org-store-link t]
9432 ["Insert Link" org-insert-link t]
9433 ["Follow Link" org-open-at-point t])
9434 "--"
9435 ("Export"
9436 ["ASCII" org-export-as-ascii t]
9437 ["Extract Visible Text" org-export-copy-visible t]
9438 ["HTML" org-export-as-html t]
9439 ["HTML and Open" org-export-as-html-and-open t]
9440 ; ["OPML" org-export-as-opml nil]
9441 "--"
9442 ["Option Template" org-insert-export-options-template t]
9443 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9444 "--"
9445 ("Documentation"
9446 ["Show Version" org-version t]
9447 ["Info Documentation" org-info t])
9448 ("Customize"
9449 ["Browse Org Group" org-customize t]
9450 "--"
9451 ["Build Full Customize Menu" org-create-customize-menu
9452 (fboundp 'customize-menu-create)])
9453 ))
9454
9455 (defun org-info (&optional node)
9456 "Read documentation for Org-mode in the info system.
9457 With optional NODE, go directly to that node."
9458 (interactive)
9459 (require 'info)
9460 (Info-goto-node (format "(org)%s" (or node ""))))
9461
9462 (defun org-install-agenda-files-menu ()
9463 (easy-menu-change
9464 '("Org") "File List for Agenda"
9465 (append
9466 (list
9467 ["Edit File List" (customize-variable 'org-agenda-files) t]
9468 ["Add Current File to List" org-add-file t]
9469 ["Remove Current File from List" org-remove-file t]
9470 "--")
9471 (mapcar 'org-file-menu-entry org-agenda-files))))
9472
9473 ;;; Documentation
9474
9475 (defun org-customize ()
9476 "Call the customize function with `org' as argument."
9477 (interactive)
9478 (customize-browse 'org))
9479
9480 (defun org-create-customize-menu ()
9481 "Create a full customization menu for Org-mode, insert it into the menu."
9482 (interactive)
9483 (if (fboundp 'customize-menu-create)
9484 (progn
9485 (easy-menu-change
9486 '("Org") "Customize"
9487 `(["Browse Org group" org-customize t]
9488 "--"
9489 ,(customize-menu-create 'org)
9490 ["Set" Custom-set t]
9491 ["Save" Custom-save t]
9492 ["Reset to Current" Custom-reset-current t]
9493 ["Reset to Saved" Custom-reset-saved t]
9494 ["Reset to Standard Settings" Custom-reset-standard t]))
9495 (message "\"Org\"-menu now contains full customization menu"))
9496 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9497
9498 ;;; Miscellaneous stuff
9499
9500 (defun org-move-line-down (arg)
9501 "Move the current line down. With prefix argument, move it past ARG lines."
9502 (interactive "p")
9503 (let ((col (current-column))
9504 beg end pos)
9505 (beginning-of-line 1) (setq beg (point))
9506 (beginning-of-line 2) (setq end (point))
9507 (beginning-of-line (+ 1 arg))
9508 (setq pos (move-marker (make-marker) (point)))
9509 (insert (delete-and-extract-region beg end))
9510 (goto-char pos)
9511 (move-to-column col)))
9512
9513 (defun org-move-line-up (arg)
9514 "Move the current line up. With prefix argument, move it past ARG lines."
9515 (interactive "p")
9516 (let ((col (current-column))
9517 beg end pos)
9518 (beginning-of-line 1) (setq beg (point))
9519 (beginning-of-line 2) (setq end (point))
9520 (beginning-of-line (- arg))
9521 (setq pos (move-marker (make-marker) (point)))
9522 (insert (delete-and-extract-region beg end))
9523 (goto-char pos)
9524 (move-to-column col)))
9525
9526 ;; Functions needed for Emacs/XEmacs region compatibility
9527
9528 (defun org-region-active-p ()
9529 "Is `transient-mark-mode' on and the region active?
9530 Works on both Emacs and XEmacs."
9531 (if org-ignore-region
9532 nil
9533 (if org-xemacs-p
9534 (and zmacs-regions (region-active-p))
9535 (and transient-mark-mode mark-active))))
9536
9537 (defun org-add-to-invisibility-spec (arg)
9538 "Add elements to `buffer-invisibility-spec'.
9539 See documentation for `buffer-invisibility-spec' for the kind of elements
9540 that can be added."
9541 (cond
9542 ((fboundp 'add-to-invisibility-spec)
9543 (add-to-invisibility-spec arg))
9544 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9545 (setq buffer-invisibility-spec (list arg)))
9546 (t
9547 (setq buffer-invisibility-spec
9548 (cons arg buffer-invisibility-spec)))))
9549
9550 (defun org-remove-from-invisibility-spec (arg)
9551 "Remove elements from `buffer-invisibility-spec'."
9552 (if (fboundp 'remove-from-invisibility-spec)
9553 (remove-from-invisibility-spec arg)
9554 (if (consp buffer-invisibility-spec)
9555 (setq buffer-invisibility-spec
9556 (delete arg buffer-invisibility-spec)))))
9557
9558 (defun org-in-invisibility-spec-p (arg)
9559 "Is ARG a member of `buffer-invisibility-spec'?."
9560 (if (consp buffer-invisibility-spec)
9561 (member arg buffer-invisibility-spec)
9562 nil))
9563
9564 (defun org-image-file-name-regexp ()
9565 "Return regexp matching the file names of images."
9566 (if (fboundp 'image-file-name-regexp)
9567 (image-file-name-regexp)
9568 (let ((image-file-name-extensions
9569 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9570 "xbm" "xpm" "pbm" "pgm" "ppm")))
9571 (concat "\\."
9572 (regexp-opt (nconc (mapcar 'upcase
9573 image-file-name-extensions)
9574 image-file-name-extensions)
9575 t)
9576 "\\'"))))
9577
9578 ;; Functions needed for compatibility with old outline.el
9579
9580 ;; The following functions capture almost the entire compatibility code
9581 ;; between the different versions of outline-mode. The only other place
9582 ;; where this is important are the font-lock-keywords. Search for
9583 ;; `org-noutline-p' to find it.
9584
9585 ;; C-a should go to the beginning of a *visible* line, also in the
9586 ;; new outline.el. I guess this should be patched into Emacs?
9587 (defun org-beginning-of-line ()
9588 "Go to the beginning of the current line. If that is invisible, continue
9589 to a visible line beginning. This makes the function of C-a more intuitive."
9590 (interactive)
9591 (beginning-of-line 1)
9592 (if (bobp)
9593 nil
9594 (backward-char 1)
9595 (if (org-invisible-p)
9596 (while (and (not (bobp)) (org-invisible-p))
9597 (backward-char 1)
9598 (beginning-of-line 1))
9599 (forward-char 1))))
9600 (when org-noutline-p
9601 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9602
9603 (defun org-invisible-p ()
9604 "Check if point is at a character currently not visible."
9605 (if org-noutline-p
9606 ;; Early versions of noutline don't have `outline-invisible-p'.
9607 (if (fboundp 'outline-invisible-p)
9608 (outline-invisible-p)
9609 (get-char-property (point) 'invisible))
9610 (save-excursion
9611 (skip-chars-backward "^\r\n")
9612 (equal (char-before) ?\r))))
9613
9614 (defun org-back-to-heading (&optional invisible-ok)
9615 "Move to previous heading line, or beginning of this line if it's a heading.
9616 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9617 (if org-noutline-p
9618 (outline-back-to-heading invisible-ok)
9619 (if (looking-at outline-regexp)
9620 t
9621 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9622 outline-regexp)
9623 nil t)
9624 (if invisible-ok
9625 (progn (goto-char (match-end 1))
9626 (looking-at outline-regexp)))
9627 (error "Before first heading")))))
9628
9629 (defun org-on-heading-p (&optional invisible-ok)
9630 "Return t if point is on a (visible) heading line.
9631 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9632 (if org-noutline-p
9633 (outline-on-heading-p 'invisible-ok)
9634 (save-excursion
9635 (skip-chars-backward "^\n\r")
9636 (and (looking-at outline-regexp)
9637 (or invisible-ok
9638 (bobp)
9639 (equal (char-before) ?\n))))))
9640
9641 (defun org-up-heading-all (arg)
9642 "Move to the heading line of which the present line is a subheading.
9643 This function considers both visible and invisible heading lines.
9644 With argument, move up ARG levels."
9645 (if org-noutline-p
9646 (if (fboundp 'outline-up-heading-all)
9647 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9648 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9649 (org-back-to-heading t)
9650 (looking-at outline-regexp)
9651 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9652 (error "Cannot move up %d levels" arg)
9653 (re-search-backward
9654 (concat "[\n\r]" (regexp-quote
9655 (make-string (- (match-end 0) (match-beginning 0) arg)
9656 ?*))
9657 "[^*]"))
9658 (forward-char 1))))
9659
9660 (defun org-show-hidden-entry ()
9661 "Show an entry where even the heading is hidden."
9662 (save-excursion
9663 (if (not org-noutline-p)
9664 (progn
9665 (org-back-to-heading t)
9666 (org-flag-heading nil)))
9667 (org-show-entry)))
9668
9669 (defun org-check-occur-regexp (regexp)
9670 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9671 Of course, only for the old outline mode."
9672 (if org-noutline-p
9673 regexp
9674 (if (string-match "^\\^" regexp)
9675 (concat "[\n\r]" (substring regexp 1))
9676 regexp)))
9677
9678 (defun org-flag-heading (flag &optional entry)
9679 "Flag the current heading. FLAG non-nil means make invisible.
9680 When ENTRY is non-nil, show the entire entry."
9681 (save-excursion
9682 (org-back-to-heading t)
9683 (if (not org-noutline-p)
9684 ;; Make the current headline visible
9685 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9686 ;; Check if we should show the entire entry
9687 (if entry
9688 (progn
9689 (org-show-entry)
9690 (save-excursion ;; FIXME: Is this the fix for points in the -|
9691 ;; middle of text? |
9692 (and (outline-next-heading) ;; |
9693 (org-flag-heading nil)))) ; show the next heading _|
9694 (outline-flag-region (max 1 (1- (point)))
9695 (save-excursion (outline-end-of-heading) (point))
9696 (if org-noutline-p
9697 flag
9698 (if flag ?\r ?\n))))))
9699
9700 (defun org-show-subtree ()
9701 "Show everything after this heading at deeper levels."
9702 (outline-flag-region
9703 (point)
9704 (save-excursion
9705 (outline-end-of-subtree) (outline-next-heading) (point))
9706 (if org-noutline-p nil ?\n)))
9707
9708 (defun org-show-entry ()
9709 "Show the body directly following this heading.
9710 Show the heading too, if it is currently invisible."
9711 (interactive)
9712 (save-excursion
9713 (org-back-to-heading t)
9714 (outline-flag-region
9715 (1- (point))
9716 (save-excursion
9717 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9718 (or (match-beginning 1) (point-max)))
9719 (if org-noutline-p nil ?\n))))
9720
9721
9722 (defun org-make-options-regexp (kwds)
9723 "Make a regular expression for keyword lines."
9724 (concat
9725 (if org-noutline-p "^" "[\n\r]")
9726 "#?[ \t]*\\+\\("
9727 (mapconcat 'regexp-quote kwds "\\|")
9728 "\\):[ \t]*"
9729 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
9730
9731 ;; Advise the bookmark-jump function to make jump position visible
9732 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
9733 (eval-after-load "bookmark"
9734 '(defadvice bookmark-jump (after org-make-visible activate)
9735 "Make the position visible."
9736 (and (eq major-mode 'org-mode)
9737 (org-invisible-p)
9738 (org-show-hierarchy-above))))
9739
9740 ;;; Finish up
9741
9742 (provide 'org)
9743
9744 (run-hooks 'org-load-hook)
9745
9746 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
9747 ;;; org.el ends here