]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-occur-highlights): New variable.
[gnu-emacs] / lisp / textmodes / org.el
1 ;;; org.el --- Outline-based notes management and organize
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.22
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-todo-list "org" "Multi-file todo list from Org mode" t)
63 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
64 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
65 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;;
67 ;; This setup will put all files with extension ".org" into Org-mode. As
68 ;; an alternative, make the first line of a file look like this:
69 ;;
70 ;; MY PROJECTS -*- mode: org; -*-
71 ;;
72 ;; which will select Org-mode for this buffer no matter what the file's
73 ;; name is.
74 ;;
75 ;; Documentation
76 ;; -------------
77 ;; The documentation of Org-mode can be found in the TeXInfo file. The
78 ;; distribution also contains a PDF version of it. At the homepage of
79 ;; Org-mode, you can read the same text online as HTML. There is also an
80 ;; excellent reference card made by Philip Rooke. This card can be found
81 ;; in the etc/ directory of Emacs 22.
82 ;;
83 ;; Changes:
84 ;; -------
85 ;; Version 3.22
86 ;; - CamelCase words link to other locations in the same file.
87 ;; - File links accept search options, to link to specific locations.
88 ;; - Plain list items can be folded with `org-cycle'. See new option
89 ;; `org-cycle-include-plain-lists'.
90 ;; - Sparse trees for specific TODO keywords through numeric prefix
91 ;; argument to `C-c C-v'.
92 ;; - Global TODO list, also for specific keywords.
93 ;; - Matches in sparse trees are highlighted (highlights disappear with
94 ;; next buffer change due to editing).
95 ;;
96 ;; Version 3.21
97 ;; - Improved CSS support for the HTML export. Thanks to Christian Egli.
98 ;; - Editing support for hand-formatted lists
99 ;; - M-S-cursor keys handle plain list items
100 ;; - C-c C-c renumbers ordered plain lists
101 ;;
102 ;; Version 3.20
103 ;; - There is finally an option to make TAB jump over horizontal lines
104 ;; in tables instead of creating a new line before that line.
105 ;; The option is `org-table-tab-jumps-over-hlines', default nil.
106 ;; - New command for sorting tables, on `C-c ^'.
107 ;; - Changes to the HTML exporter
108 ;; - hand-formatted lists are exported correctly, similar to
109 ;; markdown lists. Nested lists are possible. See the docstring
110 ;; of the variable `org-export-plain-list-max-depth'.
111 ;; - cleaned up to produce valid HTML 4.0 (transitional).
112 ;; - support for cascading style sheets.
113 ;; - New command to cycle through all agenda files, on C-,
114 ;; - C-c [ can now also be used to change the sequence of agenda files.
115 ;;
116 ;; Version 3.19
117 ;; - Bug fixes
118 ;;
119 ;; Version 3.18
120 ;; - Export of calendar information in the standard iCalendar format.
121 ;; - Some bug fixes.
122 ;;
123 ;; Version 3.17
124 ;; - HTML export specifies character set depending on coding-system.
125 ;;
126 ;; Version 3.16
127 ;; - In tables, directly after the field motion commands like TAB and RET,
128 ;; typing a character will blank the field. Can be turned off with
129 ;; variable `org-table-auto-blank-field'.
130 ;; - Inactive timestamps with `C-c !'. These do not trigger the agenda
131 ;; and are not linked to the calendar.
132 ;; - Additional key bindings to allow Org-mode to function on a tty emacs.
133 ;; - `C-c C-h' prefix key replaced by `C-c C-x', and `C-c C-x C-h' replaced
134 ;; by `C-c C-x b' (b=Browser). This was necessary to recover the
135 ;; standard meaning of C-h after a prefix key (show prefix bindings).
136 ;;
137 ;; Version 3.15
138 ;; - QUOTE keyword at the beginning of an entry causes fixed-width export
139 ;; of unmodified entry text. `C-c :' toggles this keyword.
140 ;; - New face `org-special-keyword' which is used for COMMENT, QUOTE,
141 ;; DEADLINE and SCHEDULED, and priority cookies. Default is only a weak
142 ;; color, to reduce the amount of aggressive color in the buffer.
143 ;;
144 ;; Version 3.14
145 ;; - Formulas for individual fields in table.
146 ;; - Automatic recalculation in calculating tables.
147 ;; - Named fields and columns in tables.
148 ;; - Fixed bug with calling `org-archive' several times in a row.
149 ;;
150 ;; Version 3.13
151 ;; - Efficiency improvements: Fewer table re-alignments needed.
152 ;; - New special lines in tables, for defining names for individual cells.
153 ;;
154 ;; Version 3.12
155 ;; - Tables can store formulas (one per column) and compute fields.
156 ;; Not quite like a full spreadsheet, but very powerful.
157 ;; - table.el keybinding is now `C-c ~'.
158 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
159 ;; - Small changes to keys in agenda buffer. Affected keys:
160 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
161 ;; - Bug fixes.
162 ;;
163 ;; Version 3.11
164 ;; - Links inserted with C-c C-l are now by default enclosed in angle
165 ;; brackets. See the new variable `org-link-format'.
166 ;; - ">" terminates a link, this is a way to have several links in a line.
167 ;; Both "<" and ">" are no longer allowed as characters in a link.
168 ;; - Archiving of finished tasks.
169 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
170 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
171 ;; - Compatibility problems with viper-mode fixed.
172 ;; - Improved html export of tables.
173 ;; - Various clean-up changes.
174 ;;
175 ;; Version 3.10
176 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
177 ;;
178 ;; Version 3.09
179 ;; - Time-of-day specifications in agenda are extracted and placed
180 ;; into the prefix. Timed entries can be placed into a time grid for
181 ;; day.
182 ;;
183 ;; Version 3.08
184 ;; - "|" no longer allowed as part of a link, to allow links in tables.
185 ;; - The prefix of items in the agenda buffer can be configured.
186 ;; - Cleanup.
187 ;;
188 ;; Version 3.07
189 ;; - Some folding incinsistencies removed.
190 ;; - BBDB links to company-only entries.
191 ;; - Bug fixes and global cleanup.
192 ;;
193 ;; Version 3.06
194 ;; - M-S-RET inserts a new TODO heading.
195 ;; - New startup option `content'.
196 ;; - Better visual response when TODO items in agenda change status.
197 ;; - Window positioning after visibility state changes optimized and made
198 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
199 ;;
200 ;; Version 3.05
201 ;; - Agenda entries from the diary are linked to the diary file, so
202 ;; adding and editing diary entries can be done directly from the agenda.
203 ;; - Many calendar/diary commands available directly from agenda.
204 ;; - Field copying in tables with S-RET does increment.
205 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
206 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
207 ;;
208 ;; Version 3.04
209 ;; - Table editor optimized to need fewer realignments, and to keep
210 ;; table shape when typing in fields.
211 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
212 ;; into arbitrary major modes.
213 ;; - Fixed bug with realignment in XEmacs.
214 ;; - Startup options can be set with special #+STARTUP line.
215 ;; - Heading following a match in org-occur can be suppressed.
216 ;;
217 ;; Version 3.03
218 ;; - Copyright transfer to the FSF.
219 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
220 ;; - Timeline now always contains today, and `.' jumps to it.
221 ;; - Table editor:
222 ;; - cut and paste of rectangular regions in tables
223 ;; - command to convert org-mode table to table.el table and back
224 ;; - command to treat several cells like a paragraph and fill it
225 ;; - command to convert a buffer region to a table
226 ;; - import/export tables as tab-separated files (exchange with Excel)
227 ;; - Agenda:
228 ;; - Sorting mechanism for agenda items rewritten from scratch.
229 ;; - Sorting fully configurable.
230 ;; - Entries specifying a time are sorted together.
231 ;; - Completion also covers option keywords after `#-'.
232 ;; - Bug fixes.
233 ;;
234 ;; Version 3.01
235 ;; - New reference card, thanks to Philip Rooke for creating it.
236 ;; - Single file agenda renamed to "Timeline". It no longer shows
237 ;; warnings about upcoming deadlines/overdue scheduled items.
238 ;; That functionality is now limited to the (multifile) agenda.
239 ;; - When reading a date, the calendar can be manipulated with keys.
240 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
241 ;; - Minor bug fixes and documentation improvements.
242
243 ;;; Code:
244
245 (eval-when-compile (require 'cl) (require 'calendar))
246 (require 'outline)
247 (require 'time-date)
248 (require 'easymenu)
249
250 (defvar calc-embedded-close-formula)
251 (defvar calc-embedded-open-formula)
252 (defvar font-lock-unfontify-region-function)
253
254 ;;; Customization variables
255
256 (defvar org-version "3.22"
257 "The version number of the file org.el.")
258 (defun org-version ()
259 (interactive)
260 (message "Org-mode version %s" org-version))
261
262 ;; The following two constants are for compatibility with different Emacs
263 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
264 ;; The compatibility code in org.el is based on these two constants.
265 (defconst org-xemacs-p (featurep 'xemacs)
266 "Are we running xemacs?")
267 (defconst org-noutline-p (featurep 'noutline)
268 "Are we using the new outline mode?")
269
270 (defgroup org nil
271 "Outline-based notes management and organizer "
272 :tag "Org"
273 :group 'outlines
274 :group 'hypermedia
275 :group 'calendar)
276
277 (defgroup org-startup nil
278 "Options concerning startup of Org-mode."
279 :tag "Org Startup"
280 :group 'org)
281
282 (defcustom org-CUA-compatible nil
283 "Non-nil means use alternative key bindings for S-<cursor movement>.
284 Org-mode used S-<cursor movement> for changing timestamps and priorities.
285 S-<cursor movement> is also used for example by `CUA-mode' to select text.
286 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
287 alternative bindings. Setting this variable to t will replace the following
288 keys both in Org-mode and in the Org-agenda buffer.
289
290 S-RET -> C-S-RET
291 S-up -> M-p
292 S-down -> M-n
293 S-left -> M--
294 S-right -> M-+
295
296 If you do not like the alternative keys, take a look at the variable
297 `org-disputed-keys'.
298
299 This option is only relevant at load-time of Org-mode. Changing it requires
300 a restart of Emacs to become effective."
301 :group 'org-startup
302 :type 'boolean)
303
304 (defvar org-disputed-keys
305 '((S-up [(shift up)] [(meta ?p)])
306 (S-down [(shift down)] [(meta ?n)])
307 (S-left [(shift left)] [(meta ?-)])
308 (S-right [(shift right)] [(meta ?+)])
309 (S-return [(shift return)] [(control shift return)]))
310 "Keys for which Org-mode and other modes compete.
311 This is an alist, cars are symbols for lookup, 1st element is the default key,
312 second element will be used when `org-CUA-compatible' is t.")
313
314 (defun org-key (key)
315 "Select a key according to `org-CUA-compatible'."
316 (nth (if org-CUA-compatible 2 1)
317 (or (assq key org-disputed-keys)
318 (error "Invalid Key %s in `org-key'" key))))
319
320 (defcustom org-startup-folded t
321 "Non-nil means, entering Org-mode will switch to OVERVIEW.
322 This can also be configured on a per-file basis by adding one of
323 the following lines anywhere in the buffer:
324
325 #+STARTUP: fold
326 #+STARTUP: nofold
327 #+STARTUP: content"
328 :group 'org-startup
329 :type '(choice
330 (const :tag "nofold: show all" nil)
331 (const :tag "fold: overview" t)
332 (const :tag "content: all headlines" content)))
333
334 (defcustom org-startup-truncated t
335 "Non-nil means, entering Org-mode will set `truncate-lines'.
336 This is useful since some lines containing links can be very long and
337 uninteresting. Also tables look terrible when wrapped."
338 :group 'org-startup
339 :type 'boolean)
340
341 (defcustom org-startup-with-deadline-check nil
342 "Non-nil means, entering Org-mode will run the deadline check.
343 This means, if you start editing an org file, you will get an
344 immediate reminder of any due deadlines.
345 This can also be configured on a per-file basis by adding one of
346 the following lines anywhere in the buffer:
347
348 #+STARTUP: dlcheck
349 #+STARTUP: nodlcheck"
350 :group 'org-startup
351 :type 'boolean)
352
353 (defcustom org-insert-mode-line-in-empty-file nil
354 "Non-nil means insert the first line setting Org-mode in empty files.
355 When the function `org-mode' is called interactively in an empty file, this
356 normally means that the file name does not automatically trigger Org-mode.
357 To ensure that the file will always be in Org-mode in the future, a
358 line enforcing Org-mode will be inserted into the buffer, if this option
359 has been set."
360 :group 'org-startup
361 :type 'boolean)
362
363 (defgroup org-keywords nil
364 "Options concerning TODO items in Org-mode."
365 :tag "Org Keywords"
366 :group 'org)
367
368 (defcustom org-todo-keywords '("TODO" "DONE")
369 "List of TODO entry keywords.
370 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
371 considered to mean that the entry is \"done\". All the other mean that
372 action is required, and will make the entry show up in todo lists, diaries
373 etc.
374 The command \\[org-todo] cycles an entry through these states, and an
375 additional state where no keyword is present. For details about this
376 cycling, see also the variable `org-todo-interpretation'
377 Changes become only effective after restarting Emacs."
378 :group 'org-keywords
379 :type '(repeat (string :tag "Keyword")))
380
381 (defcustom org-todo-interpretation 'sequence
382 "Controls how TODO keywords are interpreted.
383 \\<org-mode-map>Possible values are `sequence' and `type'.
384 This variable is only relevant if `org-todo-keywords' contains more than two
385 states. There are two ways how these keywords can be used:
386
387 - As a sequence in the process of working on a TODO item, for example
388 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
389 org-todo-interpretation 'sequence)
390
391 - As different types of TODO items, for example
392 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
393 org-todo-interpretation 'type)
394
395 When the states are interpreted as a sequence, \\[org-todo] always cycles
396 to the next state, in order to walk through all different states. So with
397 \\[org-todo], you turn an empty entry into the state TODO. When you started
398 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
399 later to VERIFY and finally to DONE.
400
401 When the states are interpreted as types, \\[org-todo] still cycles through
402 when it is called several times in direct succession, in order to initially
403 select the type. However, if not called immediately after a previous
404 \\[org-todo], it switches from each type directly to DONE. So with the
405 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
406 RELAXED. If you later return to this entry and press \\[org-todo] again,
407 RELAXED will not be changed REMIND, but directly to DONE.
408
409 You can create a large number of types. To initially select a
410 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
411 type with completion. Of course, you can also type the keyword
412 directly into the buffer. M-TAB completes TODO keywords at the
413 beginning of a headline."
414 :group 'org-keywords
415 :type '(choice (const sequence)
416 (const type)))
417
418 (defcustom org-default-priority ?B
419 "The default priority of TODO items.
420 This is the priority an item get if no explicit priority is given."
421 :group 'org-keywords
422 :type 'character)
423
424 (defcustom org-lowest-priority ?C
425 "The lowest priority of TODO items. A character like ?A, ?B etc."
426 :group 'org-keywords
427 :type 'character)
428
429 (defcustom org-deadline-string "DEADLINE:"
430 "String to mark deadline entries.
431 A deadline is this string, followed by a time stamp. Should be a word,
432 terminated by a colon. You can insert a schedule keyword and
433 a timestamp with \\[org-deadline].
434 Changes become only effective after restarting Emacs."
435 :group 'org-keywords
436 :type 'string)
437
438 (defcustom org-scheduled-string "SCHEDULED:"
439 "String to mark scheduled TODO entries.
440 A schedule is this string, followed by a time stamp. Should be a word,
441 terminated by a colon. You can insert a schedule keyword and
442 a timestamp with \\[org-schedule].
443 Changes become only effective after restarting Emacs."
444 :group 'org-keywords
445 :type 'string)
446
447 (defcustom org-comment-string "COMMENT"
448 "Entries starting with this keyword will never be exported.
449 An entry can be toggled between COMMENT and normal with
450 \\[org-toggle-comment].
451 Changes become only effective after restarting Emacs."
452 :group 'org-keywords
453 :type 'string)
454
455 (defcustom org-quote-string "QUOTE"
456 "Entries starting with this keyword will be exported in fixed-width font.
457 Quoting applies only to the text in the entry following the headline, and does
458 not extend beyond the next headline, even if that is lower level.
459 An entry can be toggled between QUOTE and normal with
460 \\[org-toggle-fixed-width-section]"
461 :group 'org-keywords
462 :type 'string)
463
464 (defcustom org-after-todo-state-change-hook nil
465 "Hook which is run after the state of a TODO item was changed.
466 The new state (a string with a todo keyword, or nil) is available in the
467 Lisp variable `state'."
468 :group 'org-keywords
469 :type 'hook)
470
471 ;; Variables for pre-computed regular expressions, all buffer local
472 (defvar org-todo-kwd-priority-p nil
473 "Do TODO items have priorities?")
474 (make-variable-buffer-local 'org-todo-kwd-priority-p)
475 (defvar org-todo-kwd-max-priority nil
476 "Maximum priority of TODO items.")
477 (make-variable-buffer-local 'org-todo-kwd-max-priority)
478 (defvar org-ds-keyword-length 12
479 "Maximum length of the Deadline and SCHEDULED keywords.")
480 (make-variable-buffer-local 'org-ds-keyword-length)
481 (defvar org-done-string nil
482 "The last string in `org-todo-keywords', indicating an item is DONE.")
483 (make-variable-buffer-local 'org-done-string)
484 (defvar org-todo-regexp nil
485 "Matches any of the TODO state keywords.")
486 (make-variable-buffer-local 'org-todo-regexp)
487 (defvar org-not-done-regexp nil
488 "Matches any of the TODO state keywords except the last one.")
489 (make-variable-buffer-local 'org-not-done-regexp)
490 (defvar org-todo-line-regexp nil
491 "Matches a headline and puts TODO state into group 2 if present.")
492 (make-variable-buffer-local 'org-todo-line-regexp)
493 (defvar org-nl-done-regexp nil
494 "Matches newline followed by a headline with the DONE keyword.")
495 (make-variable-buffer-local 'org-nl-done-regexp)
496 (defvar org-looking-at-done-regexp nil
497 "Matches the DONE keyword a point.")
498 (make-variable-buffer-local 'org-looking-at-done-regexp)
499 (defvar org-deadline-regexp nil
500 "Matches the DEADLINE keyword.")
501 (make-variable-buffer-local 'org-deadline-regexp)
502 (defvar org-deadline-time-regexp nil
503 "Matches the DEADLINE keyword together with a time stamp.")
504 (make-variable-buffer-local 'org-deadline-time-regexp)
505 (defvar org-deadline-line-regexp nil
506 "Matches the DEADLINE keyword and the rest of the line.")
507 (make-variable-buffer-local 'org-deadline-line-regexp)
508 (defvar org-scheduled-regexp nil
509 "Matches the SCHEDULED keyword.")
510 (make-variable-buffer-local 'org-scheduled-regexp)
511 (defvar org-scheduled-time-regexp nil
512 "Matches the SCHEDULED keyword together with a time stamp.")
513 (make-variable-buffer-local 'org-scheduled-time-regexp)
514
515 (defvar org-category nil
516 "Variable used by org files to set a category for agenda display.
517 Such files should use a file variable to set it, for example
518
519 -*- mode: org; org-category: \"ELisp\"
520
521 or contain a special line
522
523 #+CATEGORY: ELisp
524
525 If the file does not specify a category, then file's base name
526 is used instead.")
527
528 (defgroup org-time nil
529 "Options concerning time stamps and deadlines in Org-mode."
530 :tag "Org Time"
531 :group 'org)
532
533 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
534 "Formats for `format-time-string' which are used for time stamps.
535 It is not recommended to change this constant.")
536
537
538 (defcustom org-deadline-warning-days 30
539 "No. of days before expiration during which a deadline becomes active.
540 This variable governs the display in the org file."
541 :group 'org-time
542 :type 'number)
543
544 (defcustom org-popup-calendar-for-date-prompt t
545 "Non-nil means, pop up a calendar when prompting for a date.
546 In the calendar, the date can be selected with mouse-1. However, the
547 minibuffer will also be active, and you can simply enter the date as well.
548 When nil, only the minibuffer will be available."
549 :group 'org-time
550 :type 'number)
551
552 (defcustom org-calendar-follow-timestamp-change t
553 "Non-nil means, make the calendar window follow timestamp changes.
554 When a timestamp is modified and the calendar window is visible, it will be
555 moved to the new date."
556 :group 'org-time
557 :type 'boolean)
558
559 (defgroup org-agenda nil
560 "Options concerning agenda display Org-mode."
561 :tag "Org Agenda"
562 :group 'org)
563
564 (defcustom org-agenda-files nil
565 "A list of org files for agenda/diary display.
566 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
567 \\[org-remove-file]. You can also use customize to edit the list."
568 :group 'org-agenda
569 :type '(repeat file))
570
571 (defcustom org-select-timeline-window t
572 "Non-nil means, after creating a timeline, move cursor into Timeline window.
573 When nil, cursor will remain in the current window."
574 :group 'org-agenda
575 :type 'boolean)
576
577 (defcustom org-select-agenda-window t
578 "Non-nil means, after creating an agenda, move cursor into Agenda window.
579 When nil, cursor will remain in the current window."
580 :group 'org-agenda
581 :type 'boolean)
582
583 (defcustom org-fit-agenda-window t
584 "Non-nil means, change window size of agenda to fit content."
585 :group 'org-agenda
586 :type 'boolean)
587
588 (defcustom org-agenda-show-all-dates t
589 "Non-nil means, `org-agenda' shows every day in the selected range.
590 When nil, only the days which actually have entries are shown."
591 :group 'org-agenda
592 :type 'boolean)
593
594 ;; FIXME: First day of month works only for current month because it would
595 ;; require a variable ndays treatment.
596 (defcustom org-agenda-start-on-weekday 1
597 "Non-nil means, start the overview always on the specified weekday.
598 0 Denotes Sunday, 1 denotes Monday etc.
599 When nil, always start on the current day."
600 :group 'org-agenda
601 :type '(choice (const :tag "Today" nil)
602 (const :tag "First day of month" t)
603 (number :tag "Weekday No.")))
604
605 (defcustom org-agenda-ndays 7
606 "Number of days to include in overview display."
607 :group 'org-agenda
608 :type 'number)
609
610 (defcustom org-agenda-include-all-todo t
611 "Non-nil means, the agenda will always contain all TODO entries.
612 When nil, date-less entries will only be shown if `org-agenda' is called
613 with a prefix argument.
614 When non-nil, the TODO entries will be listed at the top of the agenda, before
615 the entries for specific days."
616 :group 'org-agenda
617 :type 'boolean)
618
619 (defcustom org-agenda-include-diary nil
620 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
621 :group 'org-agenda
622 :type 'boolean)
623
624 (defcustom org-calendar-to-agenda-key [?c]
625 "The key to be installed in `calendar-mode-map' for switching to the agenda.
626 The command `org-calendar-goto-agenda' will be bound to this key. The
627 default is the character `c' because then`c' can be used to switch back and
628 force between agenda and calendar."
629 :group 'org-agenda
630 :type 'sexp)
631
632 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
633 "Sorting structure for the agenda items of a single day.
634 This is a list of symbols which will be used in sequence to determine
635 if an entry should be listed before another entry. The following
636 symbols are recognized.
637
638 time-up Put entries with time-of-day indications first, early first
639 time-down Put entries with time-of-day indications first, late first
640 category-keep Keep the default order of categories, corresponding to the
641 sequence in `org-agenda-files'.
642 category-up Sort alphabetically by category, A-Z.
643 category-down Sort alphabetically by category, Z-A.
644 priority-up Sort numerically by priority, high priority last.
645 priority-down Sort numerically by priority, high priority first.
646
647 The different possibilities will be tried in sequence, and testing stops
648 if one comparison returns a \"not-equal\". For example, the default
649 '(time-up category-keep priority-down)
650 means: Pull out all entries having a specified time of day and sort them,
651 in order to make a time schedule for the current day the first thing in the
652 agenda listing for the day. Of the entries without a time indication, keep
653 the grouped in categories, don't sort the categories, but keep them in
654 the sequence given in `org-agenda-files'. Within each category sort by
655 priority.
656
657 Leaving out `category-keep' would mean that items will be sorted across
658 categories by priority."
659 :group 'org-agenda
660 :type '(repeat
661 (choice
662 (const time-up)
663 (const time-down)
664 (const category-keep)
665 (const category-up)
666 (const category-down)
667 (const priority-up)
668 (const priority-down))))
669
670 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
671 "Format specification for the prefix of items in the agenda buffer.
672 This format works similar to a printf format, with the following meaning:
673
674 %c the category of the item, \"Diary\" for entries from the diary, or
675 as given by the CATEGORY keyword or derived from the file name.
676 %t the time-of-day specification if one applies to the entry, in the
677 format HH:MM
678 %s Scheduling/Deadline information, a short string
679
680 All specifiers work basically like the standard `%s' of printf, but may
681 contain two additional characters: A question mark just after the `%' and
682 a whitespace/punctuation character just before the final letter.
683
684 If the first character after `%' is a question mark, the entire field
685 will only be included if the corresponding value applies to the
686 current entry. This is useful for fields which should have fixed
687 width when present, but zero width when absent. For example,
688 \"%?-12t\" will result in a 12 character time field if a time of the
689 day is specified, but will completely disappear in entries which do
690 not contain a time.
691
692 If there is punctuation or whitespace character just before the final
693 format letter, this character will be appended to the field value if
694 the value is not empty. For example, the format \"%-12:c\" leads to
695 \"Diary: \" if the category is \"Diary\". If the category were be
696 empty, no additional colon would be interted.
697
698 The default value of this option is \" %-12:c%?-12t% s\", meaning:
699 - Indent the line with two space characters
700 - Give the category in a 12 chars wide field, padded with whitespace on
701 the right (because of `-'). Append a colon if there is a category
702 (because of `:').
703 - If there is a time-of-day, put it into a 12 chars wide field. If no
704 time, don't put in an empty field, just skip it (because of '?').
705 - Finally, put the scheduling information and append a whitespace.
706
707 As another example, if you don't want the time-of-day of entries in
708 the prefix, you could use:
709
710 (setq org-agenda-prefix-format \" %-11:c% s\")
711
712 See also the variable `org-agenda-remove-times-when-in-prefix'."
713 :type 'string
714 :group 'org-agenda)
715
716 (defcustom org-timeline-prefix-format " % s"
717 "Like `org-agenda-prefix-format', but for the timeline of a single file."
718 :type 'string
719 :group 'org-agenda)
720
721 (defvar org-prefix-format-compiled nil
722 "The compiled version of the most recently used prefix format.
723 Depending on which command was used last, this may be the compiled version
724 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
725
726 (defcustom org-agenda-use-time-grid t
727 "Non-nil means, show a time grid in the agenda schedule.
728 A time grid is a set of lines for specific times (like every two hours between
729 8:00 and 20:00. The items scheduled for a day at specific times are
730 sorted in between these lines.
731 For deails about when the grid will be shown, and what it will look like, see
732 the variable `org-agenda-time-grid'."
733 :group 'org-agenda
734 :type 'boolean)
735
736 (defcustom org-agenda-time-grid
737 '((daily today require-timed)
738 "----------------"
739 (800 1000 1200 1400 1600 1800 2000))
740
741 "The settings for time grid for agenda display.
742 This is a list of three items. The first item is again a list. It contains
743 symbols specifying conditions when the grid should be displayed:
744
745 daily if the agenda shows a single day
746 weekly if the agenda shows an entire week
747 today show grid on current date, independent of daily/weekly display
748 require-timed show grid only if at least on item has a time specification
749
750 The second item is a string which will be places behing the grid time.
751
752 The third item is a list of integers, indicating the times that should have
753 a grid line."
754 :group 'org-agenda
755 :type
756 '(list
757 (set :greedy t :tag "Grid Display Options"
758 (const :tag "Show grid in single day agenda display" daily)
759 (const :tag "Show grid in weekly agenda display" weekly)
760 (const :tag "Always show grid for today" today)
761 (const :tag "Show grid only if any timed entries are present"
762 require-timed)
763 (const :tag "Skip grid times already present in an entry"
764 remove-match))
765 (string :tag "Grid String")
766 (repeat :tag "Grid Times" (integer :tag "Time"))))
767
768 (defcustom org-agenda-remove-times-when-in-prefix t
769 "Non-nil means, remove duplicate time specifications in agenda items.
770 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
771 time-of-day specification in a headline or diary entry is extracted and
772 placed into the prefix. If this option is non-nil, the original specification
773 \(a timestamp or -range, or just a plain time(range) specification like
774 11:30-4pm) will be removed for agenda display. This makes the agenda less
775 cluttered.
776 The option can be t or nil. It may also be the symbol `beg', indicating
777 that the time should only be removed what it is located at the beginning of
778 the headline/diary entry."
779 :group 'org-agenda
780 :type '(choice
781 (const :tag "Always" t)
782 (const :tag "Never" nil)
783 (const :tag "When at beginning of entry" beg)))
784
785 (defcustom org-sort-agenda-notime-is-late t
786 "Non-nil means, items without time are considered late.
787 This is only relevant for sorting. When t, items which have no explicit
788 time like 15:30 will be considered as 24:01, i.e. later than any items which
789 do have a time. When nil, the default time is before 0:00. You can use this
790 option to decide if the schedule for today should come before or after timeless
791 agenda entries."
792 :group 'org-agenda
793 :type 'boolean)
794
795 (defgroup org-structure nil
796 "Options concerning structure editing in Org-mode."
797 :tag "Org Structure"
798 :group 'org)
799
800 (defcustom org-cycle-include-plain-lists nil
801 "Non-nil means, include plain lists into visibility cycling.
802 This means that during cycling, plain list items will *temporarily* be
803 interpreted as outline headlines with a level given by 1000+i where i is the
804 indentation of the bullet. In all other operations, plain list items are
805 not seen as headlines. For example, you cannot assign a TODO keyword to
806 such an item."
807 :group 'org-structure
808 :type 'boolean)
809
810 (defcustom org-cycle-emulate-tab t
811 "Where should `org-cycle' emulate TAB.
812 nil Never
813 white Only in completely white lines
814 t Everywhere except in headlines"
815 :group 'org-structure
816 :type '(choice (const :tag "Never" nil)
817 (const :tag "Only in completely white lines" white)
818 (const :tag "Everywhere except in headlines" t)
819 ))
820
821 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
822 "Hook that is run after `org-cycle' has changed the buffer visibility.
823 The function(s) in this hook must accept a single argument which indicates
824 the new state that was set by the most recent `org-cycle' command. The
825 argument is a symbol. After a global state change, it can have the values
826 `overview', `content', or `all'. After a local state change, it can have
827 the values `folded', `children', or `subtree'."
828 :group 'org-structure
829 :type 'hook)
830
831 (defcustom org-highlight-sparse-tree-matches t
832 "Non-nil means, highlight all matches that define a sparse tree.
833 The highlights will automatically disappear the next time the buffer is
834 changed by an edit command."
835 :group 'org-structure
836 :type 'boolean)
837
838 (defcustom org-show-hierarchy-above t
839 "Non-nil means, show full hierarchy when showing a spot in the tree.
840 Turning this off makes sparse trees more compact, but also less clear."
841 :group 'org-structure
842 :type 'boolean)
843
844 (defcustom org-show-following-heading t
845 "Non-nil means, show heading following match in `org-occur'.
846 When doing an `org-occur' it is useful to show the headline which
847 follows the match, even if they do not match the regexp. This makes it
848 easier to edit directly inside the sparse tree. However, if you use
849 org-occur mainly as an overview, the following headlines are
850 unnecessary clutter."
851 :group 'org-structure
852 :type 'boolean)
853
854 (defcustom org-occur-hook '(org-first-headline-recenter)
855 "Hook that is run after `org-occur' has constructed a sparse tree.
856 This can be used to recenter the window to show as much of the structure
857 as possible."
858 :group 'org-structure
859 :type 'hook)
860
861 (defcustom org-level-color-stars-only nil
862 "Non-nil means fontify only the stars in each headline.
863 When nil, the entire headline is fontified.
864 After changin this, requires restart of Emacs to become effective."
865 :group 'org-structure
866 :type 'boolean)
867
868 (defcustom org-adapt-indentation t
869 "Non-nil means, adapt indentation when promoting and demoting.
870 When this is set and the *entire* text in an entry is indented, the
871 indentation is increased by one space in a demotion command, and
872 decreased by one in a promotion command. If any line in the entry
873 body starts at column 0, indentation is not changed at all."
874 :group 'org-structure
875 :type 'boolean)
876
877 (defcustom org-plain-list-ordered-item-terminator t
878 "The character that makes a line with leading number an ordered list item.
879 Valid values are ?. and ?\). To get both terminators, use t. While
880 ?. may look nicer, it creates the danger that a line with leading
881 number may be incorrectly interpreted as an item. ?\) therefore is
882 the safe choice."
883 :group 'org-structure
884 :type '(choice (const :tag "dot like in \"2.\"" ?.)
885 (const :tag "paren like in \"2)\"" ?\))
886 (const :tab "both" t)))
887
888 (defcustom org-auto-renumber-ordered-lists t
889 "Non-nil means, automatically renumber ordered plain lists.
890 Renumbering happens when the sequence have been changed with
891 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
892 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
893 :group 'org-structure
894 :type 'boolean)
895
896 (defcustom org-enable-fixed-width-editor t
897 "Non-nil means, lines starting with \":\" are treated as fixed-width.
898 This currently only means, they are never auto-wrapped.
899 When nil, such lines will be treated like ordinary lines.
900 See also the QUOTE keyword."
901 :group 'org-structure
902 :type 'boolean)
903
904 (defcustom org-archive-location "%s_archive::"
905 "The location where subtrees should be archived.
906 This string consists of two parts, separated by a double-colon.
907
908 The first part is a file name - when omitted, archiving happens in the same
909 file. %s will be replaced by the current file name (without directory part).
910 Archiving to a different file is useful to keep archived entries from
911 contributing to the Org-mode Agenda.
912
913 The part after the double colon is a headline. The archived entries will be
914 filed under that headline. When omitted, the subtrees are simply filed away
915 at the end of the file, as top-level entries.
916
917 Here are a few examples:
918 \"%s_archive::\"
919 If the current file is Projects.org, archive in file
920 Projects.org_archive, as top-level trees. This is the default.
921
922 \"::* Archived Tasks\"
923 Archive in the current file, under the top-level headline
924 \"* Archived Tasks\".
925
926 \"~/org/archive.org::\"
927 Archive in file ~/org/archive.org (absolute path), as top-level trees.
928
929 \"basement::** Finished Tasks\"
930 Archive in file ./basement (relative path), as level 3 trees
931 below the level 2 heading \"** Finished Tasks\".
932
933 You may set this option on a per-file basis by adding to the buffer a
934 line like
935
936 #+ARCHIVE: basement::** Finished Tasks"
937 :group 'org-structure
938 :type 'string)
939
940 (defcustom org-archive-mark-done t
941 "Non-nil means, mark archived entries as DONE."
942 :group 'org-structure
943 :type 'boolean)
944
945 (defcustom org-archive-stamp-time t
946 "Non-nil means, add a time stamp to archived entries.
947 The time stamp will be added directly after the TODO state keyword in the
948 first line, so it is probably best to use this in combinations with
949 `org-archive-mark-done'."
950 :group 'org-structure
951 :type 'boolean)
952
953 (defgroup org-link nil
954 "Options concerning links in Org-mode."
955 :tag "Org Link"
956 :group 'org)
957
958 (defcustom org-link-format "<%s>"
959 "Default format for linkes in the buffer.
960 This is a format string for printf, %s will be replaced by the link text.
961 If you want to make sure that your link is always properly terminated,
962 include angle brackets into this format, like \"<%s>\". Some people also
963 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
964 :group 'org-link
965 :type '(choice
966 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
967 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
968 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
969 (string :tag "Other" :value "<%s>")))
970
971 (defcustom org-allow-space-in-links t
972 "Non-nil means, file names in links may contain space characters.
973 When nil, it becomes possible to put several links into a line.
974 Note that in tables, a link never extends accross fields, so in a table
975 it is always possible to put several links into a line.
976 Changing this varable requires a re-launch of Emacs of become effective."
977 :group 'org-link
978 :type 'boolean)
979
980 (defcustom org-context-in-file-links t
981 "Non-nil means, file links from `org-store-link' contain context.
982 The line number will be added to the file name with :: as separator and
983 used to find the context when the link is activated by the command
984 `org-open-at-point'.
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-keep-stored-link-after-insertion nil
991 "Non-nil means, keep link in list for entire session.
992
993 The command `org-store-link' adds a link pointing to the current
994 location to an internal list. These links accumulate during a session.
995 The command `org-insert-link' can be used to insert links into any
996 Org-mode file (offering completion for all stored links). When this
997 option is nil, every link which has been inserted once using \\[org-insert-link]
998 will be removed from the list, to make completing the unused links
999 more efficient."
1000 :group 'org-link
1001 :type 'boolean)
1002
1003 (defcustom org-link-frame-setup
1004 '((vm . vm-visit-folder-other-frame)
1005 (gnus . gnus-other-frame)
1006 (file . find-file-other-window))
1007 "Setup the frame configuration for following links.
1008 When following a link with Emacs, it may often be useful to display
1009 this link in another window or frame. This variable can be used to
1010 set this up for the different types of links.
1011 For VM, use any of
1012 `vm-visit-folder'
1013 `vm-visit-folder-other-frame'
1014 For Gnus, use any of
1015 `gnus'
1016 `gnus-other-frame'
1017 For FILE, use any of
1018 `find-file'
1019 `find-file-other-window'
1020 `find-file-other-frame'
1021 For the calendar, use the variable `calendar-setup'.
1022 For BBDB, it is currently only possible to display the matches in
1023 another window."
1024 :group 'org-link
1025 :type '(list
1026 (cons (const vm)
1027 (choice
1028 (const vm-visit-folder)
1029 (const vm-visit-folder-other-window)
1030 (const vm-visit-folder-other-frame)))
1031 (cons (const gnus)
1032 (choice
1033 (const gnus)
1034 (const gnus-other-frame)))
1035 (cons (const file)
1036 (choice
1037 (const find-file)
1038 (const find-file-other-window)
1039 (const find-file-other-frame)))))
1040
1041 (defcustom org-usenet-links-prefer-google nil
1042 "Non-nil means, `org-store-link' will create web links to google groups.
1043 When nil, Gnus will be used for such links.
1044 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1045 negates this setting for the duration of the command."
1046 :group 'org-link
1047 :type 'boolean)
1048
1049 (defcustom org-open-non-existing-files nil
1050 "Non-nil means, `org-open-file' will open non-existing file.
1051 When nil, an error will be generated."
1052 :group 'org-link
1053 :type 'boolean)
1054
1055 (defcustom org-confirm-shell-links t
1056 "Non-nil means, ask for confirmation before executing shell links.
1057 The default is true, to keep new users from shooting into their own foot."
1058 :group 'org-link
1059 :type 'boolean)
1060
1061 (defconst org-file-apps-defaults-gnu
1062 '((t . emacs)
1063 ("jpg" . "xv %s")
1064 ("gif" . "xv %s")
1065 ("ppm" . "xv %s")
1066 ("pgm" . "xv %s")
1067 ("pbm" . "xv %s")
1068 ("tif" . "xv %s")
1069 ("png" . "xv %s")
1070 ("ps" . "gv %s")
1071 ("ps.gz" . "gv %s")
1072 ("eps" . "gv %s")
1073 ("eps.gz" . "gv %s")
1074 ("dvi" . "xdvi %s")
1075 ("mpeg" . "plaympeg %s")
1076 ("mp3" . "plaympeg %s")
1077 ("fig" . "xfig %s")
1078 ("pdf" . "acroread %s")
1079 ("doc" . "soffice %s")
1080 ("ppt" . "soffice %s")
1081 ("pps" . "soffice %s")
1082 ("html" . "netscape -remote openURL(%s,new-window)")
1083 ("htm" . "netscape -remote openURL(%s,new-window)")
1084 ("xs" . "soffice %s"))
1085 "Default file applications on a UNIX/LINUX system.
1086 See `org-file-apps'.")
1087
1088 (defconst org-file-apps-defaults-macosx
1089 '((t . "open %s")
1090 ("ps" . "gv %s")
1091 ("ps.gz" . "gv %s")
1092 ("eps" . "gv %s")
1093 ("eps.gz" . "gv %s")
1094 ("dvi" . "xdvi %s")
1095 ("fig" . "xfig %s"))
1096 "Default file applications on a MacOS X system.
1097 The system \"open\" is known as a default, but we use X11 applications
1098 for some files for which the OS does not have a good default.
1099 See `org-file-apps'.")
1100
1101 (defconst org-file-apps-defaults-windowsnt
1102 '((t . (w32-shell-execute "open" file)))
1103 "Default file applications on a Windows NT system.
1104 The system \"open\" is used for most files.
1105 See `org-file-apps'.")
1106
1107 (defcustom org-file-apps
1108 '(
1109 ("txt" . emacs)
1110 ("tex" . emacs)
1111 ("ltx" . emacs)
1112 ("org" . emacs)
1113 ("el" . emacs)
1114 )
1115 "External applications for opening `file:path' items in a document.
1116 Org-mode uses system defaults for different file types, but
1117 you can use this variable to set the application for a given file
1118 extension. The entries in this list are cons cells with a file extension
1119 and the corresponding command. Possible values for the command are:
1120 `emacs' The file will be visited by the current Emacs process.
1121 `default' Use the default application for this file type.
1122 string A command to be executed by a shell; %s will be replaced
1123 by the path to the file.
1124 sexp A Lisp form which will be evaluated. The file path will
1125 be available in the Lisp variable `file'.
1126 For more examples, see the system specific constants
1127 `org-file-apps-defaults-macosx'
1128 `org-file-apps-defaults-windowsnt'
1129 `org-file-apps-defaults-gnu'."
1130 :group 'org-link
1131 :type '(repeat
1132 (cons (string :tag "Extension")
1133 (choice :value ""
1134 (const :tag "Visit with Emacs" 'emacs)
1135 (const :tag "Use system default" 'default)
1136 (string :tag "Command")
1137 (sexp :tag "Lisp form")))))
1138
1139
1140 (defgroup org-remember nil
1141 "Options concerning interaction with remember.el."
1142 :tag "Org Remember"
1143 :group 'org)
1144
1145 (defcustom org-directory "~/org"
1146 "Directory with org files.
1147 This directory will be used as default to prompt for org files.
1148 Used by the hooks for remember.el."
1149 :group 'org-remember
1150 :type 'directory)
1151
1152 (defcustom org-default-notes-file "~/.notes"
1153 "Default target for storing notes.
1154 Used by the hooks for remember.el. This can be a string, or nil to mean
1155 the value of `remember-data-file'."
1156 :group 'org-remember
1157 :type '(choice
1158 (const :tag "Default from remember-data-file" nil)
1159 file))
1160
1161 (defcustom org-reverse-note-order nil
1162 "Non-nil means, store new notes at the beginning of a file or entry.
1163 When nil, new notes will be filed to the end of a file or entry."
1164 :group 'org-remember
1165 :type '(choice
1166 (const :tag "Reverse always" t)
1167 (const :tag "Reverse never" nil)
1168 (repeat :tag "By file name regexp"
1169 (cons regexp boolean))))
1170
1171 (defgroup org-table nil
1172 "Options concerning tables in Org-mode."
1173 :tag "Org Table"
1174 :group 'org)
1175
1176 (defcustom org-enable-table-editor 'optimized
1177 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1178 When nil, such lines will be treated like ordinary lines.
1179
1180 When equal to the symbol `optimized', the table editor will be optimized to
1181 do the following
1182 - Use automatic overwrite mode in front of whitespace in table fields.
1183 This make the structure of the table stay in tact as long as the edited
1184 field does not exceed the column width.
1185 - Minimize the number of realigns. Normally, the table is aligned each time
1186 TAB or RET are pressed to move to another field. With optimization this
1187 happens only if changes to a field might have changed the column width.
1188 Optimization requires replacing the functions `self-insert-command',
1189 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1190 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1191 very good at guessing when a re-align will be necessary, but you can always
1192 force one with \\[org-ctrl-c-ctrl-c].
1193
1194 If you would like to use the optimized version in Org-mode, but the
1195 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1196
1197 This variable can be used to turn on and off the table editor during a session,
1198 but in order to toggle optimization, a restart is required.
1199
1200 See also the variable `org-table-auto-blank-field'."
1201 :group 'org-table
1202 :type '(choice
1203 (const :tag "off" nil)
1204 (const :tag "on" t)
1205 (const :tag "on, optimized" optimized)))
1206
1207 ;; FIXME: We could have a third option which makes it jump only over the first
1208 ;; hline in a table.
1209 (defcustom org-table-tab-jumps-over-hlines t
1210 "Non-nil means, tab in the last column of a table with jump over a hline.
1211 If a horizontal separator line is following the current line,
1212 `org-table-next-field' can either create a new row before that line, or jump
1213 over the line. When this option is nil, a new line will be created before
1214 this line."
1215 :group 'org-table
1216 :type 'boolean)
1217
1218 (defcustom org-table-auto-blank-field t
1219 "Non-nil means, automatically blank table field when starting to type into it.
1220 This only happens when typing immediately after a field motion
1221 command (TAB, S-TAB or RET).
1222 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1223 :group 'org-table
1224 :type 'boolean)
1225
1226 (defcustom org-table-default-size "5x2"
1227 "The default size for newly created tables, Columns x Rows."
1228 :group 'org-table
1229 :type 'string)
1230
1231 (defcustom org-table-automatic-realign t
1232 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1233 When nil, aligning is only done with \\[org-table-align], or after column
1234 removal/insertion."
1235 :group 'org-table
1236 :type 'boolean)
1237
1238 (defcustom org-table-spaces-around-separators '(1 . 1)
1239 "The number of spaces to be placed before and after separators."
1240 :group 'org-table
1241 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1242
1243 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1244 "The number of spaces to be placed before and after separators.
1245 This option applies when the column separators have been made invisible."
1246 :group 'org-table
1247 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1248
1249 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1250 "Regular expression for recognizing numbers in table columns.
1251 If a table column contains mostly numbers, it will be aligned to the
1252 right. If not, it will be aligned to the left.
1253
1254 The default value of this option is a regular expression which allows
1255 anything which looks remotely like a number as used in scientific
1256 context. For example, all of the following will be considered a
1257 number:
1258 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1259
1260 Other options offered by the customize interface are more restrictive."
1261 :group 'org-table
1262 :type '(choice
1263 (const :tag "Positive Integers"
1264 "^[0-9]+$")
1265 (const :tag "Integers"
1266 "^[-+]?[0-9]+$")
1267 (const :tag "Floating Point Numbers"
1268 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1269 (const :tag "Floating Point Number or Integer"
1270 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1271 (const :tag "Exponential, Floating point, Integer"
1272 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1273 (const :tag "Very General Number-Like"
1274 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1275 (string :tag "Regexp:")))
1276
1277 (defcustom org-table-number-fraction 0.5
1278 "Fraction of numbers in a column required to make the column align right.
1279 In a column all non-white fields are considered. If at least this
1280 fraction of fields is matched by `org-table-number-fraction',
1281 alignment to the right border applies."
1282 :group 'org-table
1283 :type 'number)
1284
1285 (defcustom org-export-highlight-first-table-line t
1286 "Non-nil means, highlight the first table line.
1287 In HTML export, this means use <th> instead of <td>.
1288 In tables created with table.el, this applies to the first table line.
1289 In Org-mode tables, all lines before the first horizontal separator
1290 line will be formatted with <th> tags."
1291 :group 'org-table
1292 :type 'boolean)
1293
1294 (defcustom org-table-tab-recognizes-table.el t
1295 "Non-nil means, TAB will automatically notice a table.el table.
1296 When it sees such a table, it moves point into it and - if necessary -
1297 calls `table-recognize-table'."
1298 :group 'org-table
1299 :type 'boolean)
1300
1301 (defgroup org-table-calculation nil
1302 "Options concerning tables in Org-mode."
1303 :tag "Org Table Calculation"
1304 :group 'org)
1305
1306 (defcustom org-table-copy-increment t
1307 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1308 :group 'org-table-calculation
1309 :type 'boolean)
1310
1311 (defcustom org-calc-default-modes
1312 '(calc-internal-prec 12
1313 calc-float-format (float 5)
1314 calc-angle-mode deg
1315 calc-prefer-frac nil
1316 calc-symbolic-mode nil
1317 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1318 calc-display-working-message t
1319 )
1320 "List with Calc mode settings for use in calc-eval for table formulas.
1321 The list must contain alternating symbols (calc modes variables and values.
1322 Don't remove any of the default settings, just change the values. Org-mode
1323 relies on the variables to be present in the list."
1324 :group 'org-table-calculation
1325 :type 'plist)
1326
1327 (defcustom org-table-formula-evaluate-inline t
1328 "Non-nil means, TAB and RET evaluate a formula in current table field.
1329 If the current field starts with an equal sign, it is assumed to be a formula
1330 which should be evaluated as described in the manual and in the documentation
1331 string of the command `org-table-eval-formula'. This feature requires the
1332 Emacs calc package.
1333 When this variable is nil, formula calculation is only available through
1334 the command \\[org-table-eval-formula]."
1335 :group 'org-table-calculation
1336 :type 'boolean)
1337
1338
1339 (defcustom org-table-formula-use-constants t
1340 "Non-nil means, interpret constants in formulas in tables.
1341 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1342 by the value given in `org-table-formula-constants', or by a value obtained
1343 from the `constants.el' package."
1344 :group 'org-table-calculation
1345 :type 'boolean)
1346
1347 (defcustom org-table-formula-constants nil
1348 "Alist with constant names and values, for use in table formulas.
1349 The car of each element is a name of a constant, without the `$' before it.
1350 The cdr is the value as a string. For example, if you'd like to use the
1351 speed of light in a formula, you would configure
1352
1353 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1354
1355 and then use it in an equation like `$1*$c'."
1356 :group 'org-table-calculation
1357 :type '(repeat
1358 (cons (string :tag "name")
1359 (string :tag "value"))))
1360
1361 (defcustom org-table-formula-numbers-only nil
1362 "Non-nil means, calculate only with numbers in table formulas.
1363 Then all input fields will be converted to a number, and the result
1364 must also be a number. When nil, calc's full potential is available
1365 in table calculations, including symbolics etc."
1366 :group 'org-table-calculation
1367 :type 'boolean)
1368
1369 (defcustom org-table-allow-automatic-line-recalculation t
1370 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1371 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1372 :group 'org-table-calculation
1373 :type 'boolean)
1374
1375 (defgroup org-export nil
1376 "Options for exporting org-listings."
1377 :tag "Org Export"
1378 :group 'org)
1379
1380 (defcustom org-export-language-setup
1381 '(("en" "Author" "Date" "Table of Contents")
1382 ("da" "Ophavsmand" "Dato" "Indhold")
1383 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1384 ("es" "Autor" "Fecha" "\xccndice")
1385 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1386 ("it" "Autore" "Data" "Indice")
1387 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1388 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1389 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1390 "Terms used in export text, translated to different languages.
1391 Use the variable `org-export-default-language' to set the language,
1392 or use the +OPTION lines for a per-file setting."
1393 :group 'org-export
1394 :type '(repeat
1395 (list
1396 (string :tag "HTML language tag")
1397 (string :tag "Author")
1398 (string :tag "Date")
1399 (string :tag "Table of Contents"))))
1400
1401 (defcustom org-export-default-language "en"
1402 "The default language of HTML export, as a string.
1403 This should have an association in `org-export-language-setup'."
1404 :group 'org-export
1405 :type 'string)
1406
1407 (defcustom org-export-html-style
1408 "<style type=\"text/css\">
1409 html {
1410 font-family: Times, serif;
1411 font-size: 12pt;
1412 }
1413 .title { text-align: center; }
1414 .todo, .deadline { color: red; }
1415 .done { color: green; }
1416 pre {
1417 border: 1pt solid #AEBDCC;
1418 background-color: #F3F5F7;
1419 padding: 5pt;
1420 font-family: courier, monospace;
1421 }
1422 table { border-collapse: collapse; }
1423 td, th {
1424 vertical-align: top;
1425 border: 1pt solid #ADB9CC;
1426 }
1427 </style>"
1428 "The default style specification for exported HTML files.
1429 Since there are different ways of setting style information, this variable
1430 needs to contain the full HTML structure to provide a style, including the
1431 surrounding HTML tags. The style specifications should include definiitons
1432 for new classes todo, done, title, and deadline. For example, legal values
1433 would be.
1434
1435 <style type=\"text/css\">
1436 p {font-weight: normal; color: gray; }
1437 h1 {color: black; }
1438 .title { text-align: center; }
1439 .todo, .deadline { color: red; }
1440 .done { color: green; }
1441 </style>
1442
1443 or, if you want to keep the style in a file,
1444
1445 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1446
1447 As the value of this option simply gets inserted into the HTML <head> header,
1448 you can \"misuse\" it to add arbitrary text to the header."
1449 :group 'org-export
1450 :type 'string)
1451
1452 (defcustom org-export-headline-levels 3
1453 "The last level which is still exported as a headline.
1454 Inferior levels will produce itemize lists when exported.
1455 Note that a numeric prefix argument to an exporter function overrides
1456 this setting.
1457
1458 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1459 :group 'org-export
1460 :type 'number)
1461
1462 (defcustom org-export-with-section-numbers t
1463 "Non-nil means, add section numbers to headlines when exporting.
1464
1465 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1466 :group 'org-export
1467 :type 'boolean)
1468
1469 (defcustom org-export-with-toc t
1470 "Non-nil means, create a table of contents in exported files.
1471 The TOC contains headlines with levels up to`org-export-headline-levels'.
1472
1473 Headlines which contain any TODO items will be marked with \"(*)\" in
1474 ASCII export, and with red color in HTML output.
1475
1476 In HTML output, the TOC will be clickable.
1477
1478 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1479 :group 'org-export
1480 :type 'boolean)
1481
1482 (defcustom org-export-plain-list-max-depth 20
1483 "Maximum depth of hand-formatted lists in HTML export.
1484
1485 Org-mode parses hand-formatted enumeration and bullet lists and
1486 transforms them to HTML open export. Different indentation of the
1487 bullet or number indicates different list nesting levels. To avoid
1488 confusion, only a single level is allowed by default. When this is
1489 larger than 1, deeper indentation leads to deeper list nesting. For
1490 example, the default value of 3 allows the following list to be
1491 formatted correctly in HTML:
1492
1493 * Fruit
1494 - Apple
1495 - Banana
1496 1. from Africa
1497 2. from South America
1498 - Pineapple
1499 * Bread
1500 * Dairy products"
1501 :group 'org-export
1502 :type 'integer)
1503
1504 (defcustom org-export-preserve-breaks nil
1505 "Non-nil means, preserve all line breaks when exporting.
1506 Normally, in HTML output paragraphs will be reformatted. In ASCII
1507 export, line breaks will always be preserved, regardless of this variable.
1508
1509 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1510 :group 'org-export
1511 :type 'boolean)
1512
1513 (defcustom org-export-html-inline-images t
1514 "Non-nil means, inline images into exported HTML pages.
1515 The link will still be to the original location of the image file.
1516 So if you are moving the page, lets say to your public HTML site,
1517 you will have to move the image and maybe change the link."
1518 :group 'org-export
1519 :type 'boolean)
1520
1521 (defcustom org-export-html-expand t
1522 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1523 When nil, these tags will be exported as plain text and therefore
1524 not be interpreted by a browser.
1525
1526 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1527 :group 'org-export
1528 :type 'boolean)
1529
1530 (defcustom org-export-with-fixed-width t
1531 "Non-nil means, lines starting with \":\" will be in fixed width font.
1532 This can be used to have pre-formatted text, fragments of code etc. For
1533 example
1534 : ;; Some Lisp examples
1535 : (while (defc cnt)
1536 : (ding))
1537 will be looking just like this in also HTML. In ASCII export, this option
1538 has no effect.
1539
1540 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1541 :group 'org-export
1542 :type 'boolean)
1543
1544 (defcustom org-export-with-tables t
1545 "If non-nil, lines starting with \"|\" define a table.
1546 For example:
1547
1548 | Name | Address | Birthday |
1549 |-------------+----------+-----------|
1550 | Arthur Dent | England | 29.2.2100 |
1551
1552 In ASCII export, this option has no effect.
1553
1554 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1555 :group 'org-export
1556 :type 'boolean)
1557
1558 (defcustom org-export-prefer-native-exporter-for-tables nil
1559 "Non-nil means, always export tables created with table.el natively.
1560 Natively means, use the HTML code generator in table.el.
1561 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1562 the table does not use row- or column-spanning). This has the
1563 advantage, that the automatic HTML conversions for math symbols and
1564 sub/superscripts can be applied. Org-mode's HTML generator is also
1565 much faster."
1566 :group 'org-export
1567 :type 'boolean)
1568
1569 (defcustom org-export-html-table-tag
1570 "<table border=1 cellspacing=0 cellpadding=6>"
1571 "The HTML tag used to start a table.
1572 This must be a <table> tag, but you may change the options like
1573 borders and spacing."
1574 :group 'org-export
1575 :type 'string)
1576
1577 (defcustom org-export-with-emphasize t
1578 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1579 If the export target supports emphasizing text, the word will be
1580 typeset in bold, italic, or underlined, respectively. Works only for
1581 single words, but you can say: I *really* *mean* *this*.
1582 In ASCII export, this option has no effect.
1583
1584 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1585 :group 'org-export
1586 :type 'boolean)
1587
1588 (defcustom org-match-sexp-depth 3
1589 "Number of stacked braces for sub/superscript matching.
1590 This has to be set before loading org.el to be effective."
1591 :group 'org-export
1592 :type 'integer)
1593
1594 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1595 (defcustom org-export-with-sub-superscripts t
1596 "Non-nil means, interpret \"_\" and \"^\" for export.
1597 When this option is turned on, you can use TeX-like syntax for sub- and
1598 superscripts. Several characters after \"_\" or \"^\" will be
1599 considered as a single item - so grouping with {} is normally not
1600 needed. For example, the following things will be parsed as single
1601 sub- or superscripts.
1602
1603 10^24 or 10^tau several digits will be considered 1 item
1604 10^-12 or 10^-tau a leading sign with digits or a word
1605 x^2-y^3 will be read as x^2 - y^3, because items are
1606 terminated by almost any nonword/nondigit char.
1607 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1608
1609 Still, ambiguity is possible - so when in doubt use {} to enclose the
1610 sub/superscript.
1611 In ASCII export, this option has no effect.
1612
1613 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1614 :group 'org-export
1615 :type 'boolean)
1616
1617 (defcustom org-export-with-TeX-macros t
1618 "Non-nil means, interpret simple TeX-like macros when exporting.
1619 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1620 No only real TeX macros will work here, but the standard HTML entities
1621 for math can be used as macro names as well. For a list of supported
1622 names in HTML export, see the constant `org-html-entities'.
1623 In ASCII export, this option has no effect.
1624
1625 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1626 :group 'org-export
1627 :type 'boolean)
1628
1629 (defcustom org-export-html-with-timestamp nil
1630 "If non-nil, write `org-export-html-html-helper-timestamp'
1631 into the exported html text. Otherwise, the buffer will just be saved
1632 to a file."
1633 :group 'org-export
1634 :type 'boolean)
1635
1636 (defcustom org-export-html-html-helper-timestamp
1637 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1638 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1639 :group 'org-export
1640 :type 'string)
1641
1642 (defcustom org-export-ascii-show-new-buffer t
1643 "Non-nil means, popup buffer containing the exported ASCII text.
1644 Otherwise the buffer will just be saved to a file and stay hidden."
1645 :group 'org-export
1646 :type 'boolean)
1647
1648 (defcustom org-export-html-show-new-buffer nil
1649 "Non-nil means, popup buffer containing the exported html text.
1650 Otherwise, the buffer will just be saved to a file and stay hidden."
1651 :group 'org-export
1652 :type 'boolean)
1653
1654 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1655 "The file name for the iCalendar file covering all agenda files.
1656 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1657 :group 'org-export
1658 :type 'file)
1659
1660 (defcustom org-icalendar-include-todo nil
1661 "Non-nil means, export to iCalendar files should also cover TODO items."
1662 :group 'org-export
1663 :type 'boolean)
1664
1665 (defcustom org-icalendar-combined-name "OrgMode"
1666 "Calendar name for the combined iCalendar representing all agenda files."
1667 :group 'org-export
1668 :type 'string)
1669
1670 (defgroup org-faces nil
1671 "Faces for highlighting in Org-mode."
1672 :tag "Org Faces"
1673 :group 'org)
1674
1675 (defface org-level-1 ;; font-lock-function-name-face
1676 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1677 (((class color) (background light)) (:foreground "Blue"))
1678 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1679 (t (:inverse-video t :bold t)))
1680 "Face used for level 1 headlines."
1681 :group 'org-faces)
1682
1683 (defface org-level-2 ;; font-lock-variable-name-face
1684 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1685 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1686 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1687 (t (:bold t :italic t)))
1688 "Face used for level 2 headlines."
1689 :group 'org-faces)
1690
1691 (defface org-level-3 ;; font-lock-keyword-face
1692 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1693 (((class color) (background light)) (:foreground "Purple"))
1694 (((class color) (background dark)) (:foreground "Cyan"))
1695 (t (:bold t)))
1696 "Face used for level 3 headlines."
1697 :group 'org-faces)
1698
1699 (defface org-level-4 ;; font-lock-comment-face
1700 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1701 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1702 (((class color) (background light)) (:foreground "Firebrick"))
1703 (((class color) (background dark)) (:foreground "chocolate1"))
1704 (t (:bold t :italic t)))
1705 "Face used for level 4 headlines."
1706 :group 'org-faces)
1707
1708 (defface org-level-5 ;; font-lock-type-face
1709 '((((type tty) (class color)) (:foreground "green"))
1710 (((class color) (background light)) (:foreground "ForestGreen"))
1711 (((class color) (background dark)) (:foreground "PaleGreen"))
1712 (t (:bold t :underline t)))
1713 "Face used for level 5 headlines."
1714 :group 'org-faces)
1715
1716 (defface org-level-6 ;; font-lock-constant-face
1717 '((((type tty) (class color)) (:foreground "magenta"))
1718 (((class color) (background light)) (:foreground "CadetBlue"))
1719 (((class color) (background dark)) (:foreground "Aquamarine"))
1720 (t (:bold t :underline t)))
1721 "Face used for level 6 headlines."
1722 :group 'org-faces)
1723
1724 (defface org-level-7 ;; font-lock-builtin-face
1725 '((((type tty) (class color)) (:foreground "blue" :weight light))
1726 (((class color) (background light)) (:foreground "Orchid"))
1727 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1728 (t (:bold t)))
1729 "Face used for level 7 headlines."
1730 :group 'org-faces)
1731
1732 (defface org-level-8 ;; font-lock-string-face
1733 '((((type tty) (class color)) (:foreground "green"))
1734 (((class color) (background light)) (:foreground "RosyBrown"))
1735 (((class color) (background dark)) (:foreground "LightSalmon"))
1736 (t (:italic t)))
1737 "Face used for level 8 headlines."
1738 :group 'org-faces)
1739
1740 (defface org-special-keyword ;; font-lock-string-face
1741 '((((type tty) (class color)) (:foreground "green"))
1742 (((class color) (background light)) (:foreground "RosyBrown"))
1743 (((class color) (background dark)) (:foreground "LightSalmon"))
1744 (t (:italic t)))
1745 "Face used for level 8 headlines."
1746 :group 'org-faces)
1747
1748 (defface org-warning ;; font-lock-warning-face
1749 '((((type tty) (class color)) (:foreground "red"))
1750 (((class color) (background light)) (:foreground "Red" :bold t))
1751 (((class color) (background dark)) (:foreground "Red1" :bold t))
1752 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1753 (t (:inverse-video t :bold t)))
1754 "Face for deadlines and TODO keywords."
1755 :group 'org-faces)
1756
1757 (defcustom org-fontify-done-headline nil
1758 "Non-nil means, change the face of a headline if it is marked DONE.
1759 Normally, only the TODO/DONE keyword indicates the state of a headline.
1760 When this is non-nil, the headline after the keyword is set to the
1761 `org-headline-done' as an additional indication."
1762 :group 'org-faces
1763 :type 'boolean)
1764
1765 (defface org-headline-done ;; font-lock-string-face
1766 '((((type tty) (class color)) (:foreground "green"))
1767 (((class color) (background light)) (:foreground "RosyBrown"))
1768 (((class color) (background dark)) (:foreground "LightSalmon"))
1769 (t (:italic t)))
1770 "Face used to indicate that a headline is DONE. See also the variable
1771 `org-fontify-done-headline'."
1772 :group 'org-faces)
1773
1774 ;; Inheritance does not yet work for xemacs. So we just copy...
1775
1776 (defface org-deadline-announce
1777 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1778 (((class color) (background light)) (:foreground "Blue"))
1779 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1780 (t (:inverse-video t :bold t)))
1781 "Face for upcoming deadlines."
1782 :group 'org-faces)
1783
1784 (defface org-scheduled-today
1785 '((((type tty) (class color)) (:foreground "green"))
1786 (((class color) (background light)) (:foreground "DarkGreen"))
1787 (((class color) (background dark)) (:foreground "PaleGreen"))
1788 (t (:bold t :underline t)))
1789 "Face for items scheduled for a certain day."
1790 :group 'org-faces)
1791
1792 (defface org-scheduled-previously
1793 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1794 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1795 (((class color) (background light)) (:foreground "Firebrick"))
1796 (((class color) (background dark)) (:foreground "chocolate1"))
1797 (t (:bold t :italic t)))
1798 "Face for items scheduled previously, and not yet done."
1799 :group 'org-faces)
1800
1801 (defface org-formula
1802 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1803 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1804 (((class color) (background light)) (:foreground "Firebrick"))
1805 (((class color) (background dark)) (:foreground "chocolate1"))
1806 (t (:bold t :italic t)))
1807 "Face for items scheduled previously, and not yet done."
1808 :group 'org-faces)
1809
1810 (defface org-link
1811 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1812 (((class color) (background light)) (:foreground "Purple"))
1813 (((class color) (background dark)) (:foreground "Cyan"))
1814 (t (:bold t)))
1815 "Face for links."
1816 :group 'org-faces)
1817
1818 (defface org-done ;; font-lock-type-face
1819 '((((type tty) (class color)) (:foreground "green"))
1820 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1821 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1822 (t (:bold t :underline t)))
1823 "Face used for DONE."
1824 :group 'org-faces)
1825
1826 (defface org-table ;; font-lock-function-name-face
1827 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1828 (((class color) (background light)) (:foreground "Blue"))
1829 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1830 (t (:inverse-video t :bold t)))
1831 "Face used for tables."
1832 :group 'org-faces)
1833
1834 (defface org-time-grid ;; font-lock-variable-name-face
1835 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1836 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1837 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1838 (t (:bold t :italic t)))
1839 "Face used for level 2 headlines."
1840 :group 'org-faces)
1841
1842 (defvar org-level-faces
1843 '(
1844 org-level-1
1845 org-level-2
1846 org-level-3
1847 org-level-4
1848 org-level-5
1849 org-level-6
1850 org-level-7
1851 org-level-8
1852 ))
1853 (defvar org-n-levels (length org-level-faces))
1854
1855 (defun org-set-regexps-and-options ()
1856 "Precompute regular expressions for current buffer."
1857 (when (eq major-mode 'org-mode)
1858 (let ((re (org-make-options-regexp
1859 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1860 "STARTUP" "ARCHIVE")))
1861 (splitre "[ \t]+")
1862 kwds int key value cat arch)
1863 (save-excursion
1864 (save-restriction
1865 (widen)
1866 (goto-char (point-min))
1867 (while (re-search-forward re nil t)
1868 (setq key (match-string 1) value (match-string 2))
1869 (cond
1870 ((equal key "CATEGORY")
1871 (if (string-match "[ \t]+$" value)
1872 (setq value (replace-match "" t t value)))
1873 (setq cat (intern value)))
1874 ((equal key "SEQ_TODO")
1875 (setq int 'sequence
1876 kwds (append kwds (org-split-string value splitre))))
1877 ((equal key "PRI_TODO")
1878 (setq int 'priority
1879 kwds (append kwds (org-split-string value splitre))))
1880 ((equal key "TYP_TODO")
1881 (setq int 'type
1882 kwds (append kwds (org-split-string value splitre))))
1883 ((equal key "STARTUP")
1884 (let ((opts (org-split-string value splitre))
1885 (set '(("fold" org-startup-folded t)
1886 ("nofold" org-startup-folded nil)
1887 ("content" org-startup-folded content)
1888 ("dlcheck" org-startup-with-deadline-check t)
1889 ("nodlcheck" org-startup-with-deadline-check nil)))
1890 l var val)
1891 (while (setq l (assoc (pop opts) set))
1892 (setq var (nth 1 l) val (nth 2 l))
1893 (set (make-local-variable var) val))))
1894 ((equal key "ARCHIVE")
1895 (string-match " *$" value)
1896 (setq arch (replace-match "" t t value))
1897 (remove-text-properties 0 (length arch)
1898 '(face t fontified t) arch)))
1899 )))
1900 (and cat (set (make-local-variable 'org-category) cat))
1901 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1902 (and arch (set (make-local-variable 'org-archive-location) arch))
1903 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1904 ;; Compute the regular expressions and other local variables
1905 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1906 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1907 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1908 (length org-scheduled-string)))
1909 org-done-string
1910 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1911 org-todo-regexp
1912 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1913 "\\|") "\\)\\>")
1914 org-not-done-regexp
1915 (concat "\\<\\("
1916 (mapconcat 'regexp-quote
1917 (nreverse (cdr (reverse org-todo-keywords)))
1918 "\\|")
1919 "\\)\\>")
1920 org-todo-line-regexp
1921 (concat "^\\(\\*+\\)[ \t]*\\("
1922 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1923 "\\)? *\\(.*\\)")
1924 org-nl-done-regexp
1925 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1926 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1927 org-deadline-regexp (concat "\\<" org-deadline-string)
1928 org-deadline-time-regexp
1929 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1930 org-deadline-line-regexp
1931 (concat "\\<\\(" org-deadline-string "\\).*")
1932 org-scheduled-regexp
1933 (concat "\\<" org-scheduled-string)
1934 org-scheduled-time-regexp
1935 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1936 (org-set-font-lock-defaults)))
1937
1938 ;; Tell the compiler about dynamically scoped variables,
1939 ;; and variables from other packages
1940 (eval-when-compile
1941 (defvar zmacs-regions)
1942 (defvar original-date)
1943 (defvar org-transient-mark-mode)
1944 (defvar org-old-auto-fill-inhibit-regexp)
1945 (defvar orgtbl-mode-menu)
1946 (defvar org-html-entities)
1947 (defvar org-goto-start-pos)
1948 (defvar org-cursor-color)
1949 (defvar org-time-was-given)
1950 (defvar org-ts-what)
1951 (defvar mark-active)
1952 (defvar timecnt)
1953 (defvar levels-open)
1954 (defvar title)
1955 (defvar author)
1956 (defvar email)
1957 (defvar text)
1958 (defvar entry)
1959 (defvar date)
1960 (defvar language)
1961 (defvar options)
1962 (defvar ans1)
1963 (defvar ans2)
1964 (defvar starting-day)
1965 (defvar include-all-loc)
1966 (defvar vm-message-pointer)
1967 (defvar vm-folder-directory)
1968 (defvar wl-summary-buffer-elmo-folder)
1969 (defvar wl-summary-buffer-folder-name)
1970 (defvar gnus-group-name)
1971 (defvar gnus-article-current)
1972 (defvar w3m-current-url)
1973 (defvar org-selected-point)
1974 (defvar calendar-mode-map)
1975 (defvar remember-save-after-remembering)
1976 (defvar remember-data-file))
1977
1978
1979 ;;; Define the mode
1980
1981 (defvar org-mode-map (copy-keymap outline-mode-map)
1982 "Keymap for Org-mode.")
1983
1984 (defvar org-struct-menu)
1985 (defvar org-org-menu)
1986 (defvar org-tbl-menu)
1987
1988 ;; We use a before-change function to check if a table might need
1989 ;; an update.
1990 (defvar org-table-may-need-update t
1991 "Indicates of a table might need an update.
1992 This variable is set by `org-before-change-function'. `org-table-align'
1993 sets it back to nil.")
1994 (defvar org-mode-hook nil)
1995 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1996
1997
1998 ;;;###autoload
1999 (define-derived-mode org-mode outline-mode "Org"
2000 "Outline-based notes management and organizer, alias
2001 \"Carstens outline-mode for keeping track of everything.\"
2002
2003 Org-mode develops organizational tasks around a NOTES file which
2004 contains information about projects as plain text. Org-mode is
2005 implemented on top of outline-mode, which is ideal to keep the content
2006 of large files well structured. It supports ToDo items, deadlines and
2007 time stamps, which magically appear in the diary listing of the Emacs
2008 calendar. Tables are easily created with a built-in table editor.
2009 Plain text URL-like links connect to websites, emails (VM), Usenet
2010 messages (Gnus), BBDB entries, and any files related to the project.
2011 For printing and sharing of notes, an Org-mode file (or a part of it)
2012 can be exported as a structured ASCII or HTML file.
2013
2014 The following commands are available:
2015
2016 \\{org-mode-map}"
2017 (easy-menu-add org-org-menu)
2018 (easy-menu-add org-tbl-menu)
2019 (org-install-agenda-files-menu)
2020 (setq outline-regexp "\\*+")
2021 (setq outline-level 'org-outline-level)
2022 (if org-startup-truncated (setq truncate-lines t))
2023 (org-set-regexps-and-options)
2024 (set (make-local-variable 'font-lock-unfontify-region-function)
2025 'org-unfontify-region)
2026 ;; Activate before-change-function
2027 (set (make-local-variable 'org-table-may-need-update) t)
2028 (make-local-hook 'before-change-functions) ;; needed for XEmacs
2029 (add-hook 'before-change-functions 'org-before-change-function nil
2030 'local)
2031 ;; Paragraphs and auto-filling
2032 (org-set-autofill-regexps)
2033 ;; Settings for Calc embedded mode
2034 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2035 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2036 (if (and org-insert-mode-line-in-empty-file
2037 (interactive-p)
2038 (= (point-min) (point-max)))
2039 (insert " -*- mode: org -*-\n\n"))
2040
2041 ;; Get rid of Outline menus, they are not needed
2042 ;; Need to do this here because define-derived-mode sets up
2043 ;; the keymap so late.
2044 (if org-xemacs-p
2045 (progn
2046 (delete-menu-item '("Headings"))
2047 (delete-menu-item '("Show"))
2048 (delete-menu-item '("Hide"))
2049 (set-menubar-dirty-flag))
2050 (define-key org-mode-map [menu-bar headings] 'undefined)
2051 (define-key org-mode-map [menu-bar hide] 'undefined)
2052 (define-key org-mode-map [menu-bar show] 'undefined))
2053
2054 (unless org-inhibit-startup
2055 (if org-startup-with-deadline-check
2056 (call-interactively 'org-check-deadlines)
2057 (cond
2058 ((eq org-startup-folded t)
2059 (org-cycle '(4)))
2060 ((eq org-startup-folded 'content)
2061 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2062 (org-cycle '(4)) (org-cycle '(4))))))))
2063
2064 (defsubst org-current-line (&optional pos)
2065 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2066
2067 ;;; Font-Lock stuff
2068
2069 (defvar org-mouse-map (make-sparse-keymap))
2070 (define-key org-mouse-map
2071 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2072 (define-key org-mouse-map
2073 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2074
2075 (require 'font-lock)
2076
2077 (defconst org-non-link-chars "\t\n\r|<>\000")
2078 (defconst org-link-regexp
2079 (if org-allow-space-in-links
2080 (concat
2081 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2082 (concat
2083 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2084 )
2085 "Regular expression for matching links.")
2086 (defconst org-link-maybe-angles-regexp
2087 (concat "<?\\(" org-link-regexp "\\)>?")
2088 "Matches a link and optionally surrounding angle brackets.")
2089 (defconst org-protected-link-regexp
2090 (concat "\000" org-link-regexp "\000")
2091 "Matches a link and optionally surrounding angle brackets.")
2092
2093 (defconst org-ts-lengths
2094 (cons (length (format-time-string (car org-time-stamp-formats)))
2095 (length (format-time-string (cdr org-time-stamp-formats))))
2096 "This holds the lengths of the two different time formats.")
2097 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
2098 "Regular expression for fast time stamp matching.")
2099 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2100 "Regular expression matching time strings for analysis.")
2101 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2102 "Regular expression matching time stamps, with groups.")
2103 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2104 "Regular expression matching a time stamp range.")
2105 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2106 org-ts-regexp "\\)?")
2107 "Regular expression matching a time stamp or time stamp range.")
2108
2109 (defun org-activate-links (limit)
2110 "Run through the buffer and add overlays to links."
2111 (if (re-search-forward org-link-regexp limit t)
2112 (progn
2113 (add-text-properties (match-beginning 0) (match-end 0)
2114 (list 'mouse-face 'highlight
2115 'keymap org-mouse-map))
2116 t)))
2117
2118 (defun org-activate-dates (limit)
2119 "Run through the buffer and add overlays to dates."
2120 (if (re-search-forward org-tsr-regexp limit t)
2121 (progn
2122 (add-text-properties (match-beginning 0) (match-end 0)
2123 (list 'mouse-face 'highlight
2124 'keymap org-mouse-map))
2125 t)))
2126
2127 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>")
2128 (defun org-activate-camels (limit)
2129 "Run through the buffer and add overlays to dates."
2130 (if (re-search-forward org-camel-regexp limit t)
2131 (progn
2132 (add-text-properties (match-beginning 0) (match-end 0)
2133 (list 'mouse-face 'highlight
2134 'keymap org-mouse-map))
2135 t)))
2136
2137 (defun org-font-lock-level ()
2138 (save-excursion
2139 (org-back-to-heading t)
2140 (- (match-end 0) (match-beginning 0))))
2141
2142 (defun org-outline-level ()
2143 (save-excursion
2144 (looking-at outline-regexp)
2145 (if (match-beginning 1)
2146 (+ (org-get-string-indentation (match-string 1)) 1000)
2147 (- (match-end 0) (match-beginning 0)))))
2148
2149 (defvar org-font-lock-keywords nil)
2150
2151 (defun org-set-font-lock-defaults ()
2152 (let ((org-font-lock-extra-keywords
2153 (list
2154 '(org-activate-links (0 'org-link))
2155 '(org-activate-dates (0 'org-link))
2156 '(org-activate-camels (0 'org-link))
2157 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2158 '(1 'org-warning t))
2159 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2160 ; (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
2161 ; (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
2162 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2163 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2164 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2165 ;; (3 'bold))
2166 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2167 ;; (3 'italic))
2168 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2169 ;; (3 'underline))
2170 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2171 ; '(1 'org-warning t))
2172 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2173 "\\|" org-quote-string "\\)\\>")
2174 '(1 'org-special-keyword t))
2175 '("^#.*" (0 'font-lock-comment-face t))
2176 (if org-fontify-done-headline
2177 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2178 '(1 'org-done t) '(2 'org-headline-done t))
2179 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2180 '(1 'org-done t)))
2181 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2182 (1 'org-table t))
2183 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2184 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2185 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2186 )))
2187 (set (make-local-variable 'org-font-lock-keywords)
2188 (append
2189 (if org-noutline-p ; FIXME: I am not sure if eval will work
2190 ; on XEmacs if noutline is ever ported
2191 `((eval . (list "^\\(\\*+\\).*"
2192 ,(if org-level-color-stars-only 1 0)
2193 '(nth ;; FIXME: 1<->0 ????
2194 (% (- (match-end 1) (match-beginning 1) 1)
2195 org-n-levels)
2196 org-level-faces)
2197 nil t)))
2198 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2199 (,(if org-level-color-stars-only 2 0)
2200 (nth (% (- (match-end 2) (match-beginning 2) 1)
2201 org-n-levels)
2202 org-level-faces)
2203 nil t))))
2204 org-font-lock-extra-keywords))
2205 (set (make-local-variable 'font-lock-defaults)
2206 '(org-font-lock-keywords t nil nil backward-paragraph))
2207 (kill-local-variable 'font-lock-keywords) nil))
2208
2209 (defun org-unfontify-region (beg end &optional maybe_loudly)
2210 "Remove fontification and activation overlays from links."
2211 (font-lock-default-unfontify-region beg end)
2212 (let* ((buffer-undo-list t)
2213 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2214 (inhibit-modification-hooks t)
2215 deactivate-mark buffer-file-name buffer-file-truename)
2216 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2217
2218 ;;; Visibility cycling
2219
2220 (defvar org-cycle-global-status nil)
2221 (defvar org-cycle-subtree-status nil)
2222 (defun org-cycle (&optional arg)
2223 "Visibility cycling for Org-mode.
2224
2225 - When this function is called with a prefix argument, rotate the entire
2226 buffer through 3 states (global cycling)
2227 1. OVERVIEW: Show only top-level headlines.
2228 2. CONTENTS: Show all headlines of all levels, but no body text.
2229 3. SHOW ALL: Show everything.
2230
2231 - When point is at the beginning of a headline, rotate the subtree started
2232 by this line through 3 different states (local cycling)
2233 1. FOLDED: Only the main headline is shown.
2234 2. CHILDREN: The main headline and the direct children are shown. From
2235 this state, you can move to one of the children and
2236 zoom in further.
2237 3. SUBTREE: Show the entire subtree, including body text.
2238
2239 - When there is a numeric prefix, go up to a heading with level ARG, do
2240 a `show-subtree' and return to the previous cursor position. If ARG
2241 is negative, go up that many levels.
2242
2243 - When point is not at the beginning of a headline, execute
2244 `indent-relative', like TAB normally does. See the option
2245 `org-cycle-emulate-tab' for details.
2246
2247 - Special case: if point is the the beginning of the buffer and there is
2248 no headline in line 1, this function will act as if called with prefix arg."
2249 (interactive "P")
2250
2251 (if (or (and (bobp) (not (looking-at outline-regexp)))
2252 (equal arg '(4)))
2253 ;; special case: use global cycling
2254 (setq arg t))
2255
2256 (let ((outline-regexp
2257 (if org-cycle-include-plain-lists
2258 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2259 outline-regexp)))
2260
2261 (cond
2262
2263 ((org-at-table-p 'any)
2264 ;; Enter the table or move to the next field in the table
2265 (or (org-table-recognize-table.el)
2266 (progn
2267 (org-table-justify-field-maybe)
2268 (org-table-next-field))))
2269
2270 ((eq arg t) ;; Global cycling
2271
2272 (cond
2273 ((and (eq last-command this-command)
2274 (eq org-cycle-global-status 'overview))
2275 ;; We just created the overview - now do table of contents
2276 ;; This can be slow in very large buffers, so indicate action
2277 (message "CONTENTS...")
2278 (save-excursion
2279 ;; Visit all headings and show their offspring
2280 (goto-char (point-max))
2281 (catch 'exit
2282 (while (and (progn (condition-case nil
2283 (outline-previous-visible-heading 1)
2284 (error (goto-char (point-min))))
2285 t)
2286 (looking-at outline-regexp))
2287 (show-branches)
2288 (if (bobp) (throw 'exit nil))))
2289 (message "CONTENTS...done"))
2290 (setq org-cycle-global-status 'contents)
2291 (run-hook-with-args 'org-cycle-hook 'contents))
2292
2293 ((and (eq last-command this-command)
2294 (eq org-cycle-global-status 'contents))
2295 ;; We just showed the table of contents - now show everything
2296 (show-all)
2297 (message "SHOW ALL")
2298 (setq org-cycle-global-status 'all)
2299 (run-hook-with-args 'org-cycle-hook 'all))
2300
2301 (t
2302 ;; Default action: go to overview
2303 (hide-sublevels 1)
2304 (message "OVERVIEW")
2305 (setq org-cycle-global-status 'overview)
2306 (run-hook-with-args 'org-cycle-hook 'overview))))
2307
2308 ((integerp arg)
2309 ;; Show-subtree, ARG levels up from here.
2310 (save-excursion
2311 (org-back-to-heading)
2312 (outline-up-heading (if (< arg 0) (- arg)
2313 (- (outline-level) arg)))
2314 (org-show-subtree)))
2315
2316 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2317 ;; At a heading: rotate between three different views
2318 (org-back-to-heading)
2319 (let ((goal-column 0) eoh eol eos)
2320 ;; First, some boundaries
2321 (save-excursion
2322 (org-back-to-heading)
2323 (save-excursion
2324 (beginning-of-line 2)
2325 (while (and (not (eobp)) ;; this is like `next-line'
2326 (get-char-property (1- (point)) 'invisible))
2327 (beginning-of-line 2)) (setq eol (point)))
2328 (outline-end-of-heading) (setq eoh (point))
2329 (outline-end-of-subtree) (setq eos (point))
2330 (outline-next-heading))
2331 ;; Find out what to do next and set `this-command'
2332 (cond
2333 ((= eos eoh)
2334 ;; Nothing is hidden behind this heading
2335 (message "EMPTY ENTRY")
2336 (setq org-cycle-subtree-status nil))
2337 ((>= eol eos)
2338 ;; Entire subtree is hidden in one line: open it
2339 (org-show-entry)
2340 (show-children)
2341 (message "CHILDREN")
2342 (setq org-cycle-subtree-status 'children)
2343 (run-hook-with-args 'org-cycle-hook 'children))
2344 ((and (eq last-command this-command)
2345 (eq org-cycle-subtree-status 'children))
2346 ;; We just showed the children, now show everything.
2347 (org-show-subtree)
2348 (message "SUBTREE")
2349 (setq org-cycle-subtree-status 'subtree)
2350 (run-hook-with-args 'org-cycle-hook 'subtree))
2351 (t
2352 ;; Default action: hide the subtree.
2353 (hide-subtree)
2354 (message "FOLDED")
2355 (setq org-cycle-subtree-status 'folded)
2356 (run-hook-with-args 'org-cycle-hook 'folded)))))
2357
2358 ;; TAB emulation
2359 (buffer-read-only (org-back-to-heading))
2360 ((if (and (eq org-cycle-emulate-tab 'white)
2361 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2362 t
2363 (eq org-cycle-emulate-tab t))
2364 (if (and (looking-at "[ \n\r\t]")
2365 (string-match "^[ \t]*$" (buffer-substring
2366 (point-at-bol) (point))))
2367 (progn
2368 (beginning-of-line 1)
2369 (and (looking-at "[ \t]+") (replace-match ""))))
2370 (indent-relative))
2371
2372 (t (save-excursion
2373 (org-back-to-heading)
2374 (org-cycle))))))
2375
2376 (defun org-optimize-window-after-visibility-change (state)
2377 "Adjust the window after a change in outline visibility.
2378 This function is the default value of the hook `org-cycle-hook'."
2379 (cond
2380 ((eq state 'overview) (org-first-headline-recenter 1))
2381 ((eq state 'content) nil)
2382 ((eq state 'all) nil)
2383 ((eq state 'folded) nil)
2384 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2385 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2386
2387 (defun org-subtree-end-visible-p ()
2388 "Is the end of the current subtree visible?"
2389 (pos-visible-in-window-p
2390 (save-excursion (outline-end-of-subtree) (point))))
2391
2392 (defun org-first-headline-recenter (&optional N)
2393 "Move cursor to the first headline and recenter the headline.
2394 Optional argument N means, put the headline into the Nth line of the window."
2395 (goto-char (point-min))
2396 (when (re-search-forward (concat "^" outline-regexp) nil t)
2397 (beginning-of-line)
2398 (recenter (prefix-numeric-value N))))
2399
2400 (defvar org-goto-window-configuration nil)
2401 (defvar org-goto-marker nil)
2402 (defvar org-goto-map (make-sparse-keymap))
2403 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2404 (while (setq cmd (pop cmds))
2405 (substitute-key-definition cmd cmd org-goto-map global-map)))
2406 (define-key org-goto-map "\C-m" 'org-goto-ret)
2407 (define-key org-goto-map [(left)] 'org-goto-left)
2408 (define-key org-goto-map [(right)] 'org-goto-right)
2409 (define-key org-goto-map [(?q)] 'org-goto-quit)
2410 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2411 (define-key org-goto-map "\C-i" 'org-cycle)
2412 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2413 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2414 (define-key org-goto-map "n" 'outline-next-visible-heading)
2415 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2416 (define-key org-goto-map "f" 'outline-forward-same-level)
2417 (define-key org-goto-map "b" 'outline-backward-same-level)
2418 (define-key org-goto-map "u" 'outline-up-heading)
2419 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2420 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2421 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2422 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2423 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2424 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2425 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2426
2427 (defconst org-goto-help
2428 "Select a location to jump to, press RET
2429 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2430
2431 (defun org-goto ()
2432 "Go to a different location of the document, keeping current visibility.
2433
2434 When you want to go to a different location in a document, the fastest way
2435 is often to fold the entire buffer and then dive into the tree. This
2436 method has the disadvantage, that the previous location will be folded,
2437 which may not be what you want.
2438
2439 This command works around this by showing a copy of the current buffer in
2440 overview mode. You can dive into the tree in that copy, to find the
2441 location you want to reach. When pressing RET, the command returns to the
2442 original buffer in which the visibility is still unchanged. It then jumps
2443 to the new location, making it and the headline hierarchy above it visible."
2444 (interactive)
2445 (let* ((org-goto-start-pos (point))
2446 (selected-point
2447 (org-get-location (current-buffer) org-goto-help)))
2448 (if selected-point
2449 (progn
2450 (goto-char selected-point)
2451 (if (org-invisible-p) (org-show-hierarchy-above)))
2452 (error "Quit"))))
2453
2454 (defun org-get-location (buf help)
2455 "Let the user select a location in the Org-mode buffer BUF.
2456 This function uses a recursive edit. It returns the selected position
2457 or nil."
2458 (let (org-selected-point)
2459 (save-excursion
2460 (save-window-excursion
2461 (delete-other-windows)
2462 (switch-to-buffer (get-buffer-create "*org-goto*"))
2463 (with-output-to-temp-buffer "*Help*"
2464 (princ help))
2465 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2466 (setq buffer-read-only nil)
2467 (erase-buffer)
2468 (insert-buffer-substring buf)
2469 (let ((org-startup-truncated t)
2470 (org-startup-folded t)
2471 (org-startup-with-deadline-check nil))
2472 (org-mode))
2473 (setq buffer-read-only t)
2474 (if (boundp 'org-goto-start-pos)
2475 (goto-char org-goto-start-pos)
2476 (goto-char (point-min)))
2477 (org-beginning-of-line)
2478 (message "Select location and press RET")
2479 ;; now we make sure that during selection, ony very few keys work
2480 ;; and that it is impossible to switch to another window.
2481 (let ((gm (current-global-map))
2482 (overriding-local-map org-goto-map))
2483 (unwind-protect
2484 (progn
2485 (use-global-map org-goto-map)
2486 (recursive-edit))
2487 (use-global-map gm)))))
2488 (kill-buffer "*org-goto*")
2489 org-selected-point))
2490
2491 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2492 (defun org-goto-ret (&optional arg)
2493 "Finish org-goto by going to the new location."
2494 (interactive "P")
2495 (setq org-selected-point (point)
2496 current-prefix-arg arg)
2497 (throw 'exit nil))
2498
2499 (defun org-goto-left ()
2500 "Finish org-goto by going to the new location."
2501 (interactive)
2502 (if (org-on-heading-p)
2503 (progn
2504 (beginning-of-line 1)
2505 (setq org-selected-point (point)
2506 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2507 (throw 'exit nil))
2508 (error "Not on a heading")))
2509
2510 (defun org-goto-right ()
2511 "Finish org-goto by going to the new location."
2512 (interactive)
2513 (if (org-on-heading-p)
2514 (progn
2515 (outline-end-of-subtree)
2516 (or (eobp) (forward-char 1))
2517 (setq org-selected-point (point)
2518 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2519 (throw 'exit nil))
2520 (error "Not on a heading")))
2521
2522 (defun org-goto-quit ()
2523 "Finish org-goto without cursor motion."
2524 (interactive)
2525 (setq org-selected-point nil)
2526 (throw 'exit nil))
2527
2528 ;;; Promotion, Demotion, Inserting new headlines
2529
2530 (defvar org-ignore-region nil
2531 "To temporarily disable the active region.")
2532
2533 (defun org-insert-heading ()
2534 "Insert a new heading with same depth at point."
2535 (interactive)
2536 (let* ((head (save-excursion
2537 (condition-case nil
2538 (org-back-to-heading)
2539 (error (outline-next-heading)))
2540 (prog1 (match-string 0)
2541 (funcall outline-level)))))
2542 (unless (bolp) (newline))
2543 (insert head)
2544 (unless (eolp)
2545 (save-excursion (newline-and-indent)))
2546 (unless (equal (char-before) ?\ )
2547 (insert " "))
2548 (run-hooks 'org-insert-heading-hook)))
2549
2550 (defun org-insert-todo-heading (arg)
2551 "Insert a new heading with the same level and TODO state as current heading.
2552 If the heading has no TODO state, or if the state is DONE, use the first
2553 state (TODO by default). Also with prefix arg, force first state."
2554 (interactive "P")
2555 (org-insert-heading)
2556 (save-excursion
2557 (org-back-to-heading)
2558 (outline-previous-heading)
2559 (looking-at org-todo-line-regexp))
2560 (if (or arg
2561 (not (match-beginning 2))
2562 (equal (match-string 2) org-done-string))
2563 (insert (car org-todo-keywords) " ")
2564 (insert (match-string 2) " ")))
2565
2566 (defun org-promote-subtree ()
2567 "Promote the entire subtree.
2568 See also `org-promote'."
2569 (interactive)
2570 (save-excursion
2571 (org-map-tree 'org-promote)))
2572
2573 (defun org-demote-subtree ()
2574 "Demote the entire subtree. See `org-demote'.
2575 See also `org-promote'."
2576 (interactive)
2577 (save-excursion
2578 (org-map-tree 'org-demote)))
2579
2580 (defun org-do-promote ()
2581 "Promote the current heading higher up the tree.
2582 If the region is active in `transient-mark-mode', promote all headings
2583 in the region."
2584 (interactive)
2585 (save-excursion
2586 (if (org-region-active-p)
2587 (org-map-region 'org-promote (region-beginning) (region-end))
2588 (org-promote)))
2589 (org-fix-position-after-promote))
2590
2591 (defun org-do-demote ()
2592 "Demote the current heading lower down the tree.
2593 If the region is active in `transient-mark-mode', demote all headings
2594 in the region."
2595 (interactive)
2596 (save-excursion
2597 (if (org-region-active-p)
2598 (org-map-region 'org-demote (region-beginning) (region-end))
2599 (org-demote)))
2600 (org-fix-position-after-promote))
2601
2602 (defun org-fix-position-after-promote ()
2603 "Make sure that after pro/demotion cursor position is right."
2604 (and (equal (char-after) ?\ )
2605 (equal (char-before) ?*)
2606 (forward-char 1)))
2607
2608 (defun org-promote ()
2609 "Promote the current heading higher up the tree.
2610 If the region is active in `transient-mark-mode', promote all headings
2611 in the region."
2612 (org-back-to-heading t)
2613 (let* ((level (save-match-data (funcall outline-level)))
2614 (up-head (make-string (1- level) ?*)))
2615 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2616 (replace-match up-head nil t)
2617 (if org-adapt-indentation
2618 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2619
2620 (defun org-demote ()
2621 "Demote the current heading lower down the tree.
2622 If the region is active in `transient-mark-mode', demote all headings
2623 in the region."
2624 (org-back-to-heading t)
2625 (let* ((level (save-match-data (funcall outline-level)))
2626 (down-head (make-string (1+ level) ?*)))
2627 (replace-match down-head nil t)
2628 (if org-adapt-indentation
2629 (org-fixup-indentation "^ " " " "^\\S-"))))
2630
2631 (defun org-map-tree (fun)
2632 "Call FUN for every heading underneath the current one."
2633 (org-back-to-heading)
2634 (let ((level (outline-level)))
2635 (save-excursion
2636 (funcall fun)
2637 (while (and (progn
2638 (outline-next-heading)
2639 (> (funcall outline-level) level))
2640 (not (eobp)))
2641 (funcall fun)))))
2642
2643 (defun org-map-region (fun beg end)
2644 "Call FUN for every heading between BEG and END."
2645 (let ((org-ignore-region t))
2646 (save-excursion
2647 (setq end (copy-marker end))
2648 (goto-char beg)
2649 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2650 (< (point) end))
2651 (funcall fun))
2652 (while (and (progn
2653 (outline-next-heading)
2654 (< (point) end))
2655 (not (eobp)))
2656 (funcall fun)))))
2657
2658 (defun org-fixup-indentation (from to prohibit)
2659 "Change the indentation in the current entry by re-replacing FROM with TO.
2660 However, if the regexp PROHIBIT matches at all, don't do anything.
2661 This is being used to change indentation along with the length of the
2662 heading marker. But if there are any lines which are not indented, nothing
2663 is changed at all."
2664 (save-excursion
2665 (let ((end (save-excursion (outline-next-heading)
2666 (point-marker))))
2667 (unless (save-excursion (re-search-forward prohibit end t))
2668 (while (re-search-forward from end t)
2669 (replace-match to)
2670 (beginning-of-line 2)))
2671 (move-marker end nil))))
2672
2673 ;;; Vertical tree motion, cutting and pasting of subtrees
2674
2675 (defun org-move-subtree-up (&optional arg)
2676 "Move the current subtree up past ARG headlines of the same level."
2677 (interactive "p")
2678 (org-move-subtree-down (- (prefix-numeric-value arg))))
2679
2680 (defun org-move-subtree-down (&optional arg)
2681 "Move the current subtree down past ARG headlines of the same level."
2682 (interactive "p")
2683 (setq arg (prefix-numeric-value arg))
2684 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2685 'outline-get-last-sibling))
2686 (ins-point (make-marker))
2687 (cnt (abs arg))
2688 beg end txt folded)
2689 ;; Select the tree
2690 (org-back-to-heading)
2691 (setq beg (point))
2692 (save-match-data
2693 (save-excursion (outline-end-of-heading)
2694 (setq folded (org-invisible-p)))
2695 (outline-end-of-subtree))
2696 (outline-next-heading)
2697 (setq end (point))
2698 ;; Find insertion point, with error handling
2699 (goto-char beg)
2700 (while (> cnt 0)
2701 (or (and (funcall movfunc) (looking-at outline-regexp))
2702 (progn (goto-char beg)
2703 (error "Cannot move past superior level or buffer limit")))
2704 (setq cnt (1- cnt)))
2705 (if (> arg 0)
2706 ;; Moving forward - still need to move over subtree
2707 (progn (outline-end-of-subtree)
2708 (outline-next-heading)
2709 (if (not (or (looking-at (concat "^" outline-regexp))
2710 (bolp)))
2711 (newline))))
2712 (move-marker ins-point (point))
2713 (setq txt (buffer-substring beg end))
2714 (delete-region beg end)
2715 (insert txt)
2716 (goto-char ins-point)
2717 (if folded (hide-subtree))
2718 (move-marker ins-point nil)))
2719
2720 (defvar org-subtree-clip ""
2721 "Clipboard for cut and paste of subtrees.
2722 This is actually only a copy of the kill, because we use the normal kill
2723 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2724
2725 (defvar org-subtree-clip-folded nil
2726 "Was the last copied subtree folded?
2727 This is used to fold the tree back after pasting.")
2728
2729 (defun org-cut-subtree ()
2730 "Cut the current subtree into the clipboard.
2731 This is a short-hand for marking the subtree and then cutting it."
2732 (interactive)
2733 (org-copy-subtree 'cut))
2734
2735 (defun org-copy-subtree (&optional cut)
2736 "Cut the current subtree into the clipboard.
2737 This is a short-hand for marking the subtree and then copying it.
2738 If CUT is non nil, actually cut the subtree."
2739 (interactive)
2740 (let (beg end folded)
2741 (org-back-to-heading)
2742 (setq beg (point))
2743 (save-match-data
2744 (save-excursion (outline-end-of-heading)
2745 (setq folded (org-invisible-p)))
2746 (outline-end-of-subtree))
2747 (if (equal (char-after) ?\n) (forward-char 1))
2748 (setq end (point))
2749 (goto-char beg)
2750 (when (> end beg)
2751 (setq org-subtree-clip-folded folded)
2752 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2753 (setq org-subtree-clip (current-kill 0))
2754 (message "%s: Subtree with %d characters"
2755 (if cut "Cut" "Copied")
2756 (length org-subtree-clip)))))
2757
2758 (defun org-paste-subtree (&optional level tree)
2759 "Paste the clipboard as a subtree, with modification of headline level.
2760 The entire subtree is promoted or demoted in order to match a new headline
2761 level. By default, the new level is derived from the visible headings
2762 before and after the insertion point, and taken to be the inferior headline
2763 level of the two. So if the previous visible heading is level 3 and the
2764 next is level 4 (or vice versa), level 4 will be used for insertion.
2765 This makes sure that the subtree remains an independent subtree and does
2766 not swallow low level entries.
2767
2768 You can also force a different level, either by using a numeric prefix
2769 argument, or by inserting the heading marker by hand. For example, if the
2770 cursor is after \"*****\", then the tree will be shifted to level 5.
2771
2772 If you want to insert the tree as is, just use \\[yank].
2773
2774 If optional TREE is given, use this text instead of the kill ring."
2775 (interactive "P")
2776 (unless (org-kill-is-subtree-p tree)
2777 (error
2778 (substitute-command-keys
2779 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2780 (let* ((txt (or tree (current-kill 0)))
2781 (^re (concat "^\\(" outline-regexp "\\)"))
2782 (re (concat "\\(" outline-regexp "\\)"))
2783 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2784
2785 (old-level (if (string-match ^re txt)
2786 (- (match-end 0) (match-beginning 0))
2787 -1))
2788 (force-level (cond (level (prefix-numeric-value level))
2789 ((string-match
2790 ^re_ (buffer-substring (point-at-bol) (point)))
2791 (- (match-end 0) (match-beginning 0)))
2792 (t nil)))
2793 (previous-level (save-excursion
2794 (condition-case nil
2795 (progn
2796 (outline-previous-visible-heading 1)
2797 (if (looking-at re)
2798 (- (match-end 0) (match-beginning 0))
2799 1))
2800 (error 1))))
2801 (next-level (save-excursion
2802 (condition-case nil
2803 (progn
2804 (outline-next-visible-heading 1)
2805 (if (looking-at re)
2806 (- (match-end 0) (match-beginning 0))
2807 1))
2808 (error 1))))
2809 (new-level (or force-level (max previous-level next-level)))
2810 (shift (if (or (= old-level -1)
2811 (= new-level -1)
2812 (= old-level new-level))
2813 0
2814 (- new-level old-level)))
2815 (shift1 shift)
2816 (delta (if (> shift 0) -1 1))
2817 (func (if (> shift 0) 'org-demote 'org-promote))
2818 beg end)
2819 ;; Remove the forces level indicator
2820 (if force-level
2821 (delete-region (point-at-bol) (point)))
2822 ;; Make sure we start at the beginning of an empty line
2823 (if (not (bolp)) (insert "\n"))
2824 (if (not (looking-at "[ \t]*$"))
2825 (progn (insert "\n") (backward-char 1)))
2826 ;; Paste
2827 (setq beg (point))
2828 (insert txt)
2829 (setq end (point))
2830 (goto-char beg)
2831 ;; Shift if necessary
2832 (if (= shift 0)
2833 (message "Pasted at level %d, without shift" new-level)
2834 (save-restriction
2835 (narrow-to-region beg end)
2836 (while (not (= shift 0))
2837 (org-map-region func (point-min) (point-max))
2838 (setq shift (+ delta shift)))
2839 (goto-char (point-min))
2840 (message "Pasted at level %d, with shift by %d levels"
2841 new-level shift1)))
2842 (if (and (eq org-subtree-clip (current-kill 0))
2843 org-subtree-clip-folded)
2844 ;; The tree was folded before it was killed/copied
2845 (hide-subtree))))
2846
2847 (defun org-kill-is-subtree-p (&optional txt)
2848 "Check if the current kill is an outline subtree, or a set of trees.
2849 Returns nil if kill does not start with a headline, or if the first
2850 headline level is not the largest headline level in the tree.
2851 So this will actually accept several entries of equal levels as well,
2852 which is OK for `org-paste-subtree'.
2853 If optional TXT is given, check this string instead of the current kill."
2854 (let* ((kill (or txt (current-kill 0) ""))
2855 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2856 (- (match-end 0) (match-beginning 0))))
2857 (re (concat "^" outline-regexp))
2858 (start 1))
2859 (if (not start-level)
2860 nil ;; does not even start with a heading
2861 (catch 'exit
2862 (while (setq start (string-match re kill (1+ start)))
2863 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2864 (throw 'exit nil)))
2865 t))))
2866
2867 ;;; Plain list item
2868
2869 (defun org-at-item-p ()
2870 "Is point in a line starting a hand-formatted item?"
2871 (let ((llt org-plain-list-ordered-item-terminator))
2872 (save-excursion
2873 (goto-char (point-at-bol))
2874 (looking-at
2875 (cond
2876 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2877 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2878 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2879 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2880
2881 (defun org-get-indentation ()
2882 "Get the indentation of the current line, ionterpreting tabs."
2883 (save-excursion
2884 (beginning-of-line 1)
2885 (skip-chars-forward " \t")
2886 (current-column)))
2887
2888 (defun org-beginning-of-item ()
2889 "Go to the beginning of the current hand-formatted item.
2890 If the cursor is not in an item, throw an error."
2891 (let ((pos (point))
2892 (limit (save-excursion (org-back-to-heading)
2893 (beginning-of-line 2) (point)))
2894 ind ind1)
2895 (if (org-at-item-p)
2896 (beginning-of-line 1)
2897 (beginning-of-line 1)
2898 (skip-chars-forward " \t")
2899 (setq ind (current-column))
2900 (if (catch 'exit
2901 (while t
2902 (beginning-of-line 0)
2903 (if (< (point) limit) (throw 'exit nil))
2904 (unless (looking-at " \t]*$")
2905 (skip-chars-forward " \t")
2906 (setq ind1 (current-column))
2907 (if (< ind1 ind)
2908 (throw 'exit (org-at-item-p))))))
2909 nil
2910 (goto-char pos)
2911 (error "Not in an item")))))
2912
2913 (defun org-end-of-item ()
2914 "Go to the beginning of the current hand-formatted item.
2915 If the cursor is not in an item, throw an error."
2916 (let ((pos (point))
2917 (limit (save-excursion (outline-next-heading) (point)))
2918 (ind (save-excursion
2919 (org-beginning-of-item)
2920 (skip-chars-forward " \t")
2921 (current-column)))
2922 ind1)
2923 (if (catch 'exit
2924 (while t
2925 (beginning-of-line 2)
2926 (if (>= (point) limit) (throw 'exit t))
2927 (unless (looking-at "[ \t]*$")
2928 (skip-chars-forward " \t")
2929 (setq ind1 (current-column))
2930 (if (<= ind1 ind) (throw 'exit t)))))
2931 (beginning-of-line 1)
2932 (goto-char pos)
2933 (error "Not in an item"))))
2934
2935 (defun org-move-item-down (arg)
2936 "Move the plain list item at point down, i.e. swap with following item.
2937 Subitems (items with larger indentation are considered part of the item,
2938 so this really moves item trees."
2939 (interactive "p")
2940 (let (beg end ind ind1 (pos (point)) txt)
2941 (org-beginning-of-item)
2942 (setq beg (point))
2943 (setq ind (org-get-indentation))
2944 (org-end-of-item)
2945 (setq end (point))
2946 (setq ind1 (org-get-indentation))
2947 (if (and (org-at-item-p) (= ind ind1))
2948 (progn
2949 (org-end-of-item)
2950 (setq txt (buffer-substring beg end))
2951 (save-excursion
2952 (delete-region beg end))
2953 (setq pos (point))
2954 (insert txt)
2955 (goto-char pos)
2956 (org-maybe-renumber-ordered-list))
2957 (goto-char pos)
2958 (error "Cannot move this item further down"))))
2959
2960 (defun org-move-item-up (arg)
2961 "Move the plain list item at point up, i.e. swap with previous item.
2962 Subitems (items with larger indentation are considered part of the item,
2963 so this really moves item trees."
2964 (interactive "p")
2965 (let (beg end ind ind1 (pos (point)) txt)
2966 (org-beginning-of-item)
2967 (setq beg (point))
2968 (setq ind (org-get-indentation))
2969 (org-end-of-item)
2970 (setq end (point))
2971 (goto-char beg)
2972 (catch 'exit
2973 (while t
2974 (beginning-of-line 0)
2975 (if (looking-at "[ \t]*$")
2976 nil
2977 (if (<= (setq ind1 (org-get-indentation)) ind)
2978 (throw 'exit t)))))
2979 (condition-case nil
2980 (org-beginning-of-item)
2981 (error (goto-char beg)
2982 (error "Cannot move this item further up")))
2983 (setq ind1 (org-get-indentation))
2984 (if (and (org-at-item-p) (= ind ind1))
2985 (progn
2986 (setq txt (buffer-substring beg end))
2987 (save-excursion
2988 (delete-region beg end))
2989 (setq pos (point))
2990 (insert txt)
2991 (goto-char pos)
2992 (org-maybe-renumber-ordered-list))
2993 (goto-char pos)
2994 (error "Cannot move this item further up"))))
2995
2996 (defun org-maybe-renumber-ordered-list ()
2997 "Renumber the ordered list at point if setup allows it.
2998 This tests the user option `org-auto-renumber-ordered-lists' before
2999 doing the renumbering."
3000 (and org-auto-renumber-ordered-lists
3001 (org-at-item-p)
3002 (match-beginning 3)
3003 (org-renumber-ordered-list 1)))
3004
3005 (defun org-get-string-indentation (s)
3006 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3007 (let ((n -1) (i 0) (w tab-width) c)
3008 (catch 'exit
3009 (while (< (setq n (1+ n)) (length s))
3010 (setq c (aref s n))
3011 (cond ((= c ?\ ) (setq i (1+ i)))
3012 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3013 (t (throw 'exit t)))))
3014 i))
3015
3016 (defun org-renumber-ordered-list (arg)
3017 "Renumber an ordered plain list.
3018 Cursor neext to be in the first line of an item, the line that starts
3019 with something like \"1.\" or \"2)\"."
3020 (interactive "p")
3021 (unless (and (org-at-item-p)
3022 (match-beginning 3))
3023 (error "This is not an ordered list"))
3024 (let ((line (org-current-line))
3025 (col (current-column))
3026 (ind (org-get-string-indentation
3027 (buffer-substring (point-at-bol) (match-beginning 3))))
3028 (term (substring (match-string 3) -1))
3029 ind1 (n (1- arg)))
3030 ;; find where this list begins
3031 (catch 'exit
3032 (while t
3033 (catch 'next
3034 (beginning-of-line 0)
3035 (if (looking-at "[ \t]*$") (throw 'next t))
3036 (skip-chars-forward " \t") (setq ind1 (current-column))
3037 (if (and (<= ind1 ind)
3038 (not (org-at-item-p)))
3039 (throw 'exit t)))))
3040 ;; Walk forward and replace these numbers
3041 (catch 'exit
3042 (while t
3043 (catch 'next
3044 (beginning-of-line 2)
3045 (if (eobp) (throw 'exit nil))
3046 (if (looking-at "[ \t]*$") (throw 'next nil))
3047 (skip-chars-forward " \t") (setq ind1 (current-column))
3048 (if (> ind1 ind) (throw 'next t))
3049 (if (< ind1 ind) (throw 'exit t))
3050 (if (not (org-at-item-p)) (throw 'exit nil))
3051 (if (not (match-beginning 3))
3052 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3053 (delete-region (match-beginning 3) (1- (match-end 3)))
3054 (goto-char (match-beginning 3))
3055 (insert (format "%d" (setq n (1+ n)))))))
3056 (goto-line line)
3057 (move-to-column col)))
3058
3059 (defvar org-last-indent-begin-marker (make-marker))
3060 (defvar org-last-indent-end-marker (make-marker))
3061
3062
3063 (defun org-outdent-item (arg)
3064 "Outdent a local list item."
3065 (interactive "p")
3066 (org-indent-item (- arg)))
3067
3068 (defun org-indent-item (arg)
3069 "Indent a local list item."
3070 (interactive "p")
3071 (unless (org-at-item-p)
3072 (error "Not on an item"))
3073 (let (beg end ind ind1)
3074 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3075 (setq beg org-last-indent-begin-marker
3076 end org-last-indent-end-marker)
3077 (org-beginning-of-item)
3078 (setq beg (move-marker org-last-indent-begin-marker (point)))
3079 (org-end-of-item)
3080 (setq end (move-marker org-last-indent-end-marker (point))))
3081 (goto-char beg)
3082 (skip-chars-forward " \t") (setq ind (current-column))
3083 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3084 (while (< (point) end)
3085 (beginning-of-line 1)
3086 (skip-chars-forward " \t") (setq ind1 (current-column))
3087 (delete-region (point-at-bol) (point))
3088 (indent-to-column (+ ind1 arg))
3089 (beginning-of-line 2))
3090 (goto-char beg)))
3091
3092
3093 ;;; Archiving
3094
3095 (defun org-archive-subtree ()
3096 "Move the current subtree to the archive.
3097 The archive can be a certain top-level heading in the current file, or in
3098 a different file. The tree will be moved to that location, the subtree
3099 heading be marked DONE, and the current time will be added."
3100 (interactive)
3101 ;; Save all relevant TODO keyword-relatex variables
3102 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3103 (tr-org-todo-keywords org-todo-keywords)
3104 (tr-org-todo-interpretation org-todo-interpretation)
3105 (tr-org-done-string org-done-string)
3106 (tr-org-todo-regexp org-todo-regexp)
3107 (tr-org-todo-line-regexp org-todo-line-regexp)
3108 (this-buffer (current-buffer))
3109 file heading buffer level newfile-p)
3110 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3111 (progn
3112 (setq file (format (match-string 1 org-archive-location)
3113 (file-name-nondirectory (buffer-file-name)))
3114 heading (match-string 2 org-archive-location)))
3115 (error "Invalid `org-archive-location'"))
3116 (if (> (length file) 0)
3117 (setq newfile-p (not (file-exists-p file))
3118 buffer (find-file-noselect file))
3119 (setq buffer (current-buffer)))
3120 (unless buffer
3121 (error "Cannot access file \"%s\"" file))
3122 (if (and (> (length heading) 0)
3123 (string-match "^\\*+" heading))
3124 (setq level (match-end 0))
3125 (setq heading nil level 0))
3126 (save-excursion
3127 ;; We first only copy, in case something goes wrong
3128 ;; we need to protect this-command, to avoid kill-region sets it,
3129 ;; which would lead to duplication of subtrees
3130 (let (this-command) (org-copy-subtree))
3131 (set-buffer buffer)
3132 ;; Enforce org-mode for the archive buffer
3133 (if (not (eq major-mode 'org-mode))
3134 ;; Force the mode for future visits.
3135 (let ((org-insert-mode-line-in-empty-file t))
3136 (call-interactively 'org-mode)))
3137 (when newfile-p
3138 (goto-char (point-max))
3139 (insert (format "\nArchived entries from file %s\n\n"
3140 (buffer-file-name this-buffer))))
3141 ;; Force the TODO keywords of the original buffer
3142 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3143 (org-todo-keywords tr-org-todo-keywords)
3144 (org-todo-interpretation tr-org-todo-interpretation)
3145 (org-done-string tr-org-done-string)
3146 (org-todo-regexp tr-org-todo-regexp)
3147 (org-todo-line-regexp tr-org-todo-line-regexp))
3148 (goto-char (point-min))
3149 (if heading
3150 (progn
3151 (if (re-search-forward
3152 (concat "\\(^\\|\r\\)"
3153 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3154 nil t)
3155 (goto-char (match-end 0))
3156 ;; Heading not found, just insert it at the end
3157 (goto-char (point-max))
3158 (or (bolp) (insert "\n"))
3159 (insert "\n" heading "\n")
3160 (end-of-line 0))
3161 ;; Make the heading visible, and the following as well
3162 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3163 (if (re-search-forward
3164 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3165 nil t)
3166 (progn (goto-char (match-beginning 0)) (insert "\n")
3167 (beginning-of-line 0))
3168 (goto-char (point-max)) (insert "\n")))
3169 (goto-char (point-max)) (insert "\n"))
3170 ;; Paste
3171 (org-paste-subtree (1+ level))
3172 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3173 (if org-archive-mark-done
3174 (org-todo (length org-todo-keywords)))
3175 ;; Move cursor to right after the TODO keyword
3176 (when org-archive-stamp-time
3177 (beginning-of-line 1)
3178 (looking-at org-todo-line-regexp)
3179 (goto-char (or (match-end 2) (match-beginning 3)))
3180 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3181 (current-time))
3182 ")"))
3183 ;; Save the buffer, if it is not the same buffer.
3184 (if (not (eq this-buffer buffer)) (save-buffer))))
3185 ;; Here we are back in the original buffer. Everything seems to have
3186 ;; worked. So now cut the tree and finish up.
3187 (let (this-command) (org-cut-subtree))
3188 (if (looking-at "[ \t]*$") (kill-line))
3189 (message "Subtree archived %s"
3190 (if (eq this-buffer buffer)
3191 (concat "under heading: " heading)
3192 (concat "in file: " (abbreviate-file-name file))))))
3193
3194 ;;; Completion
3195
3196 (defun org-complete (&optional arg)
3197 "Perform completion on word at point.
3198 At the beginning of a headline, this completes TODO keywords as given in
3199 `org-todo-keywords'.
3200 If the current word is preceded by a backslash, completes the TeX symbols
3201 that are supported for HTML support.
3202 If the current word is preceded by \"#+\", completes special words for
3203 setting file options.
3204 At all other locations, this simply calls `ispell-complete-word'."
3205 (interactive "P")
3206 (catch 'exit
3207 (let* ((end (point))
3208 (beg (save-excursion
3209 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3210 (skip-chars-backward "a-zA-Z0-9_:$")
3211 (point)))
3212 (camel (equal (char-before beg) ?*))
3213 (texp (equal (char-before beg) ?\\))
3214 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3215 beg)
3216 "#+"))
3217 (pattern (buffer-substring-no-properties beg end))
3218 (completion-ignore-case opt)
3219 (type nil)
3220 (tbl nil)
3221 (table (cond
3222 (opt
3223 (setq type :opt)
3224 (mapcar (lambda (x)
3225 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3226 (cons (match-string 2 x) (match-string 1 x)))
3227 (org-split-string (org-get-current-options) "\n")))
3228 (texp
3229 (setq type :tex)
3230 org-html-entities)
3231 ((string-match "\\`\\*+[ \t]*\\'"
3232 (buffer-substring (point-at-bol) beg))
3233 (setq type :todo)
3234 (mapcar 'list org-todo-keywords))
3235 (camel
3236 (setq type :camel)
3237 (save-excursion
3238 (goto-char (point-min))
3239 (while (re-search-forward org-todo-line-regexp nil t)
3240 (push (list (org-make-org-heading-camel (match-string 3)))
3241 tbl)))
3242 tbl)
3243 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3244 (completion (try-completion pattern table)))
3245 (cond ((eq completion t)
3246 (if (equal type :opt)
3247 (insert (substring (cdr (assoc (upcase pattern) table))
3248 (length pattern)))))
3249 ((null completion)
3250 (message "Can't find completion for \"%s\"" pattern)
3251 (ding))
3252 ((not (string= pattern completion))
3253 (delete-region beg end)
3254 (if (string-match " +$" completion)
3255 (setq completion (replace-match "" t t completion)))
3256 (insert completion)
3257 (if (get-buffer-window "*Completions*")
3258 (delete-window (get-buffer-window "*Completions*")))
3259 (if (and (eq type :todo)
3260 (assoc completion table))
3261 (insert " "))
3262 (if (and (equal type :opt) (assoc completion table))
3263 (message "%s" (substitute-command-keys
3264 "Press \\[org-complete] again to insert example settings"))))
3265 (t
3266 (message "Making completion list...")
3267 (let ((list (sort (all-completions pattern table) 'string<)))
3268 (with-output-to-temp-buffer "*Completions*"
3269 (display-completion-list list)))
3270 (message "Making completion list...%s" "done"))))))
3271
3272 ;;; Comments, TODO and DEADLINE
3273
3274 (defun org-toggle-comment ()
3275 "Change the COMMENT state of an entry."
3276 (interactive)
3277 (save-excursion
3278 (org-back-to-heading)
3279 (if (looking-at (concat outline-regexp
3280 "\\( +\\<" org-comment-string "\\>\\)"))
3281 (replace-match "" t t nil 1)
3282 (if (looking-at outline-regexp)
3283 (progn
3284 (goto-char (match-end 0))
3285 (insert " " org-comment-string))))))
3286
3287 (defvar org-last-todo-state-is-todo nil
3288 "This is non-nil when the last TODO state change led to a TODO state.
3289 If the last change removed the TODO tag or switched to DONE, then
3290 this is nil.")
3291
3292 (defun org-todo (&optional arg)
3293 "Change the TODO state of an item.
3294 The state of an item is given by a keyword at the start of the heading,
3295 like
3296 *** TODO Write paper
3297 *** DONE Call mom
3298
3299 The different keywords are specified in the variable `org-todo-keywords'. By
3300 default the available states are \"TODO\" and \"DONE\".
3301 So for this example: when the item starts with TODO, it is changed to DONE.
3302 When it starts with DONE, the DONE is removed. And when neither TODO nor
3303 DONE are present, add TODO at the beginning of the heading.
3304
3305 With prefix arg, use completion to determined the new state. With numeric
3306 prefix arg, switch to that state."
3307 (interactive "P")
3308 (save-excursion
3309 (org-back-to-heading)
3310 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3311 (or (looking-at (concat " +" org-todo-regexp " *"))
3312 (looking-at " *"))
3313 (let* ((this (match-string 1))
3314 (completion-ignore-case t)
3315 (member (member this org-todo-keywords))
3316 (tail (cdr member))
3317 (state (cond
3318 ((equal arg '(4))
3319 ;; Read a state with completion
3320 (completing-read "State: " (mapcar (lambda(x) (list x))
3321 org-todo-keywords)
3322 nil t))
3323 ((eq arg 'right)
3324 (if this
3325 (if tail (car tail) nil)
3326 (car org-todo-keywords)))
3327 ((eq arg 'left)
3328 (if (equal member org-todo-keywords)
3329 nil
3330 (if this
3331 (nth (- (length org-todo-keywords) (length tail) 2)
3332 org-todo-keywords)
3333 org-done-string)))
3334 (arg
3335 ;; user requests a specific state
3336 (nth (1- (prefix-numeric-value arg))
3337 org-todo-keywords))
3338 ((null member) (car org-todo-keywords))
3339 ((null tail) nil) ;; -> first entry
3340 ((eq org-todo-interpretation 'sequence)
3341 (car tail))
3342 ((memq org-todo-interpretation '(type priority))
3343 (if (eq this-command last-command)
3344 (car tail)
3345 (if (> (length tail) 0) org-done-string nil)))
3346 (t nil)))
3347 (next (if state (concat " " state " ") " ")))
3348 (replace-match next t t)
3349 (setq org-last-todo-state-is-todo
3350 (not (equal state org-done-string)))
3351 (run-hooks 'org-after-todo-state-change-hook)))
3352 ;; Fixup cursor location if close to the keyword
3353 (if (and (outline-on-heading-p)
3354 (not (bolp))
3355 (save-excursion (beginning-of-line 1)
3356 (looking-at org-todo-line-regexp))
3357 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3358 (progn
3359 (goto-char (or (match-end 2) (match-end 1)))
3360 (just-one-space))))
3361
3362 (defun org-show-todo-tree (arg)
3363 "Make a compact tree which shows all headlines marked with TODO.
3364 The tree will show the lines where the regexp matches, and all higher
3365 headlines above the match.
3366 With \\[universal-argument] prefix, also show the DONE entries.
3367 With a numeric prefix N, construct a sparse tree for the Nth element
3368 of `org-todo-keywords'."
3369 (interactive "P")
3370 (let ((case-fold-search nil)
3371 (kwd-re
3372 (cond ((null arg) org-not-done-regexp)
3373 ((equal arg '(4)) org-todo-regexp)
3374 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3375 (regexp-quote (nth (1- (prefix-numeric-value arg))
3376 org-todo-keywords)))
3377 (t (error "Invalid prefix argument: %s" arg)))))
3378 (message "%d TODO entries found"
3379 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3380
3381 (defun org-deadline ()
3382 "Insert the DEADLINE: string to make a deadline.
3383 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3384 to modify it to the correct date."
3385 (interactive)
3386 (insert
3387 org-deadline-string " "
3388 (format-time-string (car org-time-stamp-formats)
3389 (org-read-date nil 'to-time)))
3390 (message "%s" (substitute-command-keys
3391 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3392
3393 (defun org-schedule ()
3394 "Insert the SCHEDULED: string to schedule a TODO item.
3395 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3396 to modify it to the correct date."
3397 (interactive)
3398 (insert
3399 org-scheduled-string " "
3400 (format-time-string (car org-time-stamp-formats)
3401 (org-read-date nil 'to-time)))
3402 (message "%s" (substitute-command-keys
3403 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3404
3405
3406 (defun org-occur (regexp &optional callback)
3407 "Make a compact tree which shows all matches of REGEXP.
3408 The tree will show the lines where the regexp matches, and all higher
3409 headlines above the match. It will also show the heading after the match,
3410 to make sure editing the matching entry is easy.
3411 if CALLBACK is non-nil, it is a function which is called to confirm
3412 that the match should indeed be shown."
3413 (interactive "sRegexp: ")
3414 (org-remove-occur-highlights nil nil t)
3415 (setq regexp (org-check-occur-regexp regexp))
3416 (let ((cnt 0))
3417 (save-excursion
3418 (goto-char (point-min))
3419 (hide-sublevels 1)
3420 (while (re-search-forward regexp nil t)
3421 (when (or (not callback)
3422 (save-match-data (funcall callback)))
3423 (setq cnt (1+ cnt))
3424 (org-highlight-new-match (match-beginning 0) (match-end 0))
3425 (add-hook 'before-change-functions 'org-remove-occur-highlights
3426 nil 'local)
3427 (org-show-hierarchy-above))))
3428 (run-hooks 'org-occur-hook)
3429 (if (interactive-p)
3430 (message "%d match(es) for regexp %s" cnt regexp))
3431 cnt))
3432
3433 (defun org-show-hierarchy-above ()
3434 "Make sure point and the headings hierarchy above is visible."
3435 (if (org-on-heading-p t)
3436 (org-flag-heading nil) ; only show the heading
3437 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3438 (save-excursion
3439 (and org-show-following-heading
3440 (outline-next-heading)
3441 (org-flag-heading nil))) ; show the next heading
3442 (when org-show-hierarchy-above
3443 (save-excursion ; show all higher headings
3444 (while (condition-case nil
3445 (progn (org-up-heading-all 1) t)
3446 (error nil))
3447 (org-flag-heading nil)))))
3448
3449 (defvar org-occur-highlights nil)
3450 (defun org-highlight-new-match (beg end)
3451 "Highlight from BEG to END and mark the highlight is an occur headline."
3452 (let ((ov (make-overlay beg end)))
3453 (overlay-put ov 'face 'secondary-selection)
3454 (push ov org-occur-highlights)))
3455
3456 (defun org-remove-occur-highlights (&optional beg end noremove)
3457 "Remove the occur highlights from the buffer.
3458 BEG and END are ignored. If NOREMOVE is nil, remove this function
3459 from the before-change-functions in the current buffer."
3460 (interactive)
3461 (mapc 'delete-overlay org-occur-highlights)
3462 (setq org-occur-highlights nil)
3463 (unless noremove
3464 (remove-hook 'before-change-functions
3465 'org-remove-occur-highlights 'local)))
3466
3467 ;;; Priorities
3468
3469 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3470 "Regular expression matching the priority indicator.")
3471
3472 (defvar org-remove-priority-next-time nil)
3473
3474 (defun org-priority-up ()
3475 "Increase the priority of the current item."
3476 (interactive)
3477 (org-priority 'up))
3478
3479 (defun org-priority-down ()
3480 "Decrease the priority of the current item."
3481 (interactive)
3482 (org-priority 'down))
3483
3484 (defun org-priority (&optional action)
3485 "Change the priority of an item by ARG.
3486 ACTION can be set, up, or down."
3487 (interactive)
3488 (setq action (or action 'set))
3489 (let (current new news have remove)
3490 (save-excursion
3491 (org-back-to-heading)
3492 (if (looking-at org-priority-regexp)
3493 (setq current (string-to-char (match-string 2))
3494 have t)
3495 (setq current org-default-priority))
3496 (cond
3497 ((eq action 'set)
3498 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3499 (setq new (read-char-exclusive))
3500 (cond ((equal new ?\ ) (setq remove t))
3501 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3502 (error "Priority must be between `%c' and `%c'"
3503 ?A org-lowest-priority))))
3504 ((eq action 'up)
3505 (setq new (1- current)))
3506 ((eq action 'down)
3507 (setq new (1+ current)))
3508 (t (error "Invalid action")))
3509 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3510 (setq news (format "%c" new))
3511 (if have
3512 (if remove
3513 (replace-match "" t t nil 1)
3514 (replace-match news t t nil 2))
3515 (if remove
3516 (error "No priority cookie found in line")
3517 (looking-at org-todo-line-regexp)
3518 (if (match-end 2)
3519 (progn
3520 (goto-char (match-end 2))
3521 (insert " [#" news "]"))
3522 (goto-char (match-beginning 3))
3523 (insert "[#" news "] ")))))
3524 (if remove
3525 (message "Priority removed")
3526 (message "Priority of current item set to %s" news))))
3527
3528
3529 (defun org-get-priority (s)
3530 "Find priority cookie and return priority."
3531 (save-match-data
3532 (if (not (string-match org-priority-regexp s))
3533 (* 1000 (- org-lowest-priority org-default-priority))
3534 (* 1000 (- org-lowest-priority
3535 (string-to-char (match-string 2 s)))))))
3536
3537 ;;; Timestamps
3538
3539 (defvar org-last-changed-timestamp nil)
3540
3541 (defun org-time-stamp (arg)
3542 "Prompt for a date/time and insert a time stamp.
3543 If the user specifies a time like HH:MM, or if this command is called
3544 with a prefix argument, the time stamp will contain date and time.
3545 Otherwise, only the date will be included. All parts of a date not
3546 specified by the user will be filled in from the current date/time.
3547 So if you press just return without typing anything, the time stamp
3548 will represent the current date/time. If there is already a timestamp
3549 at the cursor, it will be modified."
3550 (interactive "P")
3551 (let ((fmt (if arg (cdr org-time-stamp-formats)
3552 (car org-time-stamp-formats)))
3553 (org-time-was-given nil)
3554 time)
3555 (cond
3556 ((and (org-at-timestamp-p)
3557 (eq last-command 'org-time-stamp)
3558 (eq this-command 'org-time-stamp))
3559 (insert "--")
3560 (setq time (let ((this-command this-command))
3561 (org-read-date arg 'totime)))
3562 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3563 (insert (format-time-string fmt time)))
3564 ((org-at-timestamp-p)
3565 (setq time (let ((this-command this-command))
3566 (org-read-date arg 'totime)))
3567 (and (org-at-timestamp-p) (replace-match
3568 (setq org-last-changed-timestamp
3569 (format-time-string fmt time))
3570 t t))
3571 (message "Timestamp updated"))
3572 (t
3573 (setq time (let ((this-command this-command))
3574 (org-read-date arg 'totime)))
3575 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3576 (insert (format-time-string fmt time))))))
3577
3578 (defun org-time-stamp-inactive (&optional arg)
3579 "Insert an inactive time stamp.
3580 An inactive time stamp is enclosed in square brackets instead of angle
3581 brackets. It is inactive in the sense that it does not trigger agenda entries,
3582 does not link to the calendar and cannot be changed with the S-cursor keys."
3583 (interactive "P")
3584 (let ((fmt (if arg (cdr org-time-stamp-formats)
3585 (car org-time-stamp-formats)))
3586 (org-time-was-given nil)
3587 time)
3588 (setq time (org-read-date arg 'totime))
3589 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3590 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3591 (insert (format-time-string fmt time))))
3592
3593 ;;; FIXME: Make the function take "Fri" as "next friday"
3594 (defun org-read-date (&optional with-time to-time)
3595 "Read a date and make things smooth for the user.
3596 The prompt will suggest to enter an ISO date, but you can also enter anything
3597 which will at least partially be understood by `parse-time-string'.
3598 Unrecognized parts of the date will default to the current day, month ,year,
3599 hour and minute. For example,
3600 3-2-5 --> 2003-02-05
3601 feb 15 --> currentyear-02-15
3602 sep 12 9 --> 2009-09-12
3603 12:45 --> today 12:45
3604 22 sept 0:34 --> currentyear-09-22 0:34
3605 12 --> currentyear-currentmonth-12
3606 etc.
3607 The function understands only English month and weekday abbreviations,
3608 but this can be configured with the variables `parse-time-months' and
3609 `parse-time-weekdays'.
3610
3611 While prompting, a calendar is popped up - you can also select the
3612 date with the mouse (button 1). The calendar shows a period of three
3613 month. To scroll it to other months, use the keys `>' and `<'.
3614 If you don't like the calendar, turn it off with
3615 \(setq org-popup-calendar-for-date-prompt nil).
3616
3617 With optional argument TO-TIME, the date will immediately be converted
3618 to an internal time.
3619 With an optional argument WITH-TIME, the prompt will suggest to also
3620 insert a time. Note that when WITH-TIME is not set, you can still
3621 enter a time, and this function will inform the calling routine about
3622 this change. The calling routine may then choose to change the format
3623 used to insert the time stamp into the buffer to include the time."
3624 (let* ((default-time
3625 ;; Default time is either today, or, when entering a range,
3626 ;; the range start.
3627 (if (save-excursion
3628 (re-search-backward
3629 (concat org-ts-regexp "--\\=")
3630 (- (point) 20) t))
3631 (apply
3632 'encode-time
3633 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3634 (parse-time-string (match-string 1))))
3635 (current-time)))
3636 (calendar-move-hook nil)
3637 (view-diary-entries-initially nil)
3638 (timestr (format-time-string
3639 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3640 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3641 ans ans1 ans2
3642 second minute hour day month year tl)
3643
3644 (if org-popup-calendar-for-date-prompt
3645 ;; Also show a calendar for date selection
3646 ;; Copied (with modifications) from planner.el by John Wiegley
3647 (save-excursion
3648 (save-window-excursion
3649 (calendar)
3650 (calendar-forward-day (- (time-to-days default-time)
3651 (calendar-absolute-from-gregorian
3652 (calendar-current-date))))
3653 (let* ((old-map (current-local-map))
3654 (map (copy-keymap calendar-mode-map))
3655 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3656 (define-key map (kbd "RET") 'org-calendar-select)
3657 (define-key map (if org-xemacs-p [button1] [mouse-1])
3658 'org-calendar-select)
3659 (define-key minibuffer-local-map [(meta shift left)]
3660 (lambda () (interactive)
3661 (org-eval-in-calendar '(calendar-backward-month 1))))
3662 (define-key minibuffer-local-map [(meta shift right)]
3663 (lambda () (interactive)
3664 (org-eval-in-calendar '(calendar-forward-month 1))))
3665 (define-key minibuffer-local-map [(shift up)]
3666 (lambda () (interactive)
3667 (org-eval-in-calendar '(calendar-backward-week 1))))
3668 (define-key minibuffer-local-map [(shift down)]
3669 (lambda () (interactive)
3670 (org-eval-in-calendar '(calendar-forward-week 1))))
3671 (define-key minibuffer-local-map [(shift left)]
3672 (lambda () (interactive)
3673 (org-eval-in-calendar '(calendar-backward-day 1))))
3674 (define-key minibuffer-local-map [(shift right)]
3675 (lambda () (interactive)
3676 (org-eval-in-calendar '(calendar-forward-day 1))))
3677 (define-key minibuffer-local-map ">"
3678 (lambda () (interactive)
3679 (org-eval-in-calendar '(scroll-calendar-left 1))))
3680 (define-key minibuffer-local-map "<"
3681 (lambda () (interactive)
3682 (org-eval-in-calendar '(scroll-calendar-right 1))))
3683 (unwind-protect
3684 (progn
3685 (use-local-map map)
3686 (setq ans (read-string prompt "" nil nil))
3687 (setq ans (or ans1 ans2 ans)))
3688 (use-local-map old-map)))))
3689 ;; Naked prompt only
3690 (setq ans (read-string prompt "" nil timestr)))
3691
3692 (if (string-match
3693 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3694 (progn
3695 (setq year (if (match-end 2)
3696 (string-to-number (match-string 2 ans))
3697 (string-to-number (format-time-string "%Y")))
3698 month (string-to-number (match-string 3 ans))
3699 day (string-to-number (match-string 4 ans)))
3700 (if (< year 100) (setq year (+ 2000 year)))
3701 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3702 t t ans))))
3703 (setq tl (parse-time-string ans)
3704 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3705 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3706 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3707 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3708 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3709 second (or (nth 0 tl) 0))
3710 (if (and (boundp 'org-time-was-given)
3711 (nth 2 tl))
3712 (setq org-time-was-given t))
3713 (if (< year 100) (setq year (+ 2000 year)))
3714 (if to-time
3715 (encode-time second minute hour day month year)
3716 (if (or (nth 1 tl) (nth 2 tl))
3717 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3718 (format "%04d-%02d-%02d" year month day)))))
3719
3720 (defun org-eval-in-calendar (form)
3721 "Eval FORM in the calendar window and return to current window.
3722 Also, store the cursor date in variable ans2."
3723 (let ((sw (selected-window)))
3724 (select-window (get-buffer-window "*Calendar*"))
3725 (eval form)
3726 (when (calendar-cursor-to-date)
3727 (let* ((date (calendar-cursor-to-date))
3728 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3729 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3730 (select-window sw)))
3731
3732 (defun org-calendar-select ()
3733 "Return to `org-read-date' with the date currently selected.
3734 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3735 (interactive)
3736 (when (calendar-cursor-to-date)
3737 (let* ((date (calendar-cursor-to-date))
3738 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3739 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3740 (if (active-minibuffer-window) (exit-minibuffer))))
3741
3742 (defun org-check-deadlines (ndays)
3743 "Check if there are any deadlines due or past due.
3744 A deadline is considered due if it happens within `org-deadline-warning-days'
3745 days from today's date. If the deadline appears in an entry marked DONE,
3746 it is not shown. The prefix arg NDAYS can be used to test that many
3747 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3748 (interactive "P")
3749 (let* ((org-warn-days
3750 (cond
3751 ((equal ndays '(4)) 100000)
3752 (ndays (prefix-numeric-value ndays))
3753 (t org-deadline-warning-days)))
3754 (case-fold-search nil)
3755 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3756 (callback
3757 (lambda ()
3758 (and (let ((d1 (time-to-days (current-time)))
3759 (d2 (time-to-days
3760 (org-time-string-to-time (match-string 1)))))
3761 (< (- d2 d1) org-warn-days))
3762 (not (org-entry-is-done-p))))))
3763 (message "%d deadlines past-due or due within %d days"
3764 (org-occur regexp callback)
3765 org-warn-days)))
3766
3767 (defun org-evaluate-time-range (&optional to-buffer)
3768 "Evaluate a time range by computing the difference between start and end.
3769 Normally the result is just printed in the echo area, but with prefix arg
3770 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3771 If the time range is actually in a table, the result is inserted into the
3772 next column.
3773 For time difference computation, a year is assumed to be exactly 365
3774 days in order to avoid rounding problems."
3775 (interactive "P")
3776 (save-excursion
3777 (unless (org-at-date-range-p)
3778 (goto-char (point-at-bol))
3779 (re-search-forward org-tr-regexp (point-at-eol) t))
3780 (if (not (org-at-date-range-p))
3781 (error "Not at a time-stamp range, and none found in current line")))
3782 (let* ((ts1 (match-string 1))
3783 (ts2 (match-string 2))
3784 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3785 (match-end (match-end 0))
3786 (time1 (org-time-string-to-time ts1))
3787 (time2 (org-time-string-to-time ts2))
3788 (t1 (time-to-seconds time1))
3789 (t2 (time-to-seconds time2))
3790 (diff (abs (- t2 t1)))
3791 (negative (< (- t2 t1) 0))
3792 ;; (ys (floor (* 365 24 60 60)))
3793 (ds (* 24 60 60))
3794 (hs (* 60 60))
3795 (fy "%dy %dd %02d:%02d")
3796 (fy1 "%dy %dd")
3797 (fd "%dd %02d:%02d")
3798 (fd1 "%dd")
3799 (fh "%02d:%02d")
3800 y d h m align)
3801 ;; FIXME: Should I re-introduce years, make year refer to same date?
3802 ;; This would be the only useful way to have years, actually.
3803 (if havetime
3804 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3805 y 0
3806 d (floor (/ diff ds)) diff (mod diff ds)
3807 h (floor (/ diff hs)) diff (mod diff hs)
3808 m (floor (/ diff 60)))
3809 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3810 y 0
3811 d (floor (+ (/ diff ds) 0.5))
3812 h 0 m 0))
3813 (if (not to-buffer)
3814 (message (org-make-tdiff-string y d h m))
3815 (when (org-at-table-p)
3816 (goto-char match-end)
3817 (setq align t)
3818 (and (looking-at " *|") (goto-char (match-end 0))))
3819 (if (looking-at
3820 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3821 (replace-match ""))
3822 (if negative (insert " -"))
3823 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3824 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3825 (insert " " (format fh h m))))
3826 (if align (org-table-align))
3827 (message "Time difference inserted"))))
3828
3829 (defun org-make-tdiff-string (y d h m)
3830 (let ((fmt "")
3831 (l nil))
3832 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3833 l (push y l)))
3834 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3835 l (push d l)))
3836 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3837 l (push h l)))
3838 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3839 l (push m l)))
3840 (apply 'format fmt (nreverse l))))
3841
3842 (defun org-time-string-to-time (s)
3843 (apply 'encode-time (org-parse-time-string s)))
3844
3845 (defun org-parse-time-string (s &optional nodefault)
3846 "Parse the standard Org-mode time string.
3847 This should be a lot faster than the normal `parse-time-string'.
3848 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3849 hour and minute fields will be nil if not given."
3850 (if (string-match org-ts-regexp1 s)
3851 (list 0
3852 (if (or (match-beginning 8) (not nodefault))
3853 (string-to-number (or (match-string 8 s) "0")))
3854 (if (or (match-beginning 7) (not nodefault))
3855 (string-to-number (or (match-string 7 s) "0")))
3856 (string-to-number (match-string 4 s))
3857 (string-to-number (match-string 3 s))
3858 (string-to-number (match-string 2 s))
3859 nil nil nil)
3860 (make-list 9 0)))
3861
3862 (defun org-timestamp-up (&optional arg)
3863 "Increase the date item at the cursor by one.
3864 If the cursor is on the year, change the year. If it is on the month or
3865 the day, change that.
3866 With prefix ARG, change by that many units."
3867 (interactive "p")
3868 (org-timestamp-change (prefix-numeric-value arg)))
3869
3870 (defun org-timestamp-down (&optional arg)
3871 "Decrease the date item at the cursor by one.
3872 If the cursor is on the year, change the year. If it is on the month or
3873 the day, change that.
3874 With prefix ARG, change by that many units."
3875 (interactive "p")
3876 (org-timestamp-change (- (prefix-numeric-value arg))))
3877
3878 (defun org-timestamp-up-day (&optional arg)
3879 "Increase the date in the time stamp by one day.
3880 With prefix ARG, change that many days."
3881 (interactive "p")
3882 (if (and (not (org-at-timestamp-p))
3883 (org-on-heading-p))
3884 (org-todo 'up)
3885 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3886
3887 (defun org-timestamp-down-day (&optional arg)
3888 "Decrease the date in the time stamp by one day.
3889 With prefix ARG, change that many days."
3890 (interactive "p")
3891 (if (and (not (org-at-timestamp-p))
3892 (org-on-heading-p))
3893 (org-todo 'down)
3894 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3895
3896 (defsubst org-pos-in-match-range (pos n)
3897 (and (match-beginning n)
3898 (<= (match-beginning n) pos)
3899 (>= (match-end n) pos)))
3900
3901 (defun org-at-timestamp-p ()
3902 "Determine if the cursor is in or at a timestamp."
3903 (interactive)
3904 (let* ((tsr org-ts-regexp2)
3905 (pos (point))
3906 (ans (or (looking-at tsr)
3907 (save-excursion
3908 (skip-chars-backward "^<\n\r\t")
3909 (if (> (point) 1) (backward-char 1))
3910 (and (looking-at tsr)
3911 (> (- (match-end 0) pos) -1))))))
3912 (and (boundp 'org-ts-what)
3913 (setq org-ts-what
3914 (cond
3915 ((org-pos-in-match-range pos 2) 'year)
3916 ((org-pos-in-match-range pos 3) 'month)
3917 ((org-pos-in-match-range pos 7) 'hour)
3918 ((org-pos-in-match-range pos 8) 'minute)
3919 ((or (org-pos-in-match-range pos 4)
3920 (org-pos-in-match-range pos 5)) 'day)
3921 (t 'day))))
3922 ans))
3923
3924 (defun org-timestamp-change (n &optional what)
3925 "Change the date in the time stamp at point.
3926 The date will be changed by N times WHAT. WHAT can be `day', `month',
3927 `year', `minute', `second'. If WHAT is not given, the cursor position
3928 in the timestamp determines what will be changed."
3929 (let ((fmt (car org-time-stamp-formats))
3930 org-ts-what
3931 (pos (point))
3932 ts time time0)
3933 (if (not (org-at-timestamp-p))
3934 (error "Not at a timestamp"))
3935 (setq org-ts-what (or what org-ts-what))
3936 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3937 (- (match-end 0) (match-beginning 0))))
3938 1)
3939 (cdr org-time-stamp-formats)
3940 (car org-time-stamp-formats)))
3941 (setq ts (match-string 0))
3942 (replace-match "")
3943 (setq time0 (org-parse-time-string ts))
3944 (setq time
3945 (apply 'encode-time
3946 (append
3947 (list (or (car time0) 0))
3948 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3949 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3950 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3951 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3952 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3953 (nthcdr 6 time0))))
3954 (if (eq what 'calendar)
3955 (let ((cal-date
3956 (save-excursion
3957 (save-match-data
3958 (set-buffer "*Calendar*")
3959 (calendar-cursor-to-date)))))
3960 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3961 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3962 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3963 (setcar time0 (or (car time0) 0))
3964 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3965 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3966 (setq time (apply 'encode-time time0))))
3967 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3968 (goto-char pos)
3969 ;; Try to recenter the calendar window, if any
3970 (if (and org-calendar-follow-timestamp-change
3971 (get-buffer-window "*Calendar*" t)
3972 (memq org-ts-what '(day month year)))
3973 (org-recenter-calendar (time-to-days time)))))
3974
3975 (defun org-recenter-calendar (date)
3976 "If the calendar is visible, recenter it to DATE."
3977 (let* ((win (selected-window))
3978 (cwin (get-buffer-window "*Calendar*" t))
3979 (calendar-move-hook nil))
3980 (when cwin
3981 (select-window cwin)
3982 (calendar-goto-date (if (listp date) date
3983 (calendar-gregorian-from-absolute date)))
3984 (select-window win))))
3985
3986 (defun org-goto-calendar (&optional arg)
3987 "Go to the Emacs calendar at the current date.
3988 If there is a time stamp in the current line, go to that date.
3989 A prefix ARG can be used force the current date."
3990 (interactive "P")
3991 (let ((tsr org-ts-regexp) diff
3992 (calendar-move-hook nil)
3993 (view-diary-entries-initially nil))
3994 (if (or (org-at-timestamp-p)
3995 (save-excursion
3996 (beginning-of-line 1)
3997 (looking-at (concat ".*" tsr))))
3998 (let ((d1 (time-to-days (current-time)))
3999 (d2 (time-to-days
4000 (org-time-string-to-time (match-string 1)))))
4001 (setq diff (- d2 d1))))
4002 (calendar)
4003 (calendar-goto-today)
4004 (if (and diff (not arg)) (calendar-forward-day diff))))
4005
4006 (defun org-date-from-calendar ()
4007 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4008 If there is already a time stamp at the cursor position, update it."
4009 (interactive)
4010 (org-timestamp-change 0 'calendar))
4011
4012 ;;; Agenda, and Diary Integration
4013
4014 ;;; Define the mode
4015
4016 (defvar org-agenda-mode-map (make-sparse-keymap)
4017 "Keymap for `org-agenda-mode'.")
4018
4019 (defvar org-agenda-menu)
4020 (defvar org-agenda-follow-mode nil)
4021 (defvar org-agenda-buffer-name "*Org Agenda*")
4022 (defvar org-agenda-redo-command nil)
4023 (defvar org-agenda-mode-hook nil)
4024
4025 ;;;###autoload
4026 (defun org-agenda-mode ()
4027 "Mode for time-sorted view on action items in Org-mode files.
4028
4029 The following commands are available:
4030
4031 \\{org-agenda-mode-map}"
4032 (interactive)
4033 (kill-all-local-variables)
4034 (setq major-mode 'org-agenda-mode)
4035 (setq mode-name "Org-Agenda")
4036 (use-local-map org-agenda-mode-map)
4037 (easy-menu-add org-agenda-menu)
4038 (if org-startup-truncated (setq truncate-lines t))
4039 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4040 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4041 (setq org-agenda-follow-mode nil)
4042 (easy-menu-change
4043 '("Agenda") "Agenda Files"
4044 (append
4045 (list
4046 ["Edit File List" (customize-variable 'org-agenda-files) t]
4047 "--")
4048 (mapcar 'org-file-menu-entry org-agenda-files)))
4049 (org-agenda-set-mode-name)
4050 (apply
4051 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4052 org-agenda-mode-hook))
4053
4054 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4055 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4056 (define-key org-agenda-mode-map " " 'org-agenda-show)
4057 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4058 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4059 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
4060 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4061 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4062 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4063 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4064 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4065 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4066 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4067 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4068
4069 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4070 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4071 (while l (define-key org-agenda-mode-map
4072 (int-to-string (pop l)) 'digit-argument)))
4073
4074 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4075 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4076 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4077 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4078 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4079 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4080 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4081 (define-key org-agenda-mode-map "n" 'next-line)
4082 (define-key org-agenda-mode-map "p" 'previous-line)
4083 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4084 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4085 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4086 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4087 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4088 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4089 (eval-after-load "calendar"
4090 '(define-key calendar-mode-map org-calendar-to-agenda-key
4091 'org-calendar-goto-agenda))
4092 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4093 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4094 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4095 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4096 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4097 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4098 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4099 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4100 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4101 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4102 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4103 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4104 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4105 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4106 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4107 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4108 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4109 "Local keymap for agenda entries from Org-mode.")
4110
4111 (define-key org-agenda-keymap
4112 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4113 (define-key org-agenda-keymap
4114 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4115
4116 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4117 '("Agenda"
4118 ("Agenda Files")
4119 "--"
4120 ["Show" org-agenda-show t]
4121 ["Go To (other window)" org-agenda-goto t]
4122 ["Go To (one window)" org-agenda-switch-to t]
4123 ["Follow Mode" org-agenda-follow-mode
4124 :style toggle :selected org-agenda-follow-mode :active t]
4125 "--"
4126 ["Cycle TODO" org-agenda-todo t]
4127 ("Reschedule"
4128 ["Reschedule +1 day" org-agenda-date-later t]
4129 ["Reschedule -1 day" org-agenda-date-earlier t]
4130 "--"
4131 ["Reschedule to ..." org-agenda-date-prompt t])
4132 ("Priority"
4133 ["Set Priority" org-agenda-priority t]
4134 ["Increase Priority" org-agenda-priority-up t]
4135 ["Decrease Priority" org-agenda-priority-down t]
4136 ["Show Priority" org-agenda-show-priority t])
4137 "--"
4138 ["Rebuild buffer" org-agenda-redo t]
4139 ["Goto Today" org-agenda-goto-today t]
4140 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
4141 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
4142 "--"
4143 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
4144 :style radio :selected (equal org-agenda-ndays 1)]
4145 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
4146 :style radio :selected (equal org-agenda-ndays 7)]
4147 "--"
4148 ["Include Diary" org-agenda-toggle-diary
4149 :style toggle :selected org-agenda-include-diary :active t]
4150 ["Use Time Grid" org-agenda-toggle-time-grid
4151 :style toggle :selected org-agenda-use-time-grid :active t]
4152 "--"
4153 ["New Diary Entry" org-agenda-diary-entry t]
4154 ("Calendar Commands"
4155 ["Goto Calendar" org-agenda-goto-calendar t]
4156 ["Phases of the Moon" org-agenda-phases-of-moon t]
4157 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
4158 ["Holidays" org-agenda-holidays t]
4159 ["Convert" org-agenda-convert-date t])
4160 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4161 "--"
4162 ["Quit" org-agenda-quit t]
4163 ["Exit and Release Buffers" org-agenda-exit t]
4164 ))
4165
4166 (defvar org-agenda-markers nil
4167 "List of all currently active markers created by `org-agenda'.")
4168 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4169 "Creation time of the last agenda marker.")
4170
4171 (defun org-agenda-new-marker (&optional pos)
4172 "Return a new agenda marker.
4173 Org-mode keeps a list of these markers and resets them when they are
4174 no longer in use."
4175 (let ((m (copy-marker (or pos (point)))))
4176 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4177 (push m org-agenda-markers)
4178 m))
4179
4180 (defun org-agenda-maybe-reset-markers (&optional force)
4181 "Reset markers created by `org-agenda'. But only if they are old enough."
4182 (if (or force
4183 (> (- (time-to-seconds (current-time))
4184 org-agenda-last-marker-time)
4185 5))
4186 (while org-agenda-markers
4187 (move-marker (pop org-agenda-markers) nil))))
4188
4189 (defvar org-agenda-new-buffers nil
4190 "Buffers created to visit agenda files.")
4191
4192 (defun org-get-agenda-file-buffer (file)
4193 "Get a buffer visiting FILE. If the buffer needs to be created, add
4194 it to the list of buffers which might be released later."
4195 (let ((buf (find-buffer-visiting file)))
4196 (if buf
4197 buf ; just return it
4198 ;; Make a new buffer and remember it
4199 (setq buf (find-file-noselect file))
4200 (if buf (push buf org-agenda-new-buffers))
4201 buf)))
4202
4203 (defun org-release-buffers (blist)
4204 "Release all buffers in list, asking the user for confirmation when needed.
4205 When a buffer is unmodified, it is just killed. When modified, it is saved
4206 \(if the user agrees) and then killed."
4207 (let (buf file)
4208 (while (setq buf (pop blist))
4209 (setq file (buffer-file-name buf))
4210 (when (and (buffer-modified-p buf)
4211 file
4212 (y-or-n-p (format "Save file %s? " file)))
4213 (with-current-buffer buf (save-buffer)))
4214 (kill-buffer buf))))
4215
4216 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4217
4218 (defun org-timeline (&optional include-all)
4219 "Show a time-sorted view of the entries in the current org file.
4220 Only entries with a time stamp of today or later will be listed. With
4221 one \\[universal-argument] prefix argument, past entries will also be listed.
4222 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
4223 under the current date.
4224 If the buffer contains an active region, only check the region for
4225 dates."
4226 (interactive "P")
4227 (require 'calendar)
4228 (org-agenda-maybe-reset-markers 'force)
4229 (org-compile-prefix-format org-timeline-prefix-format)
4230 (let* ((dopast include-all)
4231 (dotodo (equal include-all '(16)))
4232 (entry (buffer-file-name))
4233 (org-agenda-files (list (buffer-file-name)))
4234 (date (calendar-current-date))
4235 (win (selected-window))
4236 (pos1 (point))
4237 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4238 (end (if (org-region-active-p) (region-end) (point-max)))
4239 (day-numbers (org-get-all-dates beg end 'no-ranges
4240 t)) ; always include today
4241 (today (time-to-days (current-time)))
4242 (org-respect-restriction t)
4243 (past t)
4244 s e rtn d)
4245 (setq org-agenda-redo-command
4246 (list 'progn
4247 (list 'switch-to-buffer-other-window (current-buffer))
4248 (list 'org-timeline (list 'quote include-all))))
4249 (if (not dopast)
4250 ;; Remove past dates from the list of dates.
4251 (setq day-numbers (delq nil (mapcar (lambda(x)
4252 (if (>= x today) x nil))
4253 day-numbers))))
4254 (switch-to-buffer-other-window
4255 (get-buffer-create org-agenda-buffer-name))
4256 (setq buffer-read-only nil)
4257 (erase-buffer)
4258 (org-agenda-mode) (setq buffer-read-only nil)
4259 (while (setq d (pop day-numbers))
4260 (if (and (>= d today)
4261 dopast
4262 past)
4263 (progn
4264 (setq past nil)
4265 (insert (make-string 79 ?-) "\n")))
4266 (setq date (calendar-gregorian-from-absolute d))
4267 (setq s (point))
4268 (if dotodo
4269 (setq rtn (org-agenda-get-day-entries
4270 entry date :todo :timestamp))
4271 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
4272 (if (or rtn (equal d today))
4273 (progn
4274 (insert (calendar-day-name date) " "
4275 (number-to-string (extract-calendar-day date)) " "
4276 (calendar-month-name (extract-calendar-month date)) " "
4277 (number-to-string (extract-calendar-year date)) "\n")
4278 (put-text-property s (1- (point)) 'face
4279 'org-link)
4280 (if (equal d today)
4281 (put-text-property s (1- (point)) 'org-today t))
4282 (insert (org-finalize-agenda-entries rtn) "\n")
4283 (put-text-property s (1- (point)) 'day d))))
4284 (goto-char (point-min))
4285 (setq buffer-read-only t)
4286 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4287 (point-min)))
4288 (when (not org-select-timeline-window)
4289 (select-window win)
4290 (goto-char pos1))))
4291
4292 ;;;###autoload
4293 (defun org-agenda (&optional include-all start-day ndays)
4294 "Produce a weekly view from all files in variable `org-agenda-files'.
4295 The view will be for the current week, but from the overview buffer you
4296 will be able to go to other weeks.
4297 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4298 also be shown, under the current date.
4299 START-DAY defaults to TODAY, or to the most recent match for the weekday
4300 given in `org-agenda-start-on-weekday'.
4301 NDAYS defaults to `org-agenda-ndays'."
4302 (interactive "P")
4303 (org-agenda-maybe-reset-markers 'force)
4304 (org-compile-prefix-format org-agenda-prefix-format)
4305 (require 'calendar)
4306 (let* ((org-agenda-start-on-weekday
4307 (if (or (equal ndays 1)
4308 (and (null ndays) (equal 1 org-agenda-ndays)))
4309 nil org-agenda-start-on-weekday))
4310 (files (copy-sequence org-agenda-files))
4311 (win (selected-window))
4312 (today (time-to-days (current-time)))
4313 (sd (or start-day today))
4314 (start (if (or (null org-agenda-start-on-weekday)
4315 (< org-agenda-ndays 7))
4316 sd
4317 (let* ((nt (calendar-day-of-week
4318 (calendar-gregorian-from-absolute sd)))
4319 (n1 org-agenda-start-on-weekday)
4320 (d (- nt n1)))
4321 (- sd (+ (if (< d 0) 7 0) d)))))
4322 (day-numbers (list start))
4323 (inhibit-redisplay t)
4324 s e rtn rtnall file date d start-pos end-pos todayp nd)
4325 (setq org-agenda-redo-command
4326 (list 'org-agenda (list 'quote include-all) start-day ndays))
4327 ;; Make the list of days
4328 (setq ndays (or ndays org-agenda-ndays)
4329 nd ndays)
4330 (while (> ndays 1)
4331 (push (1+ (car day-numbers)) day-numbers)
4332 (setq ndays (1- ndays)))
4333 (setq day-numbers (nreverse day-numbers))
4334 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4335 (progn
4336 (delete-other-windows)
4337 (switch-to-buffer-other-window
4338 (get-buffer-create org-agenda-buffer-name))))
4339 (setq buffer-read-only nil)
4340 (erase-buffer)
4341 (org-agenda-mode) (setq buffer-read-only nil)
4342 (set (make-local-variable 'starting-day) (car day-numbers))
4343 (set (make-local-variable 'include-all-loc) include-all)
4344 (when (and (or include-all org-agenda-include-all-todo)
4345 (member today day-numbers))
4346 (setq files org-agenda-files
4347 rtnall nil)
4348 (while (setq file (pop files))
4349 (catch 'nextfile
4350 (org-check-agenda-file file)
4351 (setq date (calendar-gregorian-from-absolute today)
4352 rtn (org-agenda-get-day-entries
4353 file date :todo))
4354 (setq rtnall (append rtnall rtn))))
4355 (when rtnall
4356 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4357 (add-text-properties (point-min) (1- (point))
4358 (list 'face 'org-link))
4359 (insert (org-finalize-agenda-entries rtnall) "\n")))
4360 (while (setq d (pop day-numbers))
4361 (setq date (calendar-gregorian-from-absolute d)
4362 s (point))
4363 (if (or (setq todayp (= d today))
4364 (and (not start-pos) (= d sd)))
4365 (setq start-pos (point))
4366 (if (and start-pos (not end-pos))
4367 (setq end-pos (point))))
4368 (setq files org-agenda-files
4369 rtnall nil)
4370 (while (setq file (pop files))
4371 (catch 'nextfile
4372 (org-check-agenda-file file)
4373 (setq rtn (org-agenda-get-day-entries file date))
4374 (setq rtnall (append rtnall rtn))))
4375 (if org-agenda-include-diary
4376 (progn
4377 (require 'diary-lib)
4378 (setq rtn (org-get-entries-from-diary date))
4379 (setq rtnall (append rtnall rtn))))
4380 (if (or rtnall org-agenda-show-all-dates)
4381 (progn
4382 (insert (format "%-9s %2d %s %4d\n"
4383 (calendar-day-name date)
4384 (extract-calendar-day date)
4385 (calendar-month-name (extract-calendar-month date))
4386 (extract-calendar-year date)))
4387 (put-text-property s (1- (point)) 'face
4388 'org-link)
4389 (if rtnall (insert
4390 (org-finalize-agenda-entries
4391 (org-agenda-add-time-grid-maybe
4392 rtnall nd todayp))
4393 "\n"))
4394 (put-text-property s (1- (point)) 'day d))))
4395 (goto-char (point-min))
4396 (setq buffer-read-only t)
4397 (if org-fit-agenda-window
4398 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4399 (/ (frame-height) 2)))
4400 (unless (and (pos-visible-in-window-p (point-min))
4401 (pos-visible-in-window-p (point-max)))
4402 (goto-char (1- (point-max)))
4403 (recenter -1)
4404 (if (not (pos-visible-in-window-p (or start-pos 1)))
4405 (progn
4406 (goto-char (or start-pos 1))
4407 (recenter 1))))
4408 (goto-char (or start-pos 1))
4409 (if (not org-select-agenda-window) (select-window win))
4410 (message "")))
4411
4412 (defvar org-select-this-todo-keyword nil)
4413
4414 ;;;###autoload
4415 (defun org-todo-list (arg)
4416 "Show all TODO entries from all agenda file in a single list.
4417 The prefix arg can be used to select a specific TODO keyword and limit
4418 the list to these. When using \\[universal-argument], you will be prompted
4419 for a keyword. A numeric prefix directly selects the Nth keyword in
4420 `org-todo-keywords'."
4421 (interactive "P")
4422 (org-agenda-maybe-reset-markers 'force)
4423 (org-compile-prefix-format org-agenda-prefix-format)
4424 (let* ((today (time-to-days (current-time)))
4425 (date (calendar-gregorian-from-absolute today))
4426 (win (selected-window))
4427 (kwds org-todo-keywords)
4428 (completion-ignore-case t)
4429 (org-select-this-todo-keyword
4430 (and arg (integerp arg) (nth (1- arg) org-todo-keywords)))
4431 rtn rtnall files file pos)
4432 (when (equal arg '(4))
4433 (setq org-select-this-todo-keyword
4434 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4435 nil t)))
4436 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4437 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4438 (progn
4439 (delete-other-windows)
4440 (switch-to-buffer-other-window
4441 (get-buffer-create org-agenda-buffer-name))))
4442 (setq buffer-read-only nil)
4443 (erase-buffer)
4444 (org-agenda-mode) (setq buffer-read-only nil)
4445 (set (make-local-variable 'last-arg) arg)
4446 (set (make-local-variable 'org-todo-keywords) kwds)
4447 (set (make-local-variable 'org-agenda-redo-command)
4448 '(org-todo-list (or current-prefix-arg last-arg)))
4449 (setq files org-agenda-files
4450 rtnall nil)
4451 (while (setq file (pop files))
4452 (catch 'nextfile
4453 (org-check-agenda-file file)
4454 (setq rtn (org-agenda-get-day-entries file date :todo))
4455 (setq rtnall (append rtnall rtn))))
4456 (insert "Global list of TODO items of type: ")
4457 (add-text-properties (point-min) (1- (point))
4458 (list 'face 'org-link))
4459 (setq pos (point))
4460 (insert (or org-select-this-todo-keyword "ALL") "\n")
4461 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4462 (when rtnall
4463 (insert (org-finalize-agenda-entries rtnall) "\n"))
4464 (goto-char (point-min))
4465 (setq buffer-read-only t)
4466 (if org-fit-agenda-window
4467 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4468 (/ (frame-height) 2)))
4469 (if (not org-select-agenda-window) (select-window win))))
4470
4471 (defun org-check-agenda-file (file)
4472 "Make sure FILE exists. If not, ask user what to do."
4473 ;; FIXME: this does not correctly change the menus
4474 ;; Could probably be fixed by explicitly going to the buffer.
4475 (when (not (file-exists-p file))
4476 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4477 file)
4478 (let ((r (downcase (read-char-exclusive))))
4479 (cond
4480 ((equal r ?r)
4481 (org-remove-file file)
4482 (throw 'nextfile t))
4483 (t (error "Abort"))))))
4484
4485 (defun org-agenda-quit ()
4486 "Exit agenda by removing the window or the buffer."
4487 (interactive)
4488 (let ((buf (current-buffer)))
4489 (if (not (one-window-p)) (delete-window))
4490 (kill-buffer buf)
4491 (org-agenda-maybe-reset-markers 'force)))
4492
4493 (defun org-agenda-exit ()
4494 "Exit agenda by removing the window or the buffer.
4495 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4496 Org-mode buffers visited directly by the user will not be touched."
4497 (interactive)
4498 (org-release-buffers org-agenda-new-buffers)
4499 (setq org-agenda-new-buffers nil)
4500 (org-agenda-quit))
4501
4502 (defun org-agenda-redo ()
4503 "Rebuild Agenda.
4504 When this is the global TODO list, a prefix argument will be interpreted."
4505 (interactive)
4506 (eval org-agenda-redo-command))
4507
4508 (defun org-agenda-goto-today ()
4509 "Go to today."
4510 (interactive)
4511 (if (boundp 'starting-day)
4512 (let ((cmd (car org-agenda-redo-command))
4513 (iall (nth 1 org-agenda-redo-command))
4514 (nday (nth 3 org-agenda-redo-command)))
4515 (eval (list cmd iall nil nday)))
4516 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4517 (point-min)))))
4518
4519 (defun org-agenda-later (arg)
4520 "Go forward in time by `org-agenda-ndays' days.
4521 With prefix ARG, go forward that many times `org-agenda-ndays'."
4522 (interactive "p")
4523 (unless (boundp 'starting-day)
4524 (error "Not allowed"))
4525 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4526 (+ starting-day (* arg org-agenda-ndays))))
4527
4528 (defun org-agenda-earlier (arg)
4529 "Go back in time by `org-agenda-ndays' days.
4530 With prefix ARG, go back that many times `org-agenda-ndays'."
4531 (interactive "p")
4532 (unless (boundp 'starting-day)
4533 (error "Not allowed"))
4534 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
4535 (- starting-day (* arg org-agenda-ndays))))
4536
4537 (defun org-agenda-week-view ()
4538 "Switch to weekly view for agenda."
4539 (interactive)
4540 (unless (boundp 'starting-day)
4541 (error "Not allowed"))
4542 (setq org-agenda-ndays 7)
4543 (org-agenda include-all-loc
4544 (or (get-text-property (point) 'day)
4545 starting-day))
4546 (org-agenda-set-mode-name)
4547 (message "Switched to week view"))
4548
4549 (defun org-agenda-day-view ()
4550 "Switch to weekly view for agenda."
4551 (interactive)
4552 (unless (boundp 'starting-day)
4553 (error "Not allowed"))
4554 (setq org-agenda-ndays 1)
4555 (org-agenda include-all-loc
4556 (or (get-text-property (point) 'day)
4557 starting-day))
4558 (org-agenda-set-mode-name)
4559 (message "Switched to day view"))
4560
4561 (defun org-agenda-next-date-line (&optional arg)
4562 "Jump to the next line indicating a date in agenda buffer."
4563 (interactive "p")
4564 (beginning-of-line 1)
4565 (if (looking-at "^\\S-") (forward-char 1))
4566 (if (not (re-search-forward "^\\S-" nil t arg))
4567 (progn
4568 (backward-char 1)
4569 (error "No next date after this line in this buffer")))
4570 (goto-char (match-beginning 0)))
4571
4572 (defun org-agenda-previous-date-line (&optional arg)
4573 "Jump to the next line indicating a date in agenda buffer."
4574 (interactive "p")
4575 (beginning-of-line 1)
4576 (if (not (re-search-backward "^\\S-" nil t arg))
4577 (error "No previous date before this line in this buffer")))
4578
4579 ;; Initialize the highlight
4580 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
4581 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
4582 'face 'highlight)
4583
4584 (defun org-highlight (begin end &optional buffer)
4585 "Highlight a region with overlay."
4586 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4587 org-hl begin end (or buffer (current-buffer))))
4588
4589 (defun org-unhighlight ()
4590 "Detach overlay INDEX."
4591 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4592
4593
4594 (defun org-agenda-follow-mode ()
4595 "Toggle follow mode in an agenda buffer."
4596 (interactive)
4597 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4598 (org-agenda-set-mode-name)
4599 (message "Follow mode is %s"
4600 (if org-agenda-follow-mode "on" "off")))
4601
4602 (defun org-agenda-toggle-diary ()
4603 "Toggle follow mode in an agenda buffer."
4604 (interactive)
4605 (setq org-agenda-include-diary (not org-agenda-include-diary))
4606 (org-agenda-redo)
4607 (org-agenda-set-mode-name)
4608 (message "Diary inclusion turned %s"
4609 (if org-agenda-include-diary "on" "off")))
4610
4611 (defun org-agenda-toggle-time-grid ()
4612 "Toggle follow mode in an agenda buffer."
4613 (interactive)
4614 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4615 (org-agenda-redo)
4616 (org-agenda-set-mode-name)
4617 (message "Time-grid turned %s"
4618 (if org-agenda-use-time-grid "on" "off")))
4619
4620 (defun org-agenda-set-mode-name ()
4621 "Set the mode name to indicate all the small mode settings."
4622 (setq mode-name
4623 (concat "Org-Agenda"
4624 (if (equal org-agenda-ndays 1) " Day" "")
4625 (if (equal org-agenda-ndays 7) " Week" "")
4626 (if org-agenda-follow-mode " Follow" "")
4627 (if org-agenda-include-diary " Diary" "")
4628 (if org-agenda-use-time-grid " Grid" "")))
4629 (force-mode-line-update))
4630
4631 (defun org-agenda-post-command-hook ()
4632 (and (eolp) (not (bolp)) (backward-char 1))
4633 (if (and org-agenda-follow-mode
4634 (get-text-property (point) 'org-marker))
4635 (org-agenda-show)))
4636
4637 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4638
4639 (defun org-get-entries-from-diary (date)
4640 "Get the (Emacs Calendar) diary entries for DATE."
4641 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4642 (diary-display-hook '(fancy-diary-display))
4643 (list-diary-entries-hook
4644 (cons 'org-diary-default-entry list-diary-entries-hook))
4645 (diary-file-name-prefix-function nil) ; turn this feature off
4646 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4647 entries
4648 (org-disable-agenda-to-diary t))
4649 (save-excursion
4650 (save-window-excursion
4651 (list-diary-entries date 1)))
4652 (if (not (get-buffer fancy-diary-buffer))
4653 (setq entries nil)
4654 (with-current-buffer fancy-diary-buffer
4655 (setq buffer-read-only nil)
4656 (if (= (point-max) 1)
4657 ;; No entries
4658 (setq entries nil)
4659 ;; Omit the date and other unnecessary stuff
4660 (org-agenda-cleanup-fancy-diary)
4661 ;; Add prefix to each line and extend the text properties
4662 (if (= (point-max) 1)
4663 (setq entries nil)
4664 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4665 (set-buffer-modified-p nil)
4666 (kill-buffer fancy-diary-buffer)))
4667 (when entries
4668 (setq entries (org-split-string entries "\n"))
4669 (setq entries
4670 (mapcar
4671 (lambda (x)
4672 (setq x (org-format-agenda-item "" x "Diary" 'time))
4673 ;; Extend the text properties to the beginning of the line
4674 (add-text-properties
4675 0 (length x)
4676 (text-properties-at (1- (length x)) x)
4677 x)
4678 x)
4679 entries)))))
4680
4681 (defun org-agenda-cleanup-fancy-diary ()
4682 "Remove unwanted stuff in buffer created by fancy-diary-display.
4683 This gets rid of the date, the underline under the date, and
4684 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4685 date. Itt also removes lines that contain only whitespace."
4686 (goto-char (point-min))
4687 (if (looking-at ".*?:[ \t]*")
4688 (progn
4689 (replace-match "")
4690 (re-search-forward "\n=+$" nil t)
4691 (replace-match "")
4692 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4693 (re-search-forward "\n=+$" nil t)
4694 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4695 (goto-char (point-min))
4696 (while (re-search-forward "^ +\n" nil t)
4697 (replace-match ""))
4698 (goto-char (point-min))
4699 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4700 (replace-match "")))
4701
4702 ;; Make sure entries from the diary have the right text properties.
4703 (eval-after-load "diary-lib"
4704 '(if (boundp 'diary-modify-entry-list-string-function)
4705 ;; We can rely on the hook, nothing to do
4706 nil
4707 ;; Hook not avaiable, must use advice to make this work
4708 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4709 "Make the position visible."
4710 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4711 (stringp string)
4712 (buffer-file-name))
4713 (setq string (org-modify-diary-entry-string string))))))
4714
4715 (defun org-modify-diary-entry-string (string)
4716 "Add text properties to string, allowing org-mode to act on it."
4717 (add-text-properties
4718 0 (length string)
4719 (list 'mouse-face 'highlight
4720 'keymap org-agenda-keymap
4721 'help-echo
4722 (format
4723 "mouse-2 or RET jump to diary file %s"
4724 (abbreviate-file-name (buffer-file-name)))
4725 'org-agenda-diary-link t
4726 'org-marker (org-agenda-new-marker (point-at-bol)))
4727 string)
4728 string)
4729
4730 (defun org-diary-default-entry ()
4731 "Add a dummy entry to the diary.
4732 Needed to avoid empty dates which mess up holiday display."
4733 ;; Catch the error if dealing with the new add-to-diary-alist
4734 (when org-disable-agenda-to-diary
4735 (condition-case nil
4736 (add-to-diary-list original-date "Org-mode dummy" "")
4737 (error
4738 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
4739
4740 (defun org-cycle-agenda-files ()
4741 "Cycle through the files in `org-agenda-files'.
4742 If the current buffer visits an agenda file, find the next one in the list.
4743 If the current buffer does not, find the first agenda file."
4744 (interactive)
4745 (let ((files (append org-agenda-files (list (car org-agenda-files))))
4746 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
4747 file)
4748 (unless files (error "No agenda files"))
4749 (catch 'exit
4750 (while (setq file (pop files))
4751 (if (equal (file-truename file) tcf)
4752 (when (car files)
4753 (find-file (car files))
4754 (throw 'exit t))))
4755 (find-file (car org-agenda-files)))))
4756
4757 (defun org-agenda-file-to-end (&optional file)
4758 "Move/add the current file to the end of the agenda fiole list.
4759 I the file is not present in the list, it is appended ot the list. If it is
4760 present, it is moved there."
4761 (interactive)
4762 (org-agenda-file-to-front 'to-end file))
4763
4764 (defun org-agenda-file-to-front (&optional to-end file)
4765 "Move/add the current file to the top of the agenda file list.
4766 If the file is not present in the list, it is added to the front. If it is
4767 present, it is moved there. With optional argument TO-END, add/move to the
4768 end of the list."
4769 (interactive "P")
4770 (let ((file-alist (mapcar (lambda (x)
4771 (cons (file-truename x) x))
4772 org-agenda-files))
4773 (ctf (file-truename (buffer-file-name)))
4774 x had)
4775 (setq x (assoc ctf file-alist) had x)
4776
4777 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
4778 (if to-end
4779 (setq file-alist (append (delq x file-alist) (list x)))
4780 (setq file-alist (cons x (delq x file-alist))))
4781 (setq org-agenda-files (mapcar 'cdr file-alist))
4782 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4783 (customize-save-variable 'org-agenda-files org-agenda-files))
4784 (org-install-agenda-files-menu)
4785 (message "File %s to %s of agenda file list"
4786 (if had "moved" "added") (if to-end "end" "front"))))
4787
4788 (defun org-remove-file (&optional file)
4789 "Remove current file from the list of files in variable `org-agenda-files'.
4790 These are the files which are being checked for agenda entries.
4791 Optional argument FILE means, use this file instead of the current."
4792 (interactive)
4793 (let* ((file (or file (buffer-file-name)))
4794 (true-file (file-truename file))
4795 (afile (abbreviate-file-name file))
4796 (files (delq nil (mapcar
4797 (lambda (x)
4798 (if (equal true-file
4799 (file-truename x))
4800 nil x))
4801 org-agenda-files))))
4802 (if (not (= (length files) (length org-agenda-files)))
4803 (progn
4804 (setq org-agenda-files files)
4805 (customize-save-variable 'org-agenda-files org-agenda-files)
4806 (org-install-agenda-files-menu)
4807 (message "Removed file: %s" afile))
4808 (message "File was not in list: %s" afile))))
4809
4810 (defun org-file-menu-entry (file)
4811 (vector file (list 'find-file file) t))
4812 ;; FIXME: Maybe removed a buffer visited through the menu from
4813 ;; org-agenda-new-buffers, so that the buffer will not be removed
4814 ;; when exiting the agenda????
4815
4816 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4817 "Return a list of all relevant day numbers from BEG to END buffer positions.
4818 If NO-RANGES is non-nil, include only the start and end dates of a range,
4819 not every single day in the range. If FORCE-TODAY is non-nil, make
4820 sure that TODAY is included in the list."
4821 (let (dates date day day1 day2 ts1 ts2)
4822 (if force-today
4823 (setq dates (list (time-to-days (current-time)))))
4824 (save-excursion
4825 (goto-char beg)
4826 (while (re-search-forward org-ts-regexp end t)
4827 (setq day (time-to-days (org-time-string-to-time
4828 (substring (match-string 1) 0 10))))
4829 (or (memq day dates) (push day dates)))
4830 (unless no-ranges
4831 (goto-char beg)
4832 (while (re-search-forward org-tr-regexp end t)
4833 (setq ts1 (substring (match-string 1) 0 10)
4834 ts2 (substring (match-string 2) 0 10)
4835 day1 (time-to-days (org-time-string-to-time ts1))
4836 day2 (time-to-days (org-time-string-to-time ts2)))
4837 (while (< (setq day1 (1+ day1)) day2)
4838 (or (memq day1 dates) (push day1 dates)))))
4839 (sort dates '<))))
4840
4841 ;;;###autoload
4842 (defun org-diary (&rest args)
4843 "Return diary information from org-files.
4844 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4845 It accesses org files and extracts information from those files to be
4846 listed in the diary. The function accepts arguments specifying what
4847 items should be listed. The following arguments are allowed:
4848
4849 :timestamp List the headlines of items containing a date stamp or
4850 date range matching the selected date. Deadlines will
4851 also be listed, on the expiration day.
4852
4853 :deadline List any deadlines past due, or due within
4854 `org-deadline-warning-days'. The listing occurs only
4855 in the diary for *today*, not at any other date. If
4856 an entry is marked DONE, it is no longer listed.
4857
4858 :scheduled List all items which are scheduled for the given date.
4859 The diary for *today* also contains items which were
4860 scheduled earlier and are not yet marked DONE.
4861
4862 :todo List all TODO items from the org-file. This may be a
4863 long list - so this is not turned on by default.
4864 Like deadlines, these entries only show up in the
4865 diary for *today*, not at any other date.
4866
4867 The call in the diary file should look like this:
4868
4869 &%%(org-diary) ~/path/to/some/orgfile.org
4870
4871 Use a separate line for each org file to check. Or, if you omit the file name,
4872 all files listed in `org-agenda-files' will be checked automatically:
4873
4874 &%%(org-diary)
4875
4876 If you don't give any arguments (as in the example above), the default
4877 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4878 also be written as
4879
4880 &%%(org-diary :deadline :timestamp :scheduled)
4881
4882 The function expects the lisp variables `entry' and `date' to be provided
4883 by the caller, because this is how the calendar works. Don't use this
4884 function from a program - use `org-agenda-get-day-entries' instead."
4885 (org-agenda-maybe-reset-markers)
4886 (org-compile-prefix-format org-agenda-prefix-format)
4887 (setq args (or args '(:deadline :scheduled :timestamp)))
4888 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4889 (list entry)
4890 org-agenda-files))
4891 file rtn results)
4892 ;; If this is called during org-agenda, don't return any entries to
4893 ;; the calendar. Org Agenda will list these entries itself.
4894 (if org-disable-agenda-to-diary (setq files nil))
4895 (while (setq file (pop files))
4896 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4897 (setq results (append results rtn)))
4898 (if results
4899 (concat (org-finalize-agenda-entries results) "\n"))))
4900 (defvar org-category-table nil)
4901 (defun org-get-category-table ()
4902 "Get the table of categories and positions in current buffer."
4903 (let (tbl)
4904 (save-excursion
4905 (goto-char (point-min))
4906 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
4907 (push (cons (point) (org-trim (match-string 1))) tbl)))
4908 tbl))
4909 (defun org-get-category (&optional pos)
4910 "Get the category applying to position POS."
4911 (if (not org-category-table)
4912 org-category
4913 (let ((tbl org-category-table)
4914 (pos (or pos (point))))
4915 (while (and tbl (> (caar tbl) pos))
4916 (pop tbl))
4917 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
4918 org-category-table))))))
4919
4920 (defun org-agenda-get-day-entries (file date &rest args)
4921 "Does the work for `org-diary' and `org-agenda'.
4922 FILE is the path to a file to be checked for entries. DATE is date like
4923 the one returned by `calendar-current-date'. ARGS are symbols indicating
4924 which kind of entries should be extracted. For details about these, see
4925 the documentation of `org-diary'."
4926 (setq args (or args '(:deadline :scheduled :timestamp)))
4927 (let* ((org-startup-with-deadline-check nil)
4928 (org-startup-folded nil)
4929 (buffer (if (file-exists-p file)
4930 (org-get-agenda-file-buffer file)
4931 (error "No such file %s" file)))
4932 arg results rtn)
4933 (if (not buffer)
4934 ;; If file does not exist, make sure an error message ends up in diary
4935 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4936 (with-current-buffer buffer
4937 (unless (eq major-mode 'org-mode)
4938 (error "Agenda file %s is not in `org-mode'" file))
4939 (setq org-category-table (org-get-category-table))
4940 (let ((case-fold-search nil))
4941 (save-excursion
4942 (save-restriction
4943 (if org-respect-restriction
4944 (if (org-region-active-p)
4945 ;; Respect a region to restrict search
4946 (narrow-to-region (region-beginning) (region-end)))
4947 ;; If we work for the calendar or many files,
4948 ;; get rid of any restriction
4949 (widen))
4950 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4951 (while (setq arg (pop args))
4952 (cond
4953 ((and (eq arg :todo)
4954 (equal date (calendar-current-date)))
4955 (setq rtn (org-agenda-get-todos))
4956 (setq results (append results rtn)))
4957 ((eq arg :timestamp)
4958 (setq rtn (org-agenda-get-blocks))
4959 (setq results (append results rtn))
4960 (setq rtn (org-agenda-get-timestamps))
4961 (setq results (append results rtn)))
4962 ((eq arg :scheduled)
4963 (setq rtn (org-agenda-get-scheduled))
4964 (setq results (append results rtn)))
4965 ((and (eq arg :deadline)
4966 (equal date (calendar-current-date)))
4967 (setq rtn (org-agenda-get-deadlines))
4968 (setq results (append results rtn))))))))
4969 results))))
4970
4971 (defun org-entry-is-done-p ()
4972 "Is the current entry marked DONE?"
4973 (save-excursion
4974 (and (re-search-backward "[\r\n]\\*" nil t)
4975 (looking-at org-nl-done-regexp))))
4976
4977 (defun org-at-date-range-p ()
4978 "Is the cursor inside a date range?"
4979 (interactive)
4980 (save-excursion
4981 (catch 'exit
4982 (let ((pos (point)))
4983 (skip-chars-backward "^<\r\n")
4984 (skip-chars-backward "<")
4985 (and (looking-at org-tr-regexp)
4986 (>= (match-end 0) pos)
4987 (throw 'exit t))
4988 (skip-chars-backward "^<\r\n")
4989 (skip-chars-backward "<")
4990 (and (looking-at org-tr-regexp)
4991 (>= (match-end 0) pos)
4992 (throw 'exit t)))
4993 nil)))
4994
4995 (defun org-agenda-get-todos ()
4996 "Return the TODO information for agenda display."
4997 (let* ((props (list 'face nil
4998 'done-face 'org-done
4999 'mouse-face 'highlight
5000 'keymap org-agenda-keymap
5001 'help-echo
5002 (format "mouse-2 or RET jump to org file %s"
5003 (abbreviate-file-name (buffer-file-name)))))
5004 (regexp (concat "[\n\r]\\*+ *\\("
5005 (if org-select-this-todo-keyword
5006 (concat "\\<\\(" org-select-this-todo-keyword
5007 "\\)\\>")
5008 org-not-done-regexp)
5009 "[^\n\r]*\\)"))
5010 marker priority category
5011 ee txt)
5012 (goto-char (point-min))
5013 (while (re-search-forward regexp nil t)
5014 (goto-char (match-beginning 1))
5015 (setq marker (org-agenda-new-marker (point-at-bol))
5016 category (org-get-category)
5017 txt (org-format-agenda-item "" (match-string 1) category)
5018 priority
5019 (+ (org-get-priority txt)
5020 (if org-todo-kwd-priority-p
5021 (- org-todo-kwd-max-priority -2
5022 (length
5023 (member (match-string 2) org-todo-keywords)))
5024 1)))
5025 (add-text-properties
5026 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5027 'priority priority 'category category)
5028 props)
5029 txt)
5030 (push txt ee)
5031 (goto-char (match-end 1)))
5032 (nreverse ee)))
5033
5034 (defconst org-agenda-no-heading-message
5035 "No heading for this item in buffer or region")
5036
5037 (defun org-agenda-get-timestamps ()
5038 "Return the date stamp information for agenda display."
5039 (let* ((props (list 'face nil
5040 'mouse-face 'highlight
5041 'keymap org-agenda-keymap
5042 'help-echo
5043 (format "mouse-2 or RET jump to org file %s"
5044 (abbreviate-file-name (buffer-file-name)))))
5045 (regexp (regexp-quote
5046 (substring
5047 (format-time-string
5048 (car org-time-stamp-formats)
5049 (apply 'encode-time ; DATE bound by calendar
5050 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5051 0 11)))
5052 marker hdmarker deadlinep scheduledp donep tmp priority category
5053 ee txt timestr)
5054 (goto-char (point-min))
5055 (while (re-search-forward regexp nil t)
5056 (if (not (save-match-data (org-at-date-range-p)))
5057 (progn
5058 (setq marker (org-agenda-new-marker (match-beginning 0))
5059 category (org-get-category (match-beginning 0))
5060 tmp (buffer-substring (max (point-min)
5061 (- (match-beginning 0)
5062 org-ds-keyword-length))
5063 (match-beginning 0))
5064 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5065 deadlinep (string-match org-deadline-regexp tmp)
5066 scheduledp (string-match org-scheduled-regexp tmp)
5067 donep (org-entry-is-done-p))
5068 (if (string-match ">" timestr)
5069 ;; substring should only run to end of time stamp
5070 (setq timestr (substring timestr 0 (match-end 0))))
5071 (save-excursion
5072 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5073 (progn
5074 (goto-char (match-end 1))
5075 (setq hdmarker (org-agenda-new-marker))
5076 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5077 (setq txt (org-format-agenda-item
5078 (format "%s%s"
5079 (if deadlinep "Deadline: " "")
5080 (if scheduledp "Scheduled: " ""))
5081 (match-string 1) category timestr)))
5082 (setq txt org-agenda-no-heading-message))
5083 (setq priority (org-get-priority txt))
5084 (add-text-properties
5085 0 (length txt) (append (list 'org-marker marker
5086 'org-hd-marker hdmarker) props)
5087 txt)
5088 (if deadlinep
5089 (add-text-properties
5090 0 (length txt)
5091 (list 'face
5092 (if donep 'org-done 'org-warning)
5093 'undone-face 'org-warning
5094 'done-face 'org-done
5095 'priority (+ 100 priority))
5096 txt)
5097 (if scheduledp
5098 (add-text-properties
5099 0 (length txt)
5100 (list 'face 'org-scheduled-today
5101 'undone-face 'org-scheduled-today
5102 'done-face 'org-done
5103 priority (+ 99 priority))
5104 txt)
5105 (add-text-properties
5106 0 (length txt)
5107 (list 'priority priority 'category category) txt)))
5108 (push txt ee))
5109 (outline-next-heading))))
5110 (nreverse ee)))
5111
5112 (defun org-agenda-get-deadlines ()
5113 "Return the deadline information for agenda display."
5114 (let* ((wdays org-deadline-warning-days)
5115 (props (list 'mouse-face 'highlight
5116 'keymap org-agenda-keymap
5117 'help-echo
5118 (format "mouse-2 or RET jump to org file %s"
5119 (abbreviate-file-name (buffer-file-name)))))
5120 (regexp org-deadline-time-regexp)
5121 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5122 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5123 d2 diff pos pos1 category
5124 ee txt head)
5125 (goto-char (point-min))
5126 (while (re-search-forward regexp nil t)
5127 (setq pos (1- (match-beginning 1))
5128 d2 (time-to-days
5129 (org-time-string-to-time (match-string 1)))
5130 diff (- d2 d1))
5131 ;; When to show a deadline in the calendar:
5132 ;; If the expiration is within wdays warning time.
5133 ;; Past-due deadlines are only shown on the current date
5134 (if (and (< diff wdays) todayp (not (= diff 0)))
5135 (save-excursion
5136 (setq category (org-get-category))
5137 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5138 (progn
5139 (goto-char (match-end 0))
5140 (setq pos1 (match-end 1))
5141 (setq head (buffer-substring-no-properties
5142 (point)
5143 (progn (skip-chars-forward "^\r\n")
5144 (point))))
5145 (if (string-match org-looking-at-done-regexp head)
5146 (setq txt nil)
5147 (setq txt (org-format-agenda-item
5148 (format "In %3d d.: " diff) head category))))
5149 (setq txt org-agenda-no-heading-message))
5150 (when txt
5151 (add-text-properties
5152 0 (length txt)
5153 (append
5154 (list 'org-marker (org-agenda-new-marker pos)
5155 'org-hd-marker (org-agenda-new-marker pos1)
5156 'priority (+ (- 10 diff) (org-get-priority txt))
5157 'category category
5158 'face (cond ((<= diff 0) 'org-warning)
5159 ((<= diff 5) 'org-scheduled-previously)
5160 (t nil))
5161 'undone-face (cond
5162 ((<= diff 0) 'org-warning)
5163 ((<= diff 5) 'org-scheduled-previously)
5164 (t nil))
5165 'done-face 'org-done)
5166 props)
5167 txt)
5168 (push txt ee)))))
5169 ee))
5170
5171 (defun org-agenda-get-scheduled ()
5172 "Return the scheduled information for agenda display."
5173 (let* ((props (list 'face 'org-scheduled-previously
5174 'undone-face 'org-scheduled-previously
5175 'done-face 'org-done
5176 'mouse-face 'highlight
5177 'keymap org-agenda-keymap
5178 'help-echo
5179 (format "mouse-2 or RET jump to org file %s"
5180 (abbreviate-file-name (buffer-file-name)))))
5181 (regexp org-scheduled-time-regexp)
5182 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5183 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5184 d2 diff pos pos1 category
5185 ee txt head)
5186 (goto-char (point-min))
5187 (while (re-search-forward regexp nil t)
5188 (setq pos (1- (match-beginning 1))
5189 d2 (time-to-days
5190 (org-time-string-to-time (match-string 1)))
5191 diff (- d2 d1))
5192 ;; When to show a scheduled item in the calendar:
5193 ;; If it is on or past the date.
5194 (if (and (< diff 0) todayp)
5195 (save-excursion
5196 (setq category (org-get-category))
5197 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5198 (progn
5199 (goto-char (match-end 0))
5200 (setq pos1 (match-end 1))
5201 (setq head (buffer-substring-no-properties
5202 (point)
5203 (progn (skip-chars-forward "^\r\n") (point))))
5204 (if (string-match org-looking-at-done-regexp head)
5205 (setq txt nil)
5206 (setq txt (org-format-agenda-item
5207 (format "Sched.%2dx: " (- 1 diff)) head
5208 category))))
5209 (setq txt org-agenda-no-heading-message))
5210 (when txt
5211 (add-text-properties
5212 0 (length txt)
5213 (append (list 'org-marker (org-agenda-new-marker pos)
5214 'org-hd-marker (org-agenda-new-marker pos1)
5215 'priority (+ (- 5 diff) (org-get-priority txt))
5216 'category category)
5217 props) txt)
5218 (push txt ee)))))
5219 ee))
5220
5221 (defun org-agenda-get-blocks ()
5222 "Return the date-range information for agenda display."
5223 (let* ((props (list 'face nil
5224 'mouse-face 'highlight
5225 'keymap org-agenda-keymap
5226 'help-echo
5227 (format "mouse-2 or RET jump to org file %s"
5228 (abbreviate-file-name (buffer-file-name)))))
5229 (regexp org-tr-regexp)
5230 (d0 (calendar-absolute-from-gregorian date))
5231 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5232 (goto-char (point-min))
5233 (while (re-search-forward regexp nil t)
5234 (setq timestr (match-string 0)
5235 s1 (match-string 1)
5236 s2 (match-string 2)
5237 d1 (time-to-days (org-time-string-to-time s1))
5238 d2 (time-to-days (org-time-string-to-time s2)))
5239 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5240 ;; Only allow days between the limits, because the normal
5241 ;; date stamps will catch the limits.
5242 (save-excursion
5243 (setq marker (org-agenda-new-marker (point)))
5244 (setq category (org-get-category))
5245 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5246 (progn
5247 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5248 (goto-char (match-end 1))
5249 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5250 (setq txt (org-format-agenda-item
5251 (format (if (= d1 d2) "" "(%d/%d): ")
5252 (1+ (- d0 d1)) (1+ (- d2 d1)))
5253 (match-string 1) category
5254 (if (= d0 d1) timestr))))
5255 (setq txt org-agenda-no-heading-message))
5256 (add-text-properties
5257 0 (length txt) (append (list 'org-marker marker
5258 'org-hd-marker hdmarker
5259 'priority (org-get-priority txt)
5260 'category category)
5261 props)
5262 txt)
5263 (push txt ee)))
5264 (outline-next-heading))
5265 ;; Sort the entries by expiration date.
5266 (nreverse ee)))
5267
5268 (defconst org-plain-time-of-day-regexp
5269 (concat
5270 "\\(\\<[012]?[0-9]"
5271 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5272 "\\(--?"
5273 "\\(\\<[012]?[0-9]"
5274 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5275 "\\)?")
5276 "Regular expression to match a plain time or time range.
5277 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5278 groups carry important information:
5279 0 the full match
5280 1 the first time, range or not
5281 8 the second time, if it is a range.")
5282
5283 (defconst org-stamp-time-of-day-regexp
5284 (concat
5285 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5286 "\\([012][0-9]:[0-5][0-9]\\)>"
5287 "\\(--?"
5288 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5289 "Regular expression to match a timestamp time or time range.
5290 After a match, the following groups carry important information:
5291 0 the full match
5292 1 date plus weekday, for backreferencing to make sure both times on same day
5293 2 the first time, range or not
5294 4 the second time, if it is a range.")
5295
5296 (defvar org-prefix-has-time nil
5297 "A flag, set by `org-compile-prefix-format'.
5298 The flag is set if the currently compiled format contains a `%t'.")
5299
5300 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5301 "Format TXT to be inserted into the agenda buffer.
5302 In particular, it adds the prefix and corresponding text properties. EXTRA
5303 must be a string and replaces the `%s' specifier in the prefix format.
5304 CATEGORY (string, symbol or nil) may be used to overule the default
5305 category taken from local variable or file name. It will replace the `%c'
5306 specifier in the format. DOTIME, when non-nil, indicates that a
5307 time-of-day should be extracted from TXT for sorting of this entry, and for
5308 the `%t' specifier in the format. When DOTIME is a string, this string is
5309 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5310 only the correctly processes TXT should be returned - this is used by
5311 `org-agenda-change-all-lines'."
5312 (save-match-data
5313 ;; Diary entries sometimes have extra whitespace at the beginning
5314 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5315 (let* ((category (or category
5316 org-category
5317 (if (buffer-file-name)
5318 (file-name-sans-extension
5319 (file-name-nondirectory (buffer-file-name)))
5320 "")))
5321 time ;; needed for the eval of the prefix format
5322 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5323 (time-of-day (and dotime (org-get-time-of-day ts)))
5324 stamp plain s0 s1 s2 rtn)
5325 (when (and dotime time-of-day org-prefix-has-time)
5326 ;; Extract starting and ending time and move them to prefix
5327 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5328 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5329 (setq s0 (match-string 0 ts)
5330 s1 (match-string (if plain 1 2) ts)
5331 s2 (match-string (if plain 8 4) ts))
5332
5333 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5334 ;; them, we might want to remove them there to avoid duplication.
5335 ;; The user can turn this off with a variable.
5336 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5337 (string-match (concat (regexp-quote s0) " *") txt)
5338 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5339 (= (match-beginning 0) 0)
5340 t))
5341 (setq txt (replace-match "" nil nil txt))))
5342 ;; Normalize the time(s) to 24 hour
5343 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5344 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5345
5346 ;; Create the final string
5347 (if noprefix
5348 (setq rtn txt)
5349 ;; Prepare the variables needed in the eval of the compiled format
5350 (setq time (cond (s2 (concat s1 "-" s2))
5351 (s1 (concat s1 "......"))
5352 (t ""))
5353 extra (or extra "")
5354 category (if (symbolp category) (symbol-name category) category))
5355 ;; Evaluate the compiled format
5356 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5357
5358 ;; And finally add the text properties
5359 (add-text-properties
5360 0 (length rtn) (list 'category (downcase category)
5361 'prefix-length (- (length rtn) (length txt))
5362 'time-of-day time-of-day
5363 'dotime dotime)
5364 rtn)
5365 rtn)))
5366
5367 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5368 (catch 'exit
5369 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5370 ((and todayp (member 'today (car org-agenda-time-grid))))
5371 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5372 ((member 'weekly (car org-agenda-time-grid)))
5373 (t (throw 'exit list)))
5374 (let* ((have (delq nil (mapcar
5375 (lambda (x) (get-text-property 1 'time-of-day x))
5376 list)))
5377 (string (nth 1 org-agenda-time-grid))
5378 (gridtimes (nth 2 org-agenda-time-grid))
5379 (req (car org-agenda-time-grid))
5380 (remove (member 'remove-match req))
5381 new time)
5382 (if (and (member 'require-timed req) (not have))
5383 ;; don't show empty grid
5384 (throw 'exit list))
5385 (while (setq time (pop gridtimes))
5386 (unless (and remove (member time have))
5387 (setq time (int-to-string time))
5388 (push (org-format-agenda-item
5389 nil string "" ;; FIXME: put a category?
5390 (concat (substring time 0 -2) ":" (substring time -2)))
5391 new)
5392 (put-text-property
5393 1 (length (car new)) 'face 'org-time-grid (car new))))
5394 (if (member 'time-up org-agenda-sorting-strategy)
5395 (append new list)
5396 (append list new)))))
5397
5398 (defun org-compile-prefix-format (format)
5399 "Compile the prefix format into a Lisp form that can be evaluated.
5400 The resulting form is returned and stored in the variable
5401 `org-prefix-format-compiled'."
5402 (setq org-prefix-has-time nil)
5403 (let ((start 0) varform vars var (s format) c f opt)
5404 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5405 s start)
5406 (setq var (cdr (assoc (match-string 4 s)
5407 '(("c" . category) ("t" . time) ("s" . extra))))
5408 c (or (match-string 3 s) "")
5409 opt (match-beginning 1)
5410 start (1+ (match-beginning 0)))
5411 (if (equal var 'time) (setq org-prefix-has-time t))
5412 (setq f (concat "%" (match-string 2 s) "s"))
5413 (if opt
5414 (setq varform
5415 `(if (equal "" ,var)
5416 ""
5417 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5418 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5419 (setq s (replace-match "%s" t nil s))
5420 (push varform vars))
5421 (setq vars (nreverse vars))
5422 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5423
5424 (defun org-get-time-of-day (s &optional string)
5425 "Check string S for a time of day.
5426 If found, return it as a military time number between 0 and 2400.
5427 If not found, return nil.
5428 The optional STRING argument forces conversion into a 5 character wide string
5429 HH:MM."
5430 (save-match-data
5431 (when
5432 (or
5433 (string-match
5434 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5435 (string-match
5436 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5437 (let* ((t0 (+ (* 100
5438 (+ (string-to-number (match-string 1 s))
5439 (if (and (match-beginning 4)
5440 (equal (downcase (match-string 4 s)) "pm"))
5441 12 0)))
5442 (if (match-beginning 3)
5443 (string-to-number (match-string 3 s))
5444 0)))
5445 (t1 (concat " " (int-to-string t0))))
5446 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5447
5448 (defun org-finalize-agenda-entries (list)
5449 "Sort and concatenate the agenda items."
5450 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5451
5452 (defsubst org-cmp-priority (a b)
5453 "Compare the priorities of string a and b."
5454 (let ((pa (or (get-text-property 1 'priority a) 0))
5455 (pb (or (get-text-property 1 'priority b) 0)))
5456 (cond ((> pa pb) +1)
5457 ((< pa pb) -1)
5458 (t nil))))
5459
5460 (defsubst org-cmp-category (a b)
5461 "Compare the string values of categories of strings a and b."
5462 (let ((ca (or (get-text-property 1 'category a) ""))
5463 (cb (or (get-text-property 1 'category b) "")))
5464 (cond ((string-lessp ca cb) -1)
5465 ((string-lessp cb ca) +1)
5466 (t nil))))
5467
5468 (defsubst org-cmp-time (a b)
5469 "Compare the time-of-day values of strings a and b."
5470 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5471 (ta (or (get-text-property 1 'time-of-day a) def))
5472 (tb (or (get-text-property 1 'time-of-day b) def)))
5473 (cond ((< ta tb) -1)
5474 ((< tb ta) +1)
5475 (t nil))))
5476
5477 (defun org-entries-lessp (a b)
5478 "Predicate for sorting agenda entries."
5479 ;; The following variables will be used when the form is evaluated.
5480 (let* ((time-up (org-cmp-time a b))
5481 (time-down (if time-up (- time-up) nil))
5482 (priority-up (org-cmp-priority a b))
5483 (priority-down (if priority-up (- priority-up) nil))
5484 (category-up (org-cmp-category a b))
5485 (category-down (if category-up (- category-up) nil))
5486 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5487 (cdr (assoc
5488 (eval (cons 'or org-agenda-sorting-strategy))
5489 '((-1 . t) (1 . nil) (nil . nil))))))
5490
5491 (defun org-agenda-show-priority ()
5492 "Show the priority of the current item.
5493 This priority is composed of the main priority given with the [#A] cookies,
5494 and by additional input from the age of a schedules or deadline entry."
5495 (interactive)
5496 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5497 (message "Priority is %d" (if pri pri -1000))))
5498
5499 (defun org-agenda-goto (&optional highlight)
5500 "Go to the Org-mode file which contains the item at point."
5501 (interactive)
5502 (let* ((marker (or (get-text-property (point) 'org-marker)
5503 (org-agenda-error)))
5504 (buffer (marker-buffer marker))
5505 (pos (marker-position marker)))
5506 (switch-to-buffer-other-window buffer)
5507 (widen)
5508 (goto-char pos)
5509 (when (eq major-mode 'org-mode)
5510 (org-show-hidden-entry)
5511 (save-excursion
5512 (and (outline-next-heading)
5513 (org-flag-heading nil)))) ; show the next heading
5514 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5515
5516 (defun org-agenda-switch-to ()
5517 "Go to the Org-mode file which contains the item at point."
5518 (interactive)
5519 (let* ((marker (or (get-text-property (point) 'org-marker)
5520 (org-agenda-error)))
5521 (buffer (marker-buffer marker))
5522 (pos (marker-position marker)))
5523 (switch-to-buffer buffer)
5524 (delete-other-windows)
5525 (widen)
5526 (goto-char pos)
5527 (when (eq major-mode 'org-mode)
5528 (org-show-hidden-entry)
5529 (save-excursion
5530 (and (outline-next-heading)
5531 (org-flag-heading nil)))))) ; show the next heading
5532
5533 (defun org-agenda-goto-mouse (ev)
5534 "Go to the Org-mode file which contains the item at the mouse click."
5535 (interactive "e")
5536 (mouse-set-point ev)
5537 (org-agenda-goto))
5538
5539 (defun org-agenda-show ()
5540 "Display the Org-mode file which contains the item at point."
5541 (interactive)
5542 (let ((win (selected-window)))
5543 (org-agenda-goto t)
5544 (select-window win)))
5545
5546 (defun org-agenda-recenter (arg)
5547 "Display the Org-mode file which contains the item at point and recenter."
5548 (interactive "P")
5549 (let ((win (selected-window)))
5550 (org-agenda-goto t)
5551 (recenter arg)
5552 (select-window win)))
5553
5554 (defun org-agenda-show-mouse (ev)
5555 "Display the Org-mode file which contains the item at the mouse click."
5556 (interactive "e")
5557 (mouse-set-point ev)
5558 (org-agenda-show))
5559
5560 (defun org-agenda-check-no-diary ()
5561 "Check if the entry is a diary link and abort if yes."
5562 (if (get-text-property (point) 'org-agenda-diary-link)
5563 (org-agenda-error)))
5564
5565 (defun org-agenda-error ()
5566 (error "Command not allowed in this line"))
5567
5568 (defvar org-last-heading-marker (make-marker)
5569 "Marker pointing to the headline that last changed its TODO state
5570 by a remote command from the agenda.")
5571
5572 (defun org-agenda-todo (&optional arg)
5573 "Cycle TODO state of line at point, also in Org-mode file.
5574 This changes the line at point, all other lines in the agenda referring to
5575 the same tree node, and the headline of the tree node in the Org-mode file."
5576 (interactive "P")
5577 (org-agenda-check-no-diary)
5578 (let* ((col (current-column))
5579 (marker (or (get-text-property (point) 'org-marker)
5580 (org-agenda-error)))
5581 (buffer (marker-buffer marker))
5582 (pos (marker-position marker))
5583 (hdmarker (get-text-property (point) 'org-hd-marker))
5584 (buffer-read-only nil)
5585 newhead)
5586 (with-current-buffer buffer
5587 (widen)
5588 (goto-char pos)
5589 (org-show-hidden-entry)
5590 (save-excursion
5591 (and (outline-next-heading)
5592 (org-flag-heading nil))) ; show the next heading
5593 (org-todo arg)
5594 (forward-char 1)
5595 (setq newhead (org-get-heading))
5596 (save-excursion
5597 (org-back-to-heading)
5598 (move-marker org-last-heading-marker (point))))
5599 (beginning-of-line 1)
5600 (save-excursion
5601 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5602 (move-to-column col)))
5603
5604 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5605 "Change all lines in the agenda buffer which match hdmarker.
5606 The new content of the line will be NEWHEAD (as modified by
5607 `org-format-agenda-item'). HDMARKER is checked with
5608 `equal' against all `org-hd-marker' text properties in the file.
5609 If FIXFACE is non-nil, the face of each item is modified acording to
5610 the new TODO state."
5611 (let* (props m pl undone-face done-face finish new dotime cat)
5612 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5613 (save-excursion
5614 (goto-char (point-max))
5615 (beginning-of-line 1)
5616 (while (not finish)
5617 (setq finish (bobp))
5618 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5619 (equal m hdmarker))
5620 (setq props (text-properties-at (point))
5621 dotime (get-text-property (point) 'dotime)
5622 cat (get-text-property (point) 'category)
5623 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
5624 pl (get-text-property (point) 'prefix-length)
5625 undone-face (get-text-property (point) 'undone-face)
5626 done-face (get-text-property (point) 'done-face))
5627 (move-to-column pl)
5628 (if (looking-at ".*")
5629 (progn
5630 (replace-match new t t)
5631 (beginning-of-line 1)
5632 (add-text-properties (point-at-bol) (point-at-eol) props)
5633 (if fixface
5634 (add-text-properties
5635 (point-at-bol) (point-at-eol)
5636 (list 'face
5637 (if org-last-todo-state-is-todo
5638 undone-face done-face))))
5639 (beginning-of-line 1))
5640 (error "Line update did not work")))
5641 (beginning-of-line 0)))))
5642
5643 (defun org-agenda-priority-up ()
5644 "Increase the priority of line at point, also in Org-mode file."
5645 (interactive)
5646 (org-agenda-priority 'up))
5647
5648 (defun org-agenda-priority-down ()
5649 "Decrease the priority of line at point, also in Org-mode file."
5650 (interactive)
5651 (org-agenda-priority 'down))
5652
5653 (defun org-agenda-priority (&optional force-direction)
5654 "Set the priority of line at point, also in Org-mode file.
5655 This changes the line at point, all other lines in the agenda referring to
5656 the same tree node, and the headline of the tree node in the Org-mode file."
5657 (interactive)
5658 (org-agenda-check-no-diary)
5659 (let* ((marker (or (get-text-property (point) 'org-marker)
5660 (org-agenda-error)))
5661 (buffer (marker-buffer marker))
5662 (pos (marker-position marker))
5663 (hdmarker (get-text-property (point) 'org-hd-marker))
5664 (buffer-read-only nil)
5665 newhead)
5666 (with-current-buffer buffer
5667 (widen)
5668 (goto-char pos)
5669 (org-show-hidden-entry)
5670 (save-excursion
5671 (and (outline-next-heading)
5672 (org-flag-heading nil))) ; show the next heading
5673 (funcall 'org-priority force-direction)
5674 (end-of-line 1)
5675 (setq newhead (org-get-heading)))
5676 (org-agenda-change-all-lines newhead hdmarker)
5677 (beginning-of-line 1)))
5678
5679 (defun org-agenda-date-later (arg &optional what)
5680 "Change the date of this item to one day later."
5681 (interactive "p")
5682 (org-agenda-check-no-diary)
5683 (let* ((marker (or (get-text-property (point) 'org-marker)
5684 (org-agenda-error)))
5685 (buffer (marker-buffer marker))
5686 (pos (marker-position marker)))
5687 (with-current-buffer buffer
5688 (widen)
5689 (goto-char pos)
5690 (if (not (org-at-timestamp-p))
5691 (error "Cannot find time stamp"))
5692 (org-timestamp-change arg (or what 'day))
5693 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5694
5695 (defun org-agenda-date-earlier (arg &optional what)
5696 "Change the date of this item to one day earlier."
5697 (interactive "p")
5698 (org-agenda-date-later (- arg) what))
5699
5700 (defun org-agenda-date-prompt (arg)
5701 "Change the date of this item. Date is prompted for, with default today.
5702 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5703 be used to request time specification in the time stamp."
5704 (interactive "P")
5705 (org-agenda-check-no-diary)
5706 (let* ((marker (or (get-text-property (point) 'org-marker)
5707 (org-agenda-error)))
5708 (buffer (marker-buffer marker))
5709 (pos (marker-position marker)))
5710 (with-current-buffer buffer
5711 (widen)
5712 (goto-char pos)
5713 (if (not (org-at-timestamp-p))
5714 (error "Cannot find time stamp"))
5715 (org-time-stamp arg)
5716 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5717
5718 (defun org-get-heading ()
5719 "Return the heading of the current entry, without the stars."
5720 (save-excursion
5721 (and (bolp) (end-of-line 1))
5722 (if (and (re-search-backward "[\r\n]\\*" nil t)
5723 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5724 (match-string 1)
5725 "")))
5726
5727 (defun org-agenda-diary-entry ()
5728 "Make a diary entry, like the `i' command from the calendar.
5729 All the standard commands work: block, weekly etc"
5730 (interactive)
5731 (require 'diary-lib)
5732 (let* ((char (progn
5733 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5734 (read-char-exclusive)))
5735 (cmd (cdr (assoc char
5736 '((?d . insert-diary-entry)
5737 (?w . insert-weekly-diary-entry)
5738 (?m . insert-monthly-diary-entry)
5739 (?y . insert-yearly-diary-entry)
5740 (?a . insert-anniversary-diary-entry)
5741 (?b . insert-block-diary-entry)
5742 (?c . insert-cyclic-diary-entry)))))
5743 (oldf (symbol-function 'calendar-cursor-to-date))
5744 (point (point))
5745 (mark (or (mark t) (point))))
5746 (unless cmd
5747 (error "No command associated with <%c>" char))
5748 (unless (and (get-text-property point 'day)
5749 (or (not (equal ?b char))
5750 (get-text-property mark 'day)))
5751 (error "Don't know which date to use for diary entry"))
5752 ;; We implement this by hacking the `calendar-cursor-to-date' function
5753 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5754 (let ((calendar-mark-ring
5755 (list (calendar-gregorian-from-absolute
5756 (or (get-text-property mark 'day)
5757 (get-text-property point 'day))))))
5758 (unwind-protect
5759 (progn
5760 (fset 'calendar-cursor-to-date
5761 (lambda (&optional error)
5762 (calendar-gregorian-from-absolute
5763 (get-text-property point 'day))))
5764 (call-interactively cmd))
5765 (fset 'calendar-cursor-to-date oldf)))))
5766
5767
5768 (defun org-agenda-execute-calendar-command (cmd)
5769 "Execute a calendar command from the agenda, with the date associated to
5770 the cursor position."
5771 (require 'diary-lib)
5772 (unless (get-text-property (point) 'day)
5773 (error "Don't know which date to use for calendar command"))
5774 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5775 (point (point))
5776 (date (calendar-gregorian-from-absolute
5777 (get-text-property point 'day)))
5778 (displayed-day (extract-calendar-day date))
5779 (displayed-month (extract-calendar-month date))
5780 (displayed-year (extract-calendar-year date)))
5781 (unwind-protect
5782 (progn
5783 (fset 'calendar-cursor-to-date
5784 (lambda (&optional error)
5785 (calendar-gregorian-from-absolute
5786 (get-text-property point 'day))))
5787 (call-interactively cmd))
5788 (fset 'calendar-cursor-to-date oldf))))
5789
5790 (defun org-agenda-phases-of-moon ()
5791 "Display the phases of the moon for the 3 months around the cursor date."
5792 (interactive)
5793 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5794
5795 (defun org-agenda-holidays ()
5796 "Display the holidays for the 3 months around the cursor date."
5797 (interactive)
5798 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5799
5800 (defun org-agenda-sunrise-sunset (arg)
5801 "Display sunrise and sunset for the cursor date.
5802 Latitude and longitude can be specified with the variables
5803 `calendar-latitude' and `calendar-longitude'. When called with prefix
5804 argument, latitude and longitude will be prompted for."
5805 (interactive "P")
5806 (let ((calendar-longitude (if arg nil calendar-longitude))
5807 (calendar-latitude (if arg nil calendar-latitude))
5808 (calendar-location-name
5809 (if arg "the given coordinates" calendar-location-name)))
5810 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5811
5812 (defun org-agenda-goto-calendar ()
5813 "Open the Emacs calendar with the date at the cursor."
5814 (interactive)
5815 (let* ((day (or (get-text-property (point) 'day)
5816 (error "Don't know which date to open in calendar")))
5817 (date (calendar-gregorian-from-absolute day))
5818 (calendar-move-hook nil)
5819 (view-diary-entries-initially nil))
5820 (calendar)
5821 (calendar-goto-date date)))
5822
5823 (defun org-calendar-goto-agenda ()
5824 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5825 This is a command that has to be installed in `calendar-mode-map'."
5826 (interactive)
5827 (org-agenda nil (calendar-absolute-from-gregorian
5828 (calendar-cursor-to-date))))
5829
5830 (defun org-agenda-convert-date ()
5831 (interactive)
5832 (let ((day (get-text-property (point) 'day))
5833 date s)
5834 (unless day
5835 (error "Don't know which date to convert"))
5836 (setq date (calendar-gregorian-from-absolute day))
5837 (setq s (concat
5838 "Gregorian: " (calendar-date-string date) "\n"
5839 "ISO: " (calendar-iso-date-string date) "\n"
5840 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5841 "Julian: " (calendar-julian-date-string date) "\n"
5842 "Astron. JD: " (calendar-astro-date-string date)
5843 " (Julian date number at noon UTC)\n"
5844 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5845 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5846 "French: " (calendar-french-date-string date) "\n"
5847 "Mayan: " (calendar-mayan-date-string date) "\n"
5848 "Coptic: " (calendar-coptic-date-string date) "\n"
5849 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5850 "Persian: " (calendar-persian-date-string date) "\n"
5851 "Chinese: " (calendar-chinese-date-string date) "\n"))
5852 (with-output-to-temp-buffer "*Dates*"
5853 (princ s))
5854 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5855
5856 ;;; Link Stuff
5857
5858 (defun org-find-file-at-mouse (ev)
5859 "Open file link or URL at mouse."
5860 (interactive "e")
5861 (mouse-set-point ev)
5862 (org-open-at-point 'in-emacs))
5863
5864 (defun org-open-at-mouse (ev)
5865 "Open file link or URL at mouse."
5866 (interactive "e")
5867 (mouse-set-point ev)
5868 (org-open-at-point))
5869
5870 (defun org-open-at-point (&optional in-emacs)
5871 "Open link at or after point.
5872 If there is no link at point, this function will search forward up to
5873 the end of the current subtree.
5874 Normally, files will be opened by an appropriate application. If the
5875 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5876 (interactive "P")
5877 (org-remove-occur-highlights nil nil t)
5878 (if (org-at-timestamp-p)
5879 (org-agenda nil (time-to-days (org-time-string-to-time
5880 (substring (match-string 1) 0 10)))
5881 1)
5882 (let (type path line search (pos (point)))
5883 (catch 'match
5884 (save-excursion
5885 (skip-chars-backward
5886 (concat (if org-allow-space-in-links "^" "^ ")
5887 org-non-link-chars))
5888 (when (looking-at org-link-regexp)
5889 (setq type (match-string 1)
5890 path (match-string 2))
5891 (throw 'match t)))
5892 (save-excursion
5893 (skip-chars-backward "a-zA-Z_")
5894 (when (looking-at org-camel-regexp)
5895 (setq type "camel" path (match-string 0))
5896 (if (equal (char-before) ?*)
5897 (setq path (concat "*" path))))
5898 (throw 'match t))
5899 (save-excursion
5900 (when (re-search-forward
5901 org-link-regexp
5902 (save-excursion
5903 (condition-case nil
5904 (progn (outline-end-of-subtree) (max pos (point)))
5905 (error (end-of-line 1) (point))))
5906 t)
5907 (setq type (match-string 1)
5908 path (match-string 2)))))
5909 (unless path
5910 (error "No link found"))
5911 ;; Remove any trailing spaces in path
5912 (if (string-match " +\\'" path)
5913 (setq path (replace-match "" t t path)))
5914
5915 (cond
5916
5917 ((string= type "camel")
5918 (org-link-search
5919 path
5920 (cond ((equal in-emacs '(4)) 'occur)
5921 ((equal in-emacs '(16)) 'org-occur)
5922 (t nil))))
5923
5924 ((string= type "file")
5925 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
5926 (setq line (string-to-number (match-string 1 path))
5927 path (substring path 0 (match-beginning 0)))
5928 (if (string-match "::\\(.+\\)\\'" path)
5929 (setq search (match-string 1 path)
5930 path (substring path 0 (match-beginning 0)))))
5931 (org-open-file path in-emacs line search))
5932
5933 ((string= type "news")
5934 (org-follow-gnus-link path))
5935
5936 ((string= type "bbdb")
5937 (org-follow-bbdb-link path))
5938
5939 ((string= type "gnus")
5940 (let (group article)
5941 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5942 (error "Error in Gnus link"))
5943 (setq group (match-string 1 path)
5944 article (match-string 3 path))
5945 (org-follow-gnus-link group article)))
5946
5947 ((string= type "vm")
5948 (let (folder article)
5949 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5950 (error "Error in VM link"))
5951 (setq folder (match-string 1 path)
5952 article (match-string 3 path))
5953 ;; in-emacs is the prefix arg, will be interpreted as read-only
5954 (org-follow-vm-link folder article in-emacs)))
5955
5956 ((string= type "wl")
5957 (let (folder article)
5958 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5959 (error "Error in Wanderlust link"))
5960 (setq folder (match-string 1 path)
5961 article (match-string 3 path))
5962 (org-follow-wl-link folder article)))
5963
5964 ((string= type "rmail")
5965 (let (folder article)
5966 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5967 (error "Error in RMAIL link"))
5968 (setq folder (match-string 1 path)
5969 article (match-string 3 path))
5970 (org-follow-rmail-link folder article)))
5971
5972 ((string= type "shell")
5973 (let ((cmd path))
5974 (while (string-match "@{" cmd)
5975 (setq cmd (replace-match "<" t t cmd)))
5976 (while (string-match "@}" cmd)
5977 (setq cmd (replace-match ">" t t cmd)))
5978 (if (or (not org-confirm-shell-links)
5979 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5980 (shell-command cmd)
5981 (error "Abort"))))
5982
5983 (t
5984 (browse-url-at-point))))))
5985
5986 (defun org-link-search (s &optional type)
5987 "Search for a link search option.
5988 When S is a CamelCaseWord, search for a target, or for a sentence containing
5989 the words. If S is surrounded by forward slashes, it is interpreted as a
5990 regular expression. In org-mode files, this will create an `org-occur'
5991 sparse tree. In ordinary files, `occur' will be used to list matched.
5992 If the current buffer is in `dired-mode', grep will be used to search
5993 in all files."
5994 (let ((case-fold-search t)
5995 (s0 s)
5996 (pos (point))
5997 (pre "") (post "")
5998 words re0 re1 re2 re3 re4 re5 reall)
5999 (cond ((string-match "^/\\(.*\\)/$" s)
6000 ;; A regular expression
6001 (cond
6002 ((eq major-mode 'org-mode)
6003 (org-occur (match-string 1 s)))
6004 ;;((eq major-mode 'dired-mode)
6005 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6006 (t (org-do-occur (match-string 1 s)))))
6007 ((string-match (concat "^" org-camel-regexp) s)
6008 ;; A camel
6009 (if (equal (string-to-char s) ?*)
6010 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6011 post "[ \t]*$"
6012 s (substring s 1)))
6013 (remove-text-properties
6014 0 (length s)
6015 '(face nil mouse-face nil keymap nil fontified nil) s)
6016 ;; Make a series of regular expressions to find a match
6017 (setq words (org-camel-to-words s)
6018 re0 (concat "<<" (regexp-quote s0) ">>")
6019 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6020 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6021 re1 (concat pre re2 post)
6022 re3 (concat pre re4 post)
6023 re5 (concat pre ".*" re4)
6024 re2 (concat pre re2)
6025 re4 (concat pre re4)
6026 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6027 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6028 re5 "\\)"
6029 ))
6030 (cond
6031 ((eq type 'org-occur) (org-occur reall))
6032 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6033 (t (goto-char (point-min))
6034 (if (or (re-search-forward re0 nil t)
6035 (re-search-forward re1 nil t)
6036 (re-search-forward re2 nil t)
6037 (re-search-forward re3 nil t)
6038 (re-search-forward re4 nil t)
6039 (re-search-forward re5 nil t))
6040 (goto-char (match-beginning 0))
6041 (goto-char pos)
6042 (error "No match")))))
6043 (t
6044 ;; Normal string-search
6045 (goto-char (point-min))
6046 (if (search-forward s nil t)
6047 (goto-char (match-beginning 0))
6048 (error "No match"))))))
6049
6050 (defun org-do-occur (regexp &optional cleanup)
6051 "Call the Emacs command `occur'.
6052 If CLEANUP is non-nil, remove the printout of the regular expression
6053 in the *Occur* buffer. This is useful if the regex is long and not useful
6054 to read."
6055 (occur regexp)
6056 (when cleanup
6057 (let ((cwin (selected-window)) win beg end)
6058 (when (setq win (get-buffer-window "*Occur*"))
6059 (select-window win))
6060 (goto-char (point-min))
6061 (when (re-search-forward "match[a-z]+" nil t)
6062 (setq beg (match-end 0))
6063 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6064 (setq end (1- (match-beginning 0)))))
6065 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6066 (goto-char (point-min))
6067 (select-window cwin))))
6068
6069 (defun org-camel-to-words (s)
6070 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6071 (let ((case-fold-search nil)
6072 words)
6073 (while (string-match "[a-z][A-Z]" s)
6074 (push (substring s 0 (1+ (match-beginning 0))) words)
6075 (setq s (substring s (1+ (match-beginning 0)))))
6076 (nreverse (cons s words))))
6077
6078 (defun org-follow-bbdb-link (name)
6079 "Follow a BBDB link to NAME."
6080 (require 'bbdb)
6081 (let ((inhibit-redisplay t))
6082 (catch 'exit
6083 ;; Exact match on name
6084 (bbdb-name (concat "\\`" name "\\'") nil)
6085 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6086 ;; Exact match on name
6087 (bbdb-company (concat "\\`" name "\\'") nil)
6088 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6089 ;; Partial match on name
6090 (bbdb-name name nil)
6091 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6092 ;; Partial match on company
6093 (bbdb-company name nil)
6094 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6095 ;; General match including network address and notes
6096 (bbdb name nil)
6097 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6098 (delete-window (get-buffer-window "*BBDB*"))
6099 (error "No matching BBDB record")))))
6100
6101 (defun org-follow-gnus-link (&optional group article)
6102 "Follow a Gnus link to GROUP and ARTICLE."
6103 (require 'gnus)
6104 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6105 (if group (gnus-fetch-group group))
6106 (if article
6107 (or (gnus-summary-goto-article article nil 'force)
6108 (if (fboundp 'gnus-summary-insert-cached-articles)
6109 (progn
6110 (gnus-summary-insert-cached-articles)
6111 (gnus-summary-goto-article article nil 'force))
6112 (message "Message could not be found.")))))
6113
6114 (defun org-follow-vm-link (&optional folder article readonly)
6115 "Follow a VM link to FOLDER and ARTICLE."
6116 (require 'vm)
6117 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6118 ;; ange-ftp or efs or tramp access
6119 (let ((user (or (match-string 1 folder) (user-login-name)))
6120 (host (match-string 2 folder))
6121 (file (match-string 3 folder)))
6122 (cond
6123 ((featurep 'tramp)
6124 ;; use tramp to access the file
6125 (if org-xemacs-p
6126 (setq folder (format "[%s@%s]%s" user host file))
6127 (setq folder (format "/%s@%s:%s" user host file))))
6128 (t
6129 ;; use ange-ftp or efs
6130 (require (if org-xemacs-p 'efs 'ange-ftp))
6131 (setq folder (format "/%s@%s:%s" user host file))))))
6132 (when folder
6133 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6134 (sit-for 0.1)
6135 (when article
6136 (vm-select-folder-buffer)
6137 (widen)
6138 (let ((case-fold-search t))
6139 (goto-char (point-min))
6140 (if (not (re-search-forward
6141 (concat "^" "message-id: *" (regexp-quote article))))
6142 (error "Could not find the specified message in this folder"))
6143 (vm-isearch-update)
6144 (vm-isearch-narrow)
6145 (vm-beginning-of-message)
6146 (vm-summarize)))))
6147
6148 (defun org-follow-wl-link (folder article)
6149 "Follow a Wanderlust link to FOLDER and ARTICLE."
6150 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6151 (if article (wl-summary-jump-to-msg-by-message-id article))
6152 (wl-summary-redisplay))
6153
6154 (defun org-follow-rmail-link (folder article)
6155 "Follow an RMAIL link to FOLDER and ARTICLE."
6156 (let (message-number)
6157 (save-excursion
6158 (save-window-excursion
6159 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6160 (setq message-number
6161 (save-restriction
6162 (widen)
6163 (goto-char (point-max))
6164 (if (re-search-backward
6165 (concat "^Message-ID:\\s-+" (regexp-quote
6166 (or article "")))
6167 nil t)
6168 (rmail-what-message))))))
6169 (if message-number
6170 (progn
6171 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6172 (rmail-show-message message-number)
6173 message-number)
6174 (error "Message not found"))))
6175
6176 (defun org-open-file (path &optional in-emacs line search)
6177 "Open the file at PATH.
6178 First, this expands any special file name abbreviations. Then the
6179 configuration variable `org-file-apps' is checked if it contains an
6180 entry for this file type, and if yes, the corresponding command is launched.
6181 If no application is found, Emacs simply visits the file.
6182 With optional argument IN-EMACS, Emacs will visit the file.
6183 Optional LINE specifies a line to go to, optional SEARCH a string to
6184 search for. If LINE or SEARCH is given, the file will always be
6185 openen in emacs.
6186 If the file does not exist, an error is thrown."
6187 (setq in-emacs (or in-emacs line search))
6188 (let* ((file (if (equal path "")
6189 (buffer-file-name)
6190 (convert-standard-filename (org-expand-file-name path))))
6191 (dfile (downcase file))
6192 ext cmd apps)
6193 (if (and (not (file-exists-p file))
6194 (not org-open-non-existing-files))
6195 (error "No such file: %s" file))
6196 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6197 (setq ext (match-string 1 dfile))
6198 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6199 (setq ext (match-string 1 dfile))))
6200 (setq apps (append org-file-apps (org-default-apps)))
6201 (if in-emacs
6202 (setq cmd 'emacs)
6203 (setq cmd (or (cdr (assoc ext apps))
6204 (cdr (assoc t apps)))))
6205 (cond
6206 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6207 (setq cmd (format cmd (concat "\"" file "\"")))
6208 (save-window-excursion
6209 (shell-command (concat cmd " & &"))))
6210 ((or (stringp cmd)
6211 (eq cmd 'emacs))
6212 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6213 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6214 (if line (goto-line line)
6215 (if search (org-link-search search))))
6216 ((consp cmd)
6217 (eval cmd))
6218 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6219
6220 (defun org-default-apps ()
6221 "Return the default applications for this operating system."
6222 (cond
6223 ((eq system-type 'darwin)
6224 org-file-apps-defaults-macosx)
6225 ((eq system-type 'windows-nt)
6226 org-file-apps-defaults-windowsnt)
6227 (t org-file-apps-defaults-gnu)))
6228
6229 (defun org-expand-file-name (path)
6230 "Replace special path abbreviations and expand the file name."
6231 (expand-file-name path))
6232
6233
6234 (defvar org-insert-link-history nil
6235 "Minibuffer history for links inserted with `org-insert-link'.")
6236
6237 (defvar org-stored-links nil
6238 "Contains the links stored with `org-store-link'.")
6239
6240 ;;;###autoload
6241 (defun org-store-link (arg)
6242 "\\<org-mode-map>Store an org-link to the current location.
6243 This link can later be inserted into an org-buffer with
6244 \\[org-insert-link].
6245 For some link types, a prefix arg is interpreted:
6246 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6247 For file links, arg negates `org-context-in-file-links'."
6248 (interactive "P")
6249 (let (link cpltxt)
6250 (cond
6251
6252 ((eq major-mode 'bbdb-mode)
6253 (setq cpltxt (concat
6254 "bbdb:"
6255 (or (bbdb-record-name (bbdb-current-record))
6256 (bbdb-record-company (bbdb-current-record))))
6257 link (org-make-link cpltxt)))
6258
6259 ((eq major-mode 'calendar-mode)
6260 (let ((cd (calendar-cursor-to-date)))
6261 (setq link
6262 (format-time-string
6263 (car org-time-stamp-formats)
6264 (apply 'encode-time
6265 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6266 nil nil nil))))))
6267
6268 ((or (eq major-mode 'vm-summary-mode)
6269 (eq major-mode 'vm-presentation-mode))
6270 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6271 (vm-follow-summary-cursor)
6272 (save-excursion
6273 (vm-select-folder-buffer)
6274 (let* ((message (car vm-message-pointer))
6275 (folder (buffer-file-name))
6276 (subject (vm-su-subject message))
6277 (author (vm-su-full-name message))
6278 (message-id (vm-su-message-id message)))
6279 (setq folder (abbreviate-file-name folder))
6280 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6281 folder)
6282 (setq folder (replace-match "" t t folder)))
6283 (setq cpltxt (concat author " on: " subject))
6284 (setq link (concat cpltxt "\n "
6285 (org-make-link
6286 "vm:" folder "#" message-id))))))
6287
6288 ((eq major-mode 'wl-summary-mode)
6289 (let* ((msgnum (wl-summary-message-number))
6290 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6291 msgnum 'message-id))
6292 (wl-message-entity (elmo-msgdb-overview-get-entity
6293 msgnum (wl-summary-buffer-msgdb)))
6294 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6295 (subject "???")) ; FIXME: How to get subject of email?
6296 (setq cpltxt (concat author " on: " subject))
6297 (setq link (concat cpltxt "\n "
6298 (org-make-link
6299 "wl:" wl-summary-buffer-folder-name
6300 "#" message-id)))))
6301
6302 ((eq major-mode 'rmail-mode)
6303 (save-excursion
6304 (save-restriction
6305 (rmail-narrow-to-non-pruned-header)
6306 (let ((folder (buffer-file-name))
6307 (message-id (mail-fetch-field "message-id"))
6308 (author (mail-fetch-field "from"))
6309 (subject (mail-fetch-field "subject")))
6310 (setq cpltxt (concat author " on: " subject))
6311 (setq link (concat cpltxt "\n "
6312 (org-make-link
6313 "rmail:" folder "#" message-id)))))))
6314
6315 ((eq major-mode 'gnus-group-mode)
6316 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
6317 (gnus-group-group-name)) ; version
6318 ((fboundp 'gnus-group-name)
6319 (gnus-group-name))
6320 (t "???"))))
6321 (setq cpltxt (concat
6322 (if (org-xor arg org-usenet-links-prefer-google)
6323 "http://groups.google.com/groups?group="
6324 "gnus:")
6325 group)
6326 link (org-make-link cpltxt))))
6327
6328 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
6329 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
6330 (gnus-summary-beginning-of-article)
6331 (let* ((group (car gnus-article-current))
6332 (article (cdr gnus-article-current))
6333 (header (gnus-summary-article-header article))
6334 (author (mail-header-from header))
6335 (message-id (mail-header-id header))
6336 (date (mail-header-date header))
6337 (subject (gnus-summary-subject-string)))
6338 (setq cpltxt (concat author " on: " subject))
6339 (if (org-xor arg org-usenet-links-prefer-google)
6340 (setq link
6341 (concat
6342 cpltxt "\n "
6343 (format "http://groups.google.com/groups?as_umsgid=%s"
6344 (org-fixup-message-id-for-http message-id))))
6345 (setq link (concat cpltxt "\n"
6346 (org-make-link
6347 "gnus:" group
6348 "#" (number-to-string article)))))))
6349
6350 ((eq major-mode 'w3-mode)
6351 (setq cpltxt (url-view-url t)
6352 link (org-make-link cpltxt)))
6353 ((eq major-mode 'w3m-mode)
6354 (setq cpltxt w3m-current-url
6355 link (org-make-link cpltxt)))
6356
6357 ((eq major-mode 'org-mode)
6358 ;; Just link to current headline
6359 (setq cpltxt (concat "file:"
6360 (abbreviate-file-name (buffer-file-name))))
6361 ;; Add a context search string
6362 (when (org-xor org-context-in-file-links arg)
6363 (if (save-excursion
6364 (skip-chars-backward "a-zA-Z<")
6365 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
6366 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6367 (setq cpltxt
6368 (concat cpltxt "::"
6369 (org-make-org-heading-camel
6370 (cond
6371 ((org-on-heading-p) nil)
6372 ((org-region-active-p)
6373 (buffer-substring (region-beginning) (region-end)))
6374 (t (buffer-substring (point-at-bol) (point-at-eol))))
6375 )))))
6376 (setq link (org-make-link cpltxt)))
6377
6378 ((buffer-file-name)
6379 ;; Just link to this file here.
6380 (setq cpltxt (concat "file:"
6381 (abbreviate-file-name (buffer-file-name))))
6382 ;; Add a context string
6383 (when (org-xor org-context-in-file-links arg)
6384 (setq cpltxt
6385 (concat cpltxt "::"
6386 (org-make-org-heading-camel
6387 (if (org-region-active-p)
6388 (buffer-substring (region-beginning) (region-end))
6389 (buffer-substring (point-at-bol) (point-at-eol)))))))
6390 (setq link (org-make-link cpltxt)))
6391
6392 ((interactive-p)
6393 (error "Cannot link to a buffer which is not visiting a file"))
6394
6395 (t (setq link nil)))
6396
6397 (if (and (interactive-p) link)
6398 (progn
6399 (setq org-stored-links
6400 (cons (cons (or cpltxt link) link) org-stored-links))
6401 (message "Stored: %s" (or cpltxt link)))
6402 link)))
6403
6404 (defun org-make-org-heading-camel (&optional string)
6405 "Make a CamelCase string for S or the current headline."
6406 (interactive)
6407 (let ((s (or string (org-get-heading))))
6408 (unless string
6409 ;; We are using a headline, clean up garbage in there.
6410 (if (string-match org-todo-regexp s)
6411 (setq s (replace-match "" t t s)))
6412 (setq s (org-trim s))
6413 (if (string-match (concat "^\\(" org-quote-string "\\|"
6414 org-comment-string "\\)") s)
6415 (setq s (replace-match "" t t s)))
6416 (while (string-match org-ts-regexp s)
6417 (setq s (replace-match "" t t s))))
6418 (while (string-match "[^a-zA-Z_ \t]+" s)
6419 (setq s (replace-match " " t t s)))
6420 (or string (setq s (concat "*" s))) ; Add * for headlines
6421 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
6422
6423 (defun org-make-link (&rest strings)
6424 "Concatenate STRINGS, format resulting string with `org-link-format'."
6425 (format org-link-format (apply 'concat strings)))
6426
6427 (defun org-xor (a b)
6428 "Exclusive or."
6429 (if a (not b) b))
6430
6431 (defun org-get-header (header)
6432 "Find a header field in the current buffer."
6433 (save-excursion
6434 (goto-char (point-min))
6435 (let ((case-fold-search t) s)
6436 (cond
6437 ((eq header 'from)
6438 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6439 (setq s (match-string 1)))
6440 (while (string-match "\"" s)
6441 (setq s (replace-match "" t t s)))
6442 (if (string-match "[<(].*" s)
6443 (setq s (replace-match "" t t s))))
6444 ((eq header 'message-id)
6445 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6446 (setq s (match-string 1))))
6447 ((eq header 'subject)
6448 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6449 (setq s (match-string 1)))))
6450 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6451 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6452 s)))
6453
6454
6455 (defun org-fixup-message-id-for-http (s)
6456 "Replace special characters in a message id, so it can be used in an http query."
6457 (while (string-match "<" s)
6458 (setq s (replace-match "%3C" t t s)))
6459 (while (string-match ">" s)
6460 (setq s (replace-match "%3E" t t s)))
6461 (while (string-match "@" s)
6462 (setq s (replace-match "%40" t t s)))
6463 s)
6464
6465 (defun org-insert-link (&optional complete-file)
6466 "Insert a link. At the prompt, enter the link.
6467
6468 Completion can be used to select a link previously stored with
6469 `org-store-link'. When the empty string is entered (i.e. if you just
6470 press RET at the prompt), the link defaults to the most recently
6471 stored link. As SPC triggers completion in the minibuffer, you need to
6472 use M-SPC or C-q SPC to force the insertion of a space character.
6473
6474 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
6475 selected using completion. The path to the file will be relative to
6476 the current directory if the file is in the current directory or a
6477 subdirectory. Otherwise, the link will be the absolute path as
6478 completed in the minibuffer (i.e. normally ~/path/to/file).
6479
6480 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
6481 is in the current directory or below."
6482 (interactive "P")
6483 (let ((link (if complete-file
6484 (read-file-name "File: ")
6485 (completing-read
6486 "Link: " org-stored-links nil nil nil
6487 org-insert-link-history
6488 (or (car (car org-stored-links))))))
6489 linktxt matched)
6490 (if (or (not link) (equal link ""))
6491 (error "No links available"))
6492 (if complete-file
6493 (let ((pwd (file-name-as-directory (expand-file-name "."))))
6494 (cond
6495 ((equal complete-file '(16))
6496 (insert
6497 (org-make-link
6498 "file:" (abbreviate-file-name (expand-file-name link)))))
6499 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6500 (expand-file-name link))
6501 (insert
6502 (org-make-link
6503 "file:" (match-string 1 (expand-file-name link)))))
6504 (t (insert (org-make-link "file:" link)))))
6505 (setq linktxt (cdr (assoc link org-stored-links)))
6506 (if (not org-keep-stored-link-after-insertion)
6507 (setq org-stored-links (delq (assoc link org-stored-links)
6508 org-stored-links)))
6509 (if (not linktxt) (setq link (org-make-link link)))
6510 (setq link (or linktxt link))
6511 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
6512 (let* ((path (match-string 1 link))
6513 (case-fold-search nil)
6514 (search (match-string 2 link)))
6515 (when (save-match-data
6516 (equal (file-truename (buffer-file-name))
6517 (file-truename path)))
6518 (if (save-match-data
6519 (string-match (concat "^" org-camel-regexp "$") search))
6520 (setq link (replace-match search t t link)
6521 matched t)
6522 (setq link (replace-match (concat "<file:::" search ">")
6523 t t link))))))
6524 (let ((lines (org-split-string link "\n")))
6525 (insert (car lines))
6526 (setq matched (or matched (string-match org-link-regexp (car lines))))
6527 (setq lines (cdr lines))
6528 (while lines
6529 (insert "\n")
6530 (if (save-excursion
6531 (beginning-of-line 0)
6532 (looking-at "[ \t]+\\S-"))
6533 (indent-relative))
6534 (setq matched (or matched
6535 (string-match org-link-regexp (car lines))))
6536 (insert (car lines))
6537 (setq lines (cdr lines))))
6538 (unless matched
6539 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
6540
6541 ;;; Hooks for remember.el
6542 ;;;###autoload
6543 (defun org-remember-annotation ()
6544 "Return a link to the current location as an annotation for remember.el.
6545 If you are using Org-mode files as target for data storage with
6546 remember.el, then the annotations should include a link compatible with the
6547 conventions in Org-mode. This function returns such a link."
6548 (org-store-link nil))
6549
6550 (defconst org-remember-help
6551 "Select a destination location for the note.
6552 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
6553 RET at beg-of-buf -> Append to file as level 2 headline
6554 RET on headline -> Store as sublevel entry to current headline
6555 <left>/<right> -> before/after current headline, same headings level")
6556
6557 ;;;###autoload
6558 (defun org-remember-handler ()
6559 "Store stuff from remember.el into an org file.
6560 First prompts for an org file. If the user just presses return, the value
6561 of `org-default-notes-file' is used.
6562 Then the command offers the headings tree of the selected file in order to
6563 file the text at a specific location.
6564 You can either immediately press RET to get the note appended to the
6565 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
6566 find a better place. Then press RET or <left> or <right> in insert the note.
6567
6568 Key Cursor position Note gets inserted
6569 -----------------------------------------------------------------------------
6570 RET buffer-start as level 2 heading at end of file
6571 RET on headline as sublevel of the heading at cursor
6572 RET no heading at cursor position, level taken from context.
6573 Or use prefix arg to specify level manually.
6574 <left> on headline as same level, before current heading
6575 <right> on headline as same level, after current heading
6576
6577 So the fastest way to store the note is to press RET RET to append it to
6578 the default file. This way your current train of thought is not
6579 interrupted, in accordance with the principles of remember.el. But with
6580 little extra effort, you can push it directly to the correct location.
6581
6582 Before being stored away, the function ensures that the text has a
6583 headline, i.e. a first line that starts with a \"*\". If not, a headline
6584 is constructed from the current date and some additional data.
6585
6586 If the variable `org-adapt-indentation' is non-nil, the entire text is
6587 also indented so that it starts in the same column as the headline
6588 \(i.e. after the stars).
6589
6590 See also the variable `org-reverse-note-order'."
6591 (catch 'quit
6592 (let* ((txt (buffer-substring (point-min) (point-max)))
6593 (fastp current-prefix-arg)
6594 (file (if fastp org-default-notes-file (org-get-org-file)))
6595 (visiting (find-buffer-visiting file))
6596 (org-startup-with-deadline-check nil)
6597 (org-startup-folded nil)
6598 spos level indent reversed)
6599 ;; Modify text so that it becomes a nice subtree which can be inserted
6600 ;; into an org tree.
6601 (let* ((lines (split-string txt "\n"))
6602 (first (car lines))
6603 (lines (cdr lines)))
6604 (if (string-match "^\\*+" first)
6605 ;; Is already a headline
6606 (setq indent (make-string (- (match-end 0) (match-beginning 0)
6607 -1) ?\ ))
6608 ;; We need to add a headline: Use time and first buffer line
6609 (setq lines (cons first lines)
6610 first (concat "* " (current-time-string)
6611 " (" (remember-buffer-desc) ")")
6612 indent " "))
6613 (if org-adapt-indentation
6614 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
6615 (setq txt (concat first "\n"
6616 (mapconcat 'identity lines "\n"))))
6617 ;; Find the file
6618 (if (not visiting)
6619 (find-file-noselect file))
6620 (with-current-buffer (get-file-buffer file)
6621 (setq reversed (org-notes-order-reversed-p))
6622 (save-excursion
6623 (save-restriction
6624 (widen)
6625 ;; Ask the User for a location
6626 (setq spos (if fastp 1 (org-get-location
6627 (current-buffer)
6628 org-remember-help)))
6629 (if (not spos) (throw 'quit nil)) ; return nil to show we did
6630 ; not handle this note
6631 (goto-char spos)
6632 (cond ((bobp)
6633 ;; Put it at the start or end, as level 2
6634 (save-restriction
6635 (widen)
6636 (goto-char (if reversed (point-min) (point-max)))
6637 (if (not (bolp)) (newline))
6638 (org-paste-subtree (or current-prefix-arg 2) txt)))
6639 ((and (org-on-heading-p nil) (not current-prefix-arg))
6640 ;; Put it below this entry, at the beg/end of the subtree
6641 (org-back-to-heading)
6642 (setq level (outline-level))
6643 (if reversed
6644 (outline-end-of-heading)
6645 (outline-end-of-subtree))
6646 (if (not (bolp)) (newline))
6647 (beginning-of-line 1)
6648 (org-paste-subtree (1+ level) txt))
6649 (t
6650 ;; Put it right there, with automatic level determined by
6651 ;; org-paste-subtree or from prefix arg
6652 (org-paste-subtree current-prefix-arg txt)))
6653 (when remember-save-after-remembering
6654 (save-buffer)
6655 (if (not visiting) (kill-buffer (current-buffer)))))))))
6656 t) ;; return t to indicate that we took care of this note.
6657
6658 (defun org-get-org-file ()
6659 "Read a filename, with default directory `org-directory'."
6660 (let ((default (or org-default-notes-file remember-data-file)))
6661 (read-file-name (format "File name [%s]: " default)
6662 (file-name-as-directory org-directory)
6663 default)))
6664
6665 (defun org-notes-order-reversed-p ()
6666 "Check if the current file should receive notes in reversed order."
6667 (cond
6668 ((not org-reverse-note-order) nil)
6669 ((eq t org-reverse-note-order) t)
6670 ((not (listp org-reverse-note-order)) nil)
6671 (t (catch 'exit
6672 (let ((all org-reverse-note-order)
6673 entry)
6674 (while (setq entry (pop all))
6675 (if (string-match (car entry) (buffer-file-name))
6676 (throw 'exit (cdr entry))))
6677 nil)))))
6678
6679 ;;; Tables
6680
6681 ;; Watch out: Here we are talking about two different kind of tables.
6682 ;; Most of the code is for the tables created with the Org-mode table editor.
6683 ;; Sometimes, we talk about tables created and edited with the table.el
6684 ;; Emacs package. We call the former org-type tables, and the latter
6685 ;; table.el-type tables.
6686
6687
6688 (defun org-before-change-function (beg end)
6689 "Every change indicates that a table might need an update."
6690 (setq org-table-may-need-update t))
6691
6692 (defconst org-table-line-regexp "^[ \t]*|"
6693 "Detects an org-type table line.")
6694 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6695 "Detects an org-type table line.")
6696 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6697 "Detects a table line marked for automatic recalculation.")
6698 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6699 "Detects a table line marked for automatic recalculation.")
6700 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6701 "Detects a table line marked for automatic recalculation.")
6702 (defconst org-table-hline-regexp "^[ \t]*|-"
6703 "Detects an org-type table hline.")
6704 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6705 "Detects a table-type table hline.")
6706 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6707 "Detects an org-type or table-type table.")
6708 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6709 "Searching from within a table (any type) this finds the first line
6710 outside the table.")
6711 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6712 "Searching from within a table (any type) this finds the first line
6713 outside the table.")
6714
6715 (defun org-table-create-with-table.el ()
6716 "Use the table.el package to insert a new table.
6717 If there is already a table at point, convert between Org-mode tables
6718 and table.el tables."
6719 (interactive)
6720 (require 'table)
6721 (cond
6722 ((org-at-table.el-p)
6723 (if (y-or-n-p "Convert table to Org-mode table? ")
6724 (org-table-convert)))
6725 ((org-at-table-p)
6726 (if (y-or-n-p "Convert table to table.el table? ")
6727 (org-table-convert)))
6728 (t (call-interactively 'table-insert))))
6729
6730 (defun org-table-create (&optional size)
6731 "Query for a size and insert a table skeleton.
6732 SIZE is a string Columns x Rows like for example \"3x2\"."
6733 (interactive "P")
6734 (unless size
6735 (setq size (read-string
6736 (concat "Table size Columns x Rows [e.g. "
6737 org-table-default-size "]: ")
6738 "" nil org-table-default-size)))
6739
6740 (let* ((pos (point))
6741 (indent (make-string (current-column) ?\ ))
6742 (split (org-split-string size " *x *"))
6743 (rows (string-to-number (nth 1 split)))
6744 (columns (string-to-number (car split)))
6745 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6746 "\n")))
6747 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6748 (point-at-bol) (point)))
6749 (beginning-of-line 1)
6750 (newline))
6751 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6752 (dotimes (i rows) (insert line))
6753 (goto-char pos)
6754 (if (> rows 1)
6755 ;; Insert a hline after the first row.
6756 (progn
6757 (end-of-line 1)
6758 (insert "\n|-")
6759 (goto-char pos)))
6760 (org-table-align)))
6761
6762 (defun org-table-convert-region (beg0 end0 nspace)
6763 "Convert region to a table.
6764 The region goes from BEG0 to END0, but these borders will be moved
6765 slightly, to make sure a beginning of line in the first line is included.
6766 When NSPACE is non-nil, it indicates the minimum number of spaces that
6767 separate columns (default: just one space)"
6768 (let* ((beg (min beg0 end0))
6769 (end (max beg0 end0))
6770 (tabsep t)
6771 re)
6772 (goto-char beg)
6773 (beginning-of-line 1)
6774 (setq beg (move-marker (make-marker) (point)))
6775 (goto-char end)
6776 (if (bolp) (backward-char 1) (end-of-line 1))
6777 (setq end (move-marker (make-marker) (point)))
6778 ;; Lets see if this is tab-separated material. If every nonempty line
6779 ;; contains a tab, we will assume that it is tab-separated material
6780 (if nspace
6781 (setq tabsep nil)
6782 (goto-char beg)
6783 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6784 (if nspace (setq tabsep nil))
6785 (if tabsep
6786 (setq re "^\\|\t")
6787 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6788 (max 1 (prefix-numeric-value nspace)))))
6789 (goto-char beg)
6790 (while (re-search-forward re end t)
6791 (replace-match "|" t t))
6792 (goto-char beg)
6793 (insert " ")
6794 (org-table-align)))
6795
6796 (defun org-table-import (file arg)
6797 "Import FILE as a table.
6798 The file is assumed to be tab-separated. Such files can be produced by most
6799 spreadsheet and database applications. If no tabs (at least one per line)
6800 are found, lines will be split on whitespace into fields."
6801 (interactive "f\nP")
6802 (or (bolp) (newline))
6803 (let ((beg (point))
6804 (pm (point-max)))
6805 (insert-file-contents file)
6806 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6807
6808 (defun org-table-export ()
6809 "Export table as a tab-separated file.
6810 Such a file can be imported into a spreadsheet program like Excel."
6811 (interactive)
6812 (let* ((beg (org-table-begin))
6813 (end (org-table-end))
6814 (table (buffer-substring beg end))
6815 (file (read-file-name "Export table to: "))
6816 buf)
6817 (unless (or (not (file-exists-p file))
6818 (y-or-n-p (format "Overwrite file %s? " file)))
6819 (error "Abort"))
6820 (with-current-buffer (find-file-noselect file)
6821 (setq buf (current-buffer))
6822 (erase-buffer)
6823 (fundamental-mode)
6824 (insert table)
6825 (goto-char (point-min))
6826 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6827 (replace-match "" t t)
6828 (end-of-line 1))
6829 (goto-char (point-min))
6830 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6831 (replace-match "" t t)
6832 (goto-char (min (1+ (point)) (point-max))))
6833 (goto-char (point-min))
6834 (while (re-search-forward "^-[-+]*$" nil t)
6835 (replace-match "")
6836 (if (looking-at "\n")
6837 (delete-char 1)))
6838 (goto-char (point-min))
6839 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6840 (replace-match "\t" t t))
6841 (save-buffer))
6842 (kill-buffer buf)))
6843
6844 (defvar org-table-aligned-begin-marker (make-marker)
6845 "Marker at the beginning of the table last aligned.
6846 Used to check if cursor still is in that table, to minimize realignment.")
6847 (defvar org-table-aligned-end-marker (make-marker)
6848 "Marker at the end of the table last aligned.
6849 Used to check if cursor still is in that table, to minimize realignment.")
6850 (defvar org-table-last-alignment nil
6851 "List of flags for flushright alignment, from the last re-alignment.
6852 This is being used to correctly align a single field after TAB or RET.")
6853 ;; FIXME: The following is currently not used.
6854 (defvar org-table-last-column-widths nil
6855 "List of max width of fields in each column.
6856 This is being used to correctly align a single field after TAB or RET.")
6857
6858 (defvar org-last-recalc-line nil)
6859
6860 (defun org-table-align ()
6861 "Align the table at point by aligning all vertical bars."
6862 (interactive)
6863 ;; (message "align") (sit-for 2)
6864 (let* (
6865 ;; Limits of table
6866 (beg (org-table-begin))
6867 (end (org-table-end))
6868 ;; Current cursor position
6869 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6870 (colpos (org-table-current-column))
6871 (winstart (window-start))
6872 text lines (new "") lengths l typenums ty fields maxfields i
6873 column
6874 (indent "") cnt frac
6875 rfmt hfmt
6876 (spaces (if (org-in-invisibility-spec-p '(org-table))
6877 org-table-spaces-around-invisible-separators
6878 org-table-spaces-around-separators))
6879 (sp1 (car spaces))
6880 (sp2 (cdr spaces))
6881 (rfmt1 (concat
6882 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6883 (hfmt1 (concat
6884 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6885 emptystrings)
6886 (untabify beg end)
6887 ;; (message "Aligning table...")
6888 ;; Get the rows
6889 (setq lines (org-split-string
6890 (buffer-substring-no-properties beg end) "\n"))
6891 ;; Store the indentation of the first line
6892 (if (string-match "^ *" (car lines))
6893 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6894 ;; Mark the hlines
6895 (setq lines (mapcar (lambda (l)
6896 (if (string-match "^ *|-" l)
6897 nil
6898 (if (string-match "[ \t]+$" l)
6899 (substring l 0 (match-beginning 0))
6900 l)))
6901 lines))
6902 ;; Get the data fields
6903 (setq fields (mapcar
6904 (lambda (l)
6905 (org-split-string l " *| *"))
6906 (delq nil (copy-sequence lines))))
6907 ;; How many fields in the longest line?
6908 (condition-case nil
6909 (setq maxfields (apply 'max (mapcar 'length fields)))
6910 (error
6911 (kill-region beg end)
6912 (org-table-create org-table-default-size)
6913 (error "Empty table - created default table")))
6914 ;; A list of empty string to fill any short rows on output
6915 (setq emptystrings (make-list maxfields ""))
6916 ;; Get the maximum length of a field and the most common datatype
6917 ;; for each column
6918 (setq i -1)
6919 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6920 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6921 ;; maximum length
6922 (push (apply 'max 1 (mapcar 'length column)) lengths)
6923 ;; compute the fraction stepwise, ignoring empty fields
6924 (setq cnt 0 frac 0.0)
6925 (mapcar
6926 (lambda (x)
6927 (if (equal x "")
6928 nil
6929 (setq frac ( / (+ (* frac cnt)
6930 (if (string-match org-table-number-regexp x) 1 0))
6931 (setq cnt (1+ cnt))))))
6932 column)
6933 (push (>= frac org-table-number-fraction) typenums))
6934 (setq lengths (nreverse lengths)
6935 typenums (nreverse typenums))
6936 (setq org-table-last-alignment typenums
6937 org-table-last-column-widths lengths)
6938 ;; Compute the formats needed for output of the table
6939 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6940 (while (setq l (pop lengths))
6941 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6942 (setq rfmt (concat rfmt (format rfmt1 ty l))
6943 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6944 (setq rfmt (concat rfmt "\n")
6945 hfmt (concat (substring hfmt 0 -1) "|\n"))
6946 ;; Produce the new table
6947 ;;(while lines
6948 ;; (setq l (pop lines))
6949 ;; (if l
6950 ;; (setq new (concat new (apply 'format rfmt
6951 ;; (append (pop fields) emptystrings))))
6952 ;; (setq new (concat new hfmt))))
6953 (setq new (mapconcat
6954 (lambda (l)
6955 (if l (apply 'format rfmt
6956 (append (pop fields) emptystrings))
6957 hfmt))
6958 lines ""))
6959 ;; Replace the old one
6960 (delete-region beg end)
6961 (move-marker end nil)
6962 (move-marker org-table-aligned-begin-marker (point))
6963 (insert new)
6964 (move-marker org-table-aligned-end-marker (point))
6965 ;; Try to move to the old location (approximately)
6966 (goto-line linepos)
6967 (set-window-start (selected-window) winstart 'noforce)
6968 (org-table-goto-column colpos)
6969 (setq org-table-may-need-update nil)
6970 (if (org-in-invisibility-spec-p '(org-table))
6971 (org-table-add-invisible-to-vertical-lines))
6972 ))
6973
6974 (defun org-table-begin (&optional table-type)
6975 "Find the beginning of the table and return its position.
6976 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6977 (save-excursion
6978 (if (not (re-search-backward
6979 (if table-type org-table-any-border-regexp
6980 org-table-border-regexp)
6981 nil t))
6982 (error "Can't find beginning of table")
6983 (goto-char (match-beginning 0))
6984 (beginning-of-line 2)
6985 (point))))
6986
6987 (defun org-table-end (&optional table-type)
6988 "Find the end of the table and return its position.
6989 With argument TABLE-TYPE, go to the end of a table.el-type table."
6990 (save-excursion
6991 (if (not (re-search-forward
6992 (if table-type org-table-any-border-regexp
6993 org-table-border-regexp)
6994 nil t))
6995 (goto-char (point-max))
6996 (goto-char (match-beginning 0)))
6997 (point-marker)))
6998
6999 (defun org-table-justify-field-maybe (&optional new)
7000 "Justify the current field, text to left, number to right.
7001 Optional argument NEW may specify text to replace the current field content."
7002 (cond
7003 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7004 ((org-at-table-hline-p)
7005 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7006 ;; (setq org-table-may-need-update t)
7007 )
7008 ((and (not new)
7009 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7010 (current-buffer)))
7011 (< (point) org-table-aligned-begin-marker)
7012 (>= (point) org-table-aligned-end-marker)))
7013 ;; This is not the same table, force a full re-align
7014 (setq org-table-may-need-update t))
7015 (t ;; realign the current field, based on previous full realign
7016 (let* ((pos (point)) s
7017 (col (org-table-current-column))
7018 (num (nth (1- col) org-table-last-alignment))
7019 l f n o e)
7020 (when (> col 0)
7021 (skip-chars-backward "^|\n")
7022 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7023 (progn
7024 (setq s (match-string 1)
7025 o (match-string 0)
7026 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7027 e (not (= (match-beginning 2) (match-end 2))))
7028 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7029 l (if e "|" (setq org-table-may-need-update t) ""))
7030 n (format f s t t))
7031 (if new
7032 (if (<= (length new) l)
7033 (setq n (format f new t t)) ;; FIXME: why t t?????
7034 (setq n (concat new "|") org-table-may-need-update t)))
7035 (or (equal n o)
7036 (let (org-table-may-need-update)
7037 (replace-match n))))
7038 (setq org-table-may-need-update t))
7039 (goto-char pos))))))
7040
7041 (defun org-table-next-field ()
7042 "Go to the next field in the current table, creating new lines as needed.
7043 Before doing so, re-align the table if necessary."
7044 (interactive)
7045 (org-table-maybe-eval-formula)
7046 (org-table-maybe-recalculate-line)
7047 (if (and org-table-automatic-realign
7048 org-table-may-need-update)
7049 (org-table-align))
7050 (let ((end (org-table-end)))
7051 (if (org-at-table-hline-p)
7052 (end-of-line 1))
7053 (condition-case nil
7054 (progn
7055 (re-search-forward "|" end)
7056 (if (looking-at "[ \t]*$")
7057 (re-search-forward "|" end))
7058 (if (and (looking-at "-")
7059 org-table-tab-jumps-over-hlines
7060 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7061 (goto-char (match-beginning 1)))
7062 (if (looking-at "-")
7063 (progn
7064 (beginning-of-line 0)
7065 (org-table-insert-row 'below))
7066 (if (looking-at " ") (forward-char 1))))
7067 (error
7068 (org-table-insert-row 'below)))))
7069
7070 (defun org-table-previous-field ()
7071 "Go to the previous field in the table.
7072 Before doing so, re-align the table if necessary."
7073 (interactive)
7074 (org-table-justify-field-maybe)
7075 (org-table-maybe-recalculate-line)
7076 (if (and org-table-automatic-realign
7077 org-table-may-need-update)
7078 (org-table-align))
7079 (if (org-at-table-hline-p)
7080 (end-of-line 1))
7081 (re-search-backward "|" (org-table-begin))
7082 (re-search-backward "|" (org-table-begin))
7083 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7084 (re-search-backward "|" (org-table-begin)))
7085 (if (looking-at "| ?")
7086 (goto-char (match-end 0))))
7087
7088 (defun org-table-next-row ()
7089 "Go to the next row (same column) in the current table.
7090 Before doing so, re-align the table if necessary."
7091 (interactive)
7092 (org-table-maybe-eval-formula)
7093 (org-table-maybe-recalculate-line)
7094 (if (or (looking-at "[ \t]*$")
7095 (save-excursion (skip-chars-backward " \t") (bolp)))
7096 (newline)
7097 (if (and org-table-automatic-realign
7098 org-table-may-need-update)
7099 (org-table-align))
7100 (let ((col (org-table-current-column)))
7101 (beginning-of-line 2)
7102 (if (or (not (org-at-table-p))
7103 (org-at-table-hline-p))
7104 (progn
7105 (beginning-of-line 0)
7106 (org-table-insert-row 'below)))
7107 (org-table-goto-column col)
7108 (skip-chars-backward "^|\n\r")
7109 (if (looking-at " ") (forward-char 1)))))
7110
7111 (defun org-table-copy-down (n)
7112 "Copy a field down in the current column.
7113 If the field at the cursor is empty, copy into it the content of the nearest
7114 non-empty field above. With argument N, use the Nth non-empty field.
7115 If the current field is not empty, it is copied down to the next row, and
7116 the cursor is moved with it. Therefore, repeating this command causes the
7117 column to be filled row-by-row.
7118 If the variable `org-table-copy-increment' is non-nil and the field is an
7119 integer, it will be incremented while copying."
7120 (interactive "p")
7121 (let* ((colpos (org-table-current-column))
7122 (field (org-table-get-field))
7123 (non-empty (string-match "[^ \t]" field))
7124 (beg (org-table-begin))
7125 txt)
7126 (org-table-check-inside-data-field)
7127 (if non-empty
7128 (progn
7129 (setq txt (org-trim field))
7130 (org-table-next-row)
7131 (org-table-blank-field))
7132 (save-excursion
7133 (setq txt
7134 (catch 'exit
7135 (while (progn (beginning-of-line 1)
7136 (re-search-backward org-table-dataline-regexp
7137 beg t))
7138 (org-table-goto-column colpos t)
7139 (if (and (looking-at
7140 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7141 (= (setq n (1- n)) 0))
7142 (throw 'exit (match-string 1))))))))
7143 (if txt
7144 (progn
7145 (if (and org-table-copy-increment
7146 (string-match "^[0-9]+$" txt))
7147 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7148 (insert txt)
7149 (org-table-maybe-recalculate-line)
7150 (org-table-align))
7151 (error "No non-empty field found"))))
7152
7153 (defun org-table-check-inside-data-field ()
7154 "Is point inside a table data field?
7155 I.e. not on a hline or before the first or after the last column?
7156 This actually throws an error, so it aborts the current command."
7157 (if (or (not (org-at-table-p))
7158 (= (org-table-current-column) 0)
7159 (org-at-table-hline-p)
7160 (looking-at "[ \t]*$"))
7161 (error "Not in table data field")))
7162
7163 (defvar org-table-clip nil
7164 "Clipboard for table regions.")
7165
7166 (defun org-table-blank-field ()
7167 "Blank the current table field or active region."
7168 (interactive)
7169 (org-table-check-inside-data-field)
7170 (if (and (interactive-p) (org-region-active-p))
7171 (let (org-table-clip)
7172 (org-table-cut-region (region-beginning) (region-end)))
7173 (skip-chars-backward "^|")
7174 (backward-char 1)
7175 (if (looking-at "|[^|\n]+")
7176 (let* ((pos (match-beginning 0))
7177 (match (match-string 0))
7178 (len (length match)))
7179 (replace-match (concat "|" (make-string (1- len) ?\ )))
7180 (goto-char (+ 2 pos))
7181 (substring match 1)))))
7182
7183 (defun org-table-get-field (&optional n replace)
7184 "Return the value of the field in column N of current row.
7185 N defaults to current field.
7186 If REPLACE is a string, replace field with this value. The return value
7187 is always the old value."
7188 (and n (org-table-goto-column n))
7189 (skip-chars-backward "^|\n")
7190 (backward-char 1)
7191 (if (looking-at "|[^|\r\n]*")
7192 (let* ((pos (match-beginning 0))
7193 (val (buffer-substring (1+ pos) (match-end 0))))
7194 (if replace
7195 (replace-match (concat "|" replace)))
7196 (goto-char (min (point-at-eol) (+ 2 pos)))
7197 val)
7198 (forward-char 1) ""))
7199
7200 (defun org-table-current-column ()
7201 "Find out which column we are in.
7202 When called interactively, column is also displayed in echo area."
7203 (interactive)
7204 (if (interactive-p) (org-table-check-inside-data-field))
7205 (save-excursion
7206 (let ((cnt 0) (pos (point)))
7207 (beginning-of-line 1)
7208 (while (search-forward "|" pos t)
7209 (setq cnt (1+ cnt)))
7210 (if (interactive-p) (message "This is table column %d" cnt))
7211 cnt)))
7212
7213 (defun org-table-goto-column (n &optional on-delim force)
7214 "Move the cursor to the Nth column in the current table line.
7215 With optional argument ON-DELIM, stop with point before the left delimiter
7216 of the field.
7217 If there are less than N fields, just go to after the last delimiter.
7218 However, when FORCE is non-nil, create new columns if necessary."
7219 (interactive "p")
7220 (let ((pos (point-at-eol)))
7221 (beginning-of-line 1)
7222 (when (> n 0)
7223 (while (and (> (setq n (1- n)) -1)
7224 (or (search-forward "|" pos t)
7225 (and force
7226 (progn (end-of-line 1)
7227 (skip-chars-backward "^|")
7228 (insert " | "))))))
7229 ; (backward-char 2) t)))))
7230 (when (and force (not (looking-at ".*|")))
7231 (save-excursion (end-of-line 1) (insert " | ")))
7232 (if on-delim
7233 (backward-char 1)
7234 (if (looking-at " ") (forward-char 1))))))
7235
7236 (defun org-at-table-p (&optional table-type)
7237 "Return t if the cursor is inside an org-type table.
7238 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7239 (if org-enable-table-editor
7240 (save-excursion
7241 (beginning-of-line 1)
7242 (looking-at (if table-type org-table-any-line-regexp
7243 org-table-line-regexp)))
7244 nil))
7245
7246 (defun org-at-table.el-p ()
7247 "Return t if and only if we are at a table.el table."
7248 (and (org-at-table-p 'any)
7249 (save-excursion
7250 (goto-char (org-table-begin 'any))
7251 (looking-at org-table1-hline-regexp))))
7252
7253 (defun org-table-recognize-table.el ()
7254 "If there is a table.el table nearby, recognize it and move into it."
7255 (if org-table-tab-recognizes-table.el
7256 (if (org-at-table.el-p)
7257 (progn
7258 (beginning-of-line 1)
7259 (if (looking-at org-table-dataline-regexp)
7260 nil
7261 (if (looking-at org-table1-hline-regexp)
7262 (progn
7263 (beginning-of-line 2)
7264 (if (looking-at org-table-any-border-regexp)
7265 (beginning-of-line -1)))))
7266 (if (re-search-forward "|" (org-table-end t) t)
7267 (progn
7268 (require 'table)
7269 (if (table--at-cell-p (point))
7270 t
7271 (message "recognizing table.el table...")
7272 (table-recognize-table)
7273 (message "recognizing table.el table...done")))
7274 (error "This should not happen..."))
7275 t)
7276 nil)
7277 nil))
7278
7279 (defun org-at-table-hline-p ()
7280 "Return t if the cursor is inside a hline in a table."
7281 (if org-enable-table-editor
7282 (save-excursion
7283 (beginning-of-line 1)
7284 (looking-at org-table-hline-regexp))
7285 nil))
7286
7287 (defun org-table-insert-column ()
7288 "Insert a new column into the table."
7289 (interactive)
7290 (if (not (org-at-table-p))
7291 (error "Not at a table"))
7292 (org-table-find-dataline)
7293 (let* ((col (max 1 (org-table-current-column)))
7294 (beg (org-table-begin))
7295 (end (org-table-end))
7296 ;; Current cursor position
7297 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7298 (colpos col))
7299 (goto-char beg)
7300 (while (< (point) end)
7301 (if (org-at-table-hline-p)
7302 nil
7303 (org-table-goto-column col t)
7304 (insert "| "))
7305 (beginning-of-line 2))
7306 (move-marker end nil)
7307 (goto-line linepos)
7308 (org-table-goto-column colpos)
7309 (org-table-align)
7310 (org-table-modify-formulas 'insert col)))
7311
7312 (defun org-table-find-dataline ()
7313 "Find a dataline in the current table, which is needed for column commands."
7314 (if (and (org-at-table-p)
7315 (not (org-at-table-hline-p)))
7316 t
7317 (let ((col (current-column))
7318 (end (org-table-end)))
7319 (move-to-column col)
7320 (while (and (< (point) end)
7321 (or (not (= (current-column) col))
7322 (org-at-table-hline-p)))
7323 (beginning-of-line 2)
7324 (move-to-column col))
7325 (if (and (org-at-table-p)
7326 (not (org-at-table-hline-p)))
7327 t
7328 (error
7329 "Please position cursor in a data line for column operations")))))
7330
7331 (defun org-table-delete-column ()
7332 "Delete a column into the table."
7333 (interactive)
7334 (if (not (org-at-table-p))
7335 (error "Not at a table"))
7336 (org-table-find-dataline)
7337 (org-table-check-inside-data-field)
7338 (let* ((col (org-table-current-column))
7339 (beg (org-table-begin))
7340 (end (org-table-end))
7341 ;; Current cursor position
7342 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7343 (colpos col))
7344 (goto-char beg)
7345 (while (< (point) end)
7346 (if (org-at-table-hline-p)
7347 nil
7348 (org-table-goto-column col t)
7349 (and (looking-at "|[^|\n]+|")
7350 (replace-match "|")))
7351 (beginning-of-line 2))
7352 (move-marker end nil)
7353 (goto-line linepos)
7354 (org-table-goto-column colpos)
7355 (org-table-align)
7356 (org-table-modify-formulas 'remove col)))
7357
7358 (defun org-table-move-column-right ()
7359 "Move column to the right."
7360 (interactive)
7361 (org-table-move-column nil))
7362 (defun org-table-move-column-left ()
7363 "Move column to the left."
7364 (interactive)
7365 (org-table-move-column 'left))
7366
7367 (defun org-table-move-column (&optional left)
7368 "Move the current column to the right. With arg LEFT, move to the left."
7369 (interactive "P")
7370 (if (not (org-at-table-p))
7371 (error "Not at a table"))
7372 (org-table-find-dataline)
7373 (org-table-check-inside-data-field)
7374 (let* ((col (org-table-current-column))
7375 (col1 (if left (1- col) col))
7376 (beg (org-table-begin))
7377 (end (org-table-end))
7378 ;; Current cursor position
7379 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7380 (colpos (if left (1- col) (1+ col))))
7381 (if (and left (= col 1))
7382 (error "Cannot move column further left"))
7383 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7384 (error "Cannot move column further right"))
7385 (goto-char beg)
7386 (while (< (point) end)
7387 (if (org-at-table-hline-p)
7388 nil
7389 (org-table-goto-column col1 t)
7390 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7391 (replace-match "|\\2|\\1|")))
7392 (beginning-of-line 2))
7393 (move-marker end nil)
7394 (goto-line linepos)
7395 (org-table-goto-column colpos)
7396 (org-table-align)
7397 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
7398
7399 (defun org-table-move-row-down ()
7400 "move table row down."
7401 (interactive)
7402 (org-table-move-row nil))
7403 (defun org-table-move-row-up ()
7404 "move table row up."
7405 (interactive)
7406 (org-table-move-row 'up))
7407
7408 (defun org-table-move-row (&optional up)
7409 "Move the current table line down. With arg UP, move it up."
7410 (interactive "P")
7411 (let ((col (current-column))
7412 (pos (point))
7413 (tonew (if up 0 2))
7414 txt)
7415 (beginning-of-line tonew)
7416 (if (not (org-at-table-p))
7417 (progn
7418 (goto-char pos)
7419 (error "Cannot move row further")))
7420 (goto-char pos)
7421 (beginning-of-line 1)
7422 (setq pos (point))
7423 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7424 (delete-region (point) (1+ (point-at-eol)))
7425 (beginning-of-line tonew)
7426 (insert txt)
7427 (beginning-of-line 0)
7428 (move-to-column col)))
7429
7430 (defun org-table-insert-row (&optional arg)
7431 "Insert a new row above the current line into the table.
7432 With prefix ARG, insert below the current line."
7433 (interactive "P")
7434 (if (not (org-at-table-p))
7435 (error "Not at a table"))
7436 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7437 new)
7438 (if (string-match "^[ \t]*|-" line)
7439 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
7440 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
7441 ;; Fix the first field if necessary
7442 (setq new (concat new))
7443 (if (string-match "^[ \t]*| *[#$] *|" line)
7444 (setq new (replace-match (match-string 0 line) t t new)))
7445 (beginning-of-line (if arg 2 1))
7446 (let (org-table-may-need-update)
7447 (insert-before-markers new)
7448 (insert-before-markers "\n"))
7449 (beginning-of-line 0)
7450 (re-search-forward "| ?" (point-at-eol) t)
7451 (and org-table-may-need-update (org-table-align))))
7452
7453 (defun org-table-insert-hline (&optional arg)
7454 "Insert a horizontal-line below the current line into the table.
7455 With prefix ARG, insert above the current line."
7456 (interactive "P")
7457 (if (not (org-at-table-p))
7458 (error "Not at a table"))
7459 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
7460 (col (current-column))
7461 start)
7462 (if (string-match "^[ \t]*|-" line)
7463 (setq line
7464 (mapcar (lambda (x) (if (member x '(?| ?+))
7465 (prog1 (if start ?+ ?|) (setq start t))
7466 (if start ?- ?\ )))
7467 line))
7468 (setq line
7469 (mapcar (lambda (x) (if (equal x ?|)
7470 (prog1 (if start ?+ ?|) (setq start t))
7471 (if start ?- ?\ )))
7472 line)))
7473 (beginning-of-line (if arg 1 2))
7474 (apply 'insert line)
7475 (if (equal (char-before (point)) ?+)
7476 (progn (backward-delete-char 1) (insert "|")))
7477 (insert "\n")
7478 (beginning-of-line 0)
7479 (move-to-column col)))
7480
7481 (defun org-table-kill-row ()
7482 "Delete the current row or horizontal line from the table."
7483 (interactive)
7484 (if (not (org-at-table-p))
7485 (error "Not at a table"))
7486 (let ((col (current-column)))
7487 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7488 (if (not (org-at-table-p)) (beginning-of-line 0))
7489 (move-to-column col)))
7490
7491 (defun org-table-sort-lines (beg end numericp)
7492 "Sort table lines in region.
7493 Point and mark define the first and last line to include. Both point and
7494 mark should be in the column that is used for sorting. For example, to
7495 sort according to column 3, put the mark in the first line to sort, in
7496 table column 3. Put point into the last line to be included in the sorting,
7497 also in table column 3. The command will prompt for the sorting method (n for
7498 numerical, a for alphanumeric)."
7499 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
7500 (setq numericp (string-match "[nN]" numericp))
7501 (org-table-align) ;; Just to be safe
7502 (let* (bcol ecol cmp column lns)
7503 (goto-char beg)
7504 (org-table-check-inside-data-field)
7505 (setq column (org-table-current-column)
7506 beg (move-marker (make-marker) (point-at-bol)))
7507 (goto-char end)
7508 (org-table-check-inside-data-field)
7509 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
7510 (untabify beg end)
7511 (goto-char beg)
7512 (org-table-goto-column column)
7513 (skip-chars-backward "^|")
7514 (setq bcol (current-column))
7515 (org-table-goto-column (1+ column))
7516 (skip-chars-backward "^|")
7517 (setq ecol (1- (current-column)))
7518 (setq cmp (if numericp
7519 (lambda (a b) (< (car a) (car b)))
7520 (lambda (a b) (string< (car a) (car b)))))
7521 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7522 (split-string (buffer-substring beg end) "\n")))
7523 (if numericp
7524 (setq lns (mapcar (lambda(x)
7525 (cons (string-to-number (car x)) (cdr x)))
7526 lns)))
7527 (delete-region beg end)
7528 (move-marker beg nil)
7529 (move-marker end nil)
7530 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
7531 (message "%d lines sorted %s based on column %d"
7532 (length lns)
7533 (if numericp "numerically" "alphabetically") column)))
7534
7535 (defun org-table-cut-region (beg end)
7536 "Copy region in table to the clipboard and blank all relevant fields."
7537 (interactive "r")
7538 (org-table-copy-region beg end 'cut))
7539
7540 (defun org-table-copy-region (beg end &optional cut)
7541 "Copy rectangular region in table to clipboard.
7542 A special clipboard is used which can only be accessed
7543 with `org-table-paste-rectangle'"
7544 (interactive "rP")
7545 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7546 region cols
7547 (rpl (if cut " " nil)))
7548 (goto-char beg)
7549 (org-table-check-inside-data-field)
7550 (setq l01 (count-lines (point-min) (point))
7551 c01 (org-table-current-column))
7552 (goto-char end)
7553 (org-table-check-inside-data-field)
7554 (setq l02 (count-lines (point-min) (point))
7555 c02 (org-table-current-column))
7556 (setq l1 (min l01 l02) l2 (max l01 l02)
7557 c1 (min c01 c02) c2 (max c01 c02))
7558 (catch 'exit
7559 (while t
7560 (catch 'nextline
7561 (if (> l1 l2) (throw 'exit t))
7562 (goto-line l1)
7563 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7564 (setq cols nil ic1 c1 ic2 c2)
7565 (while (< ic1 (1+ ic2))
7566 (push (org-table-get-field ic1 rpl) cols)
7567 (setq ic1 (1+ ic1)))
7568 (push (nreverse cols) region)
7569 (setq l1 (1+ l1)))))
7570 (setq org-table-clip (nreverse region))
7571 (if cut (org-table-align))
7572 org-table-clip))
7573
7574 (defun org-table-paste-rectangle ()
7575 "Paste a rectangular region into a table.
7576 The upper right corner ends up in the current field. All involved fields
7577 will be overwritten. If the rectangle does not fit into the present table,
7578 the table is enlarged as needed. The process ignores horizontal separator
7579 lines."
7580 (interactive)
7581 (unless (and org-table-clip (listp org-table-clip))
7582 (error "First cut/copy a region to paste!"))
7583 (org-table-check-inside-data-field)
7584 (let* ((clip org-table-clip)
7585 (line (count-lines (point-min) (point)))
7586 (col (org-table-current-column))
7587 (org-enable-table-editor t)
7588 (org-table-automatic-realign nil)
7589 c cols field)
7590 (while (setq cols (pop clip))
7591 (while (org-at-table-hline-p) (beginning-of-line 2))
7592 (if (not (org-at-table-p))
7593 (progn (end-of-line 0) (org-table-next-field)))
7594 (setq c col)
7595 (while (setq field (pop cols))
7596 (org-table-goto-column c nil 'force)
7597 (org-table-get-field nil field)
7598 (setq c (1+ c)))
7599 (beginning-of-line 2))
7600 (goto-line line)
7601 (org-table-goto-column col)
7602 (org-table-align)))
7603
7604 (defun org-table-convert ()
7605 "Convert from `org-mode' table to table.el and back.
7606 Obviously, this only works within limits. When an Org-mode table is
7607 converted to table.el, all horizontal separator lines get lost, because
7608 table.el uses these as cell boundaries and has no notion of horizontal lines.
7609 A table.el table can be converted to an Org-mode table only if it does not
7610 do row or column spanning. Multiline cells will become multiple cells.
7611 Beware, Org-mode does not test if the table can be successfully converted - it
7612 blindly applies a recipe that works for simple tables."
7613 (interactive)
7614 (require 'table)
7615 (if (org-at-table.el-p)
7616 ;; convert to Org-mode table
7617 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7618 (end (move-marker (make-marker) (org-table-end t))))
7619 (table-unrecognize-region beg end)
7620 (goto-char beg)
7621 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7622 (replace-match ""))
7623 (goto-char beg))
7624 (if (org-at-table-p)
7625 ;; convert to table.el table
7626 (let ((beg (move-marker (make-marker) (org-table-begin)))
7627 (end (move-marker (make-marker) (org-table-end))))
7628 ;; first, get rid of all horizontal lines
7629 (goto-char beg)
7630 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7631 (replace-match ""))
7632 ;; insert a hline before first
7633 (goto-char beg)
7634 (org-table-insert-hline 'above)
7635 ;; insert a hline after each line
7636 (while (progn (beginning-of-line 2) (< (point) end))
7637 (org-table-insert-hline))
7638 (goto-char beg)
7639 (setq end (move-marker end (org-table-end)))
7640 ;; replace "+" at beginning and ending of hlines
7641 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7642 (replace-match "\\1+-"))
7643 (goto-char beg)
7644 (while (re-search-forward "-|[ \t]*$" end t)
7645 (replace-match "-+"))
7646 (goto-char beg)))))
7647
7648 (defun org-table-wrap-region (arg)
7649 "Wrap several fields in a column like a paragraph.
7650 This is useful if you'd like to spread the contents of a field over several
7651 lines, in order to keep the table compact.
7652
7653 If there is an active region, and both point and mark are in the same column,
7654 the text in the column is wrapped to minimum width for the given number of
7655 lines. Generally, this makes the table more compact. A prefix ARG may be
7656 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7657 formats the selected text to two lines. If the region was longer than 2
7658 lines, the remaining lines remain empty. A negative prefix argument reduces
7659 the current number of lines by that amount. The wrapped text is pasted back
7660 into the table. If you formatted it to more lines than it was before, fields
7661 further down in the table get overwritten - so you might need to make space in
7662 the table first.
7663
7664 If there is no region, the current field is split at the cursor position and
7665 the text fragment to the right of the cursor is prepended to the field one
7666 line down.
7667
7668 If there is no region, but you specify a prefix ARG, the current field gets
7669 blank, and the content is appended to the field above."
7670 (interactive "P")
7671 (org-table-check-inside-data-field)
7672 (if (org-region-active-p)
7673 ;; There is a region: fill as a paragraph
7674 (let ((beg (region-beginning))
7675 nlines)
7676 (org-table-cut-region (region-beginning) (region-end))
7677 (if (> (length (car org-table-clip)) 1)
7678 (error "Region must be limited to single column"))
7679 (setq nlines (if arg
7680 (if (< arg 1)
7681 (+ (length org-table-clip) arg)
7682 arg)
7683 (length org-table-clip)))
7684 (setq org-table-clip
7685 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7686 nil nlines)))
7687 (goto-char beg)
7688 (org-table-paste-rectangle))
7689 ;; No region, split the current field at point
7690 (if arg
7691 ;; combine with field above
7692 (let ((s (org-table-blank-field))
7693 (col (org-table-current-column)))
7694 (beginning-of-line 0)
7695 (while (org-at-table-hline-p) (beginning-of-line 0))
7696 (org-table-goto-column col)
7697 (skip-chars-forward "^|")
7698 (skip-chars-backward " ")
7699 (insert " " (org-trim s))
7700 (org-table-align))
7701 ;; split field
7702 (when (looking-at "\\([^|]+\\)+|")
7703 (let ((s (match-string 1)))
7704 (replace-match " |")
7705 (goto-char (match-beginning 0))
7706 (org-table-next-row)
7707 (insert (org-trim s) " ")
7708 (org-table-align))))))
7709
7710 (defun org-trim (s)
7711 "Remove whitespace at beginning and end of string."
7712 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7713 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7714 s)
7715
7716 (defun org-wrap (string &optional width lines)
7717 "Wrap string to either a number of lines, or a width in characters.
7718 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7719 that costs. If there is a word longer than WIDTH, the text is actually
7720 wrapped to the length of that word.
7721 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7722 many lines, whatever width that takes.
7723 The return value is a list of lines, without newlines at the end."
7724 (let* ((words (org-split-string string "[ \t\n]+"))
7725 (maxword (apply 'max (mapcar 'length words)))
7726 w ll)
7727 (cond (width
7728 (org-do-wrap words (max maxword width)))
7729 (lines
7730 (setq w maxword)
7731 (setq ll (org-do-wrap words maxword))
7732 (if (<= (length ll) lines)
7733 ll
7734 (setq ll words)
7735 (while (> (length ll) lines)
7736 (setq w (1+ w))
7737 (setq ll (org-do-wrap words w)))
7738 ll))
7739 (t (error "Cannot wrap this")))))
7740
7741
7742 (defun org-do-wrap (words width)
7743 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7744 (let (lines line)
7745 (while words
7746 (setq line (pop words))
7747 (while (and words (< (+ (length line) (length (car words))) width))
7748 (setq line (concat line " " (pop words))))
7749 (setq lines (push line lines)))
7750 (nreverse lines)))
7751
7752 ;; FIXME: I think I can make this more efficient
7753 (defun org-split-string (string &optional separators)
7754 "Splits STRING into substrings at SEPARATORS.
7755 No empty strings are returned if there are matches at the beginning
7756 and end of string."
7757 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7758 (start 0)
7759 notfirst
7760 (list nil))
7761 (while (and (string-match rexp string
7762 (if (and notfirst
7763 (= start (match-beginning 0))
7764 (< start (length string)))
7765 (1+ start) start))
7766 (< (match-beginning 0) (length string)))
7767 (setq notfirst t)
7768 (or (eq (match-beginning 0) 0)
7769 (and (eq (match-beginning 0) (match-end 0))
7770 (eq (match-beginning 0) start))
7771 (setq list
7772 (cons (substring string start (match-beginning 0))
7773 list)))
7774 (setq start (match-end 0)))
7775 (or (eq start (length string))
7776 (setq list
7777 (cons (substring string start)
7778 list)))
7779 (nreverse list)))
7780
7781 (defun org-table-add-invisible-to-vertical-lines ()
7782 "Add an `invisible' property to vertical lines of current table."
7783 (interactive)
7784 (let* ((beg (org-table-begin))
7785 (end (org-table-end))
7786 (end1))
7787 (save-excursion
7788 (goto-char beg)
7789 (while (< (point) end)
7790 (setq end1 (point-at-eol))
7791 (if (looking-at org-table-dataline-regexp)
7792 (while (re-search-forward "|" end1 t)
7793 (add-text-properties (1- (point)) (point)
7794 '(invisible org-table)))
7795 (while (re-search-forward "[+|]" end1 t)
7796 (add-text-properties (1- (point)) (point)
7797 '(invisible org-table))))
7798 (beginning-of-line 2)))))
7799
7800 (defun org-table-toggle-vline-visibility (&optional arg)
7801 "Toggle the visibility of table vertical lines.
7802 The effect is immediate and on all tables in the file.
7803 With prefix ARG, make lines invisible when ARG is positive, make lines
7804 visible when ARG is not positive"
7805 (interactive "P")
7806 (let ((action (cond
7807 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
7808 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
7809 (t (if (org-in-invisibility-spec-p '(org-table))
7810 'off
7811 'on)))))
7812 (if (eq action 'off)
7813 (progn
7814 (org-remove-from-invisibility-spec '(org-table))
7815 (org-table-map-tables 'org-table-align)
7816 (message "Vertical table lines visible")
7817 (if (org-at-table-p)
7818 (org-table-align)))
7819 (org-add-to-invisibility-spec '(org-table))
7820 (org-table-map-tables 'org-table-align)
7821 (message "Vertical table lines invisible"))
7822 (redraw-frame (selected-frame))))
7823
7824 (defun org-table-map-tables (function)
7825 "Apply FUNCTION to the start of all tables in the buffer."
7826 (save-excursion
7827 (save-restriction
7828 (widen)
7829 (goto-char (point-min))
7830 (while (re-search-forward org-table-any-line-regexp nil t)
7831 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7832 (beginning-of-line 1)
7833 (if (looking-at org-table-line-regexp)
7834 (save-excursion (funcall function)))
7835 (re-search-forward org-table-any-border-regexp nil 1)))))
7836
7837 (defun org-table-sum (&optional beg end nlast)
7838 "Sum numbers in region of current table column.
7839 The result will be displayed in the echo area, and will be available
7840 as kill to be inserted with \\[yank].
7841
7842 If there is an active region, it is interpreted as a rectangle and all
7843 numbers in that rectangle will be summed. If there is no active
7844 region and point is located in a table column, sum all numbers in that
7845 column.
7846
7847 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7848 numbers are assumed to be times as well (in decimal hours) and the
7849 numbers are added as such.
7850
7851 If NLAST is a number, only the NLAST fields will actually be summed."
7852 (interactive)
7853 (save-excursion
7854 (let (col (timecnt 0) diff h m s org-table-clip)
7855 (cond
7856 ((and beg end)) ; beg and end given explicitly
7857 ((org-region-active-p)
7858 (setq beg (region-beginning) end (region-end)))
7859 (t
7860 (setq col (org-table-current-column))
7861 (goto-char (org-table-begin))
7862 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7863 (error "No table data"))
7864 (org-table-goto-column col)
7865 ;not needed? (skip-chars-backward "^|")
7866 (setq beg (point))
7867 (goto-char (org-table-end))
7868 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7869 (error "No table data"))
7870 (org-table-goto-column col)
7871 ;not needed? (skip-chars-forward "^|")
7872 (setq end (point))))
7873 (let* ((items (apply 'append (org-table-copy-region beg end)))
7874 (items1 (cond ((not nlast) items)
7875 ((>= nlast (length items)) items)
7876 (t (setq items (reverse items))
7877 (setcdr (nthcdr (1- nlast) items) nil)
7878 (nreverse items))))
7879 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7880 items1)))
7881 (res (apply '+ numbers))
7882 (sres (if (= timecnt 0)
7883 (format "%g" res)
7884 (setq diff (* 3600 res)
7885 h (floor (/ diff 3600)) diff (mod diff 3600)
7886 m (floor (/ diff 60)) diff (mod diff 60)
7887 s diff)
7888 (format "%d:%02d:%02d" h m s))))
7889 (kill-new sres)
7890 (if (interactive-p)
7891 (message "%s"
7892 (substitute-command-keys
7893 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7894 (length numbers) sres))))
7895 sres))))
7896
7897 (defun org-table-get-number-for-summing (s)
7898 (let (n)
7899 (if (string-match "^ *|? *" s)
7900 (setq s (replace-match "" nil nil s)))
7901 (if (string-match " *|? *$" s)
7902 (setq s (replace-match "" nil nil s)))
7903 (setq n (string-to-number s))
7904 (cond
7905 ((and (string-match "0" s)
7906 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7907 ((string-match "\\`[ \t]+\\'" s) nil)
7908 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7909 (let ((h (string-to-number (or (match-string 1 s) "0")))
7910 (m (string-to-number (or (match-string 2 s) "0")))
7911 (s (string-to-number (or (match-string 4 s) "0"))))
7912 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
7913 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7914 ((equal n 0) nil)
7915 (t n))))
7916
7917 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7918 "Get a calc vector from a column, accorting to desctiptor DESC.
7919 Optional arguments TBEG and COL can give the beginning of the table and
7920 the current column, to avoid unnecessary parsing."
7921 (save-excursion
7922 (or tbeg (setq tbeg (org-table-begin)))
7923 (or col (setq col (org-table-current-column)))
7924 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7925 (cond
7926 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7927 (setq n1 (- (match-end 1) (match-beginning 1)))
7928 (if (match-beginning 3)
7929 (setq n2 (- (match-end 2) (match-beginning 3))))
7930 (setq n (if n2 (max n1 n2) n1))
7931 (setq n1 (if n2 (min n1 n2)))
7932 (setq nn n)
7933 (while (and (> nn 0)
7934 (re-search-backward org-table-hline-regexp tbeg t))
7935 (push (org-current-line) hline-list)
7936 (setq nn (1- nn)))
7937 (setq hline-list (nreverse hline-list))
7938 (goto-line (nth (1- n) hline-list))
7939 (when (re-search-forward org-table-dataline-regexp)
7940 (org-table-goto-column col)
7941 (setq beg (point)))
7942 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7943 (when (re-search-backward org-table-dataline-regexp)
7944 (org-table-goto-column col)
7945 (setq end (point)))
7946 (setq l (apply 'append (org-table-copy-region beg end)))
7947 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7948 (if (equal x "") "0" x))
7949 l ",") "]"))
7950 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7951 (setq n1 (string-to-number (match-string 1 desc))
7952 n2 (string-to-number (match-string 2 desc)))
7953 (beginning-of-line 1)
7954 (save-excursion
7955 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7956 (org-table-goto-column col)
7957 (setq beg (point))))
7958 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7959 (org-table-goto-column col)
7960 (setq end (point)))
7961 (setq l (apply 'append (org-table-copy-region beg end)))
7962 (concat "[" (mapconcat
7963 (lambda (x) (setq x (org-trim x))
7964 (if (equal x "") "0" x))
7965 l ",") "]"))
7966 ((string-match "\\([0-9]+\\)" desc)
7967 (beginning-of-line 1)
7968 (when (re-search-backward org-table-dataline-regexp tbeg t
7969 (string-to-number (match-string 0 desc)))
7970 (org-table-goto-column col)
7971 (org-trim (org-table-get-field))))))))
7972
7973 (defvar org-table-formula-history nil)
7974
7975 (defvar org-table-column-names nil
7976 "Alist with column names, derived from the `!' line.")
7977 (defvar org-table-column-name-regexp nil
7978 "Regular expression matching the current column names.")
7979 (defvar org-table-local-parameters nil
7980 "Alist with parameter names, derived from the `$' line.")
7981 (defvar org-table-named-field-locations nil
7982 "Alist with locations of named fields.")
7983
7984 (defun org-table-get-formula (&optional equation named)
7985 "Read a formula from the minibuffer, offer stored formula as default."
7986 (let* ((name (car (rassoc (list (org-current-line)
7987 (org-table-current-column))
7988 org-table-named-field-locations)))
7989 (scol (if named
7990 (if name name
7991 (error "Not in a named field"))
7992 (int-to-string (org-table-current-column))))
7993 (dummy (and name (not named)
7994 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7995 (error "Abort")))
7996 (org-table-may-need-update nil)
7997 (stored-list (org-table-get-stored-formulas))
7998 (stored (cdr (assoc scol stored-list)))
7999 (eq (cond
8000 ((and stored equation (string-match "^ *=? *$" equation))
8001 stored)
8002 ((stringp equation)
8003 equation)
8004 (t (read-string
8005 (format "%s formula $%s=" (if named "Field" "Column") scol)
8006 (or stored "") 'org-table-formula-history
8007 ;stored
8008 ))))
8009 mustsave)
8010 (when (not (string-match "\\S-" eq))
8011 ;; remove formula
8012 (setq stored-list (delq (assoc scol stored-list) stored-list))
8013 (org-table-store-formulas stored-list)
8014 (error "Formula removed"))
8015 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8016 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8017 (if (and name (not named))
8018 ;; We set the column equation, delete the named one.
8019 (setq stored-list (delq (assoc name stored-list) stored-list)
8020 mustsave t))
8021 (if stored
8022 (setcdr (assoc scol stored-list) eq)
8023 (setq stored-list (cons (cons scol eq) stored-list)))
8024 (if (or mustsave (not (equal stored eq)))
8025 (org-table-store-formulas stored-list))
8026 eq))
8027
8028 (defun org-table-store-formulas (alist)
8029 "Store the list of formulas below the current table."
8030 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8031 (save-excursion
8032 (goto-char (org-table-end))
8033 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8034 (delete-region (point) (match-end 0)))
8035 (insert "#+TBLFM: "
8036 (mapconcat (lambda (x)
8037 (concat "$" (car x) "=" (cdr x)))
8038 alist "::")
8039 "\n")))
8040
8041 (defun org-table-get-stored-formulas ()
8042 "Return an alist with the t=stored formulas directly after current table."
8043 (interactive)
8044 (let (scol eq eq-alist strings string seen)
8045 (save-excursion
8046 (goto-char (org-table-end))
8047 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8048 (setq strings (org-split-string (match-string 2) " *:: *"))
8049 (while (setq string (pop strings))
8050 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8051 (setq scol (match-string 1 string)
8052 eq (match-string 2 string)
8053 eq-alist (cons (cons scol eq) eq-alist))
8054 (if (member scol seen)
8055 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8056 (push scol seen))))))
8057 (nreverse eq-alist)))
8058
8059 (defun org-table-modify-formulas (action &rest columns)
8060 "Modify the formulas stored below the current table.
8061 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8062 expected, for the other action only a single column number is needed."
8063 (let ((list (org-table-get-stored-formulas))
8064 (nmax (length (org-split-string
8065 (buffer-substring (point-at-bol) (point-at-eol))
8066 "|")))
8067 col col1 col2 scol si sc1 sc2)
8068 (cond
8069 ((null list)) ; No action needed if there are no stored formulas
8070 ((eq action 'remove)
8071 (setq col (car columns)
8072 scol (int-to-string col))
8073 (org-table-replace-in-formulas list scol "INVALID")
8074 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8075 (loop for i from (1+ col) upto nmax by 1 do
8076 (setq si (int-to-string i))
8077 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8078 (if (assoc si list) (setcar (assoc si list)
8079 (int-to-string (1- i))))))
8080 ((eq action 'insert)
8081 (setq col (car columns))
8082 (loop for i from nmax downto col by 1 do
8083 (setq si (int-to-string i))
8084 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8085 (if (assoc si list) (setcar (assoc si list)
8086 (int-to-string (1+ i))))))
8087 ((eq action 'swap)
8088 (setq col1 (car columns) col2 (nth 1 columns)
8089 sc1 (int-to-string col1) sc2 (int-to-string col2))
8090 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8091 (org-table-replace-in-formulas list sc1 "ZqZ")
8092 (org-table-replace-in-formulas list sc2 sc1)
8093 (org-table-replace-in-formulas list "ZqZ" sc2)
8094 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8095 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8096 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8097 (t (error "Invalid action in `org-table-modify-formulas'")))
8098 (if list (org-table-store-formulas list))))
8099
8100 (defun org-table-replace-in-formulas (list s1 s2)
8101 (let (elt re s)
8102 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8103 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8104 re (concat (regexp-quote s1) "\\>"))
8105 (while (setq elt (pop list))
8106 (setq s (cdr elt))
8107 (while (string-match re s)
8108 (setq s (replace-match s2 t t s)))
8109 (setcdr elt s))))
8110
8111 (defun org-table-get-specials ()
8112 "Get the column nmaes and local parameters for this table."
8113 (save-excursion
8114 (let ((beg (org-table-begin)) (end (org-table-end))
8115 names name fields fields1 field cnt c v line col)
8116 (setq org-table-column-names nil
8117 org-table-local-parameters nil
8118 org-table-named-field-locations nil)
8119 (goto-char beg)
8120 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8121 (setq names (org-split-string (match-string 1) " *| *")
8122 cnt 1)
8123 (while (setq name (pop names))
8124 (setq cnt (1+ cnt))
8125 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8126 (push (cons name (int-to-string cnt)) org-table-column-names))))
8127 (setq org-table-column-names (nreverse org-table-column-names))
8128 (setq org-table-column-name-regexp
8129 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8130 (goto-char beg)
8131 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8132 (setq fields (org-split-string (match-string 1) " *| *"))
8133 (while (setq field (pop fields))
8134 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8135 (push (cons (match-string 1 field) (match-string 2 field))
8136 org-table-local-parameters))))
8137 (goto-char beg)
8138 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8139 (setq c (match-string 1)
8140 fields (org-split-string (match-string 2) " *| *"))
8141 (save-excursion
8142 (beginning-of-line (if (equal c "_") 2 0))
8143 (setq line (org-current-line) col 1)
8144 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8145 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8146 (while (and fields1 (setq field (pop fields)))
8147 (setq v (pop fields1) col (1+ col))
8148 (when (and (stringp field) (stringp v)
8149 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8150 (push (cons field v) org-table-local-parameters)
8151 (push (list field line col) org-table-named-field-locations)))))))
8152
8153 (defun org-this-word ()
8154 ;; Get the current word
8155 (save-excursion
8156 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8157 (end (progn (skip-chars-forward "^ \t\n") (point))))
8158 (buffer-substring-no-properties beg end))))
8159
8160 (defun org-table-maybe-eval-formula ()
8161 "Check if the current field starts with \"=\" or \":=\".
8162 If yes, store the formula and apply it."
8163 ;; We already know we are in a table. Get field will only return a formula
8164 ;; when appropriate. It might return a separator line, but no problem.
8165 (when org-table-formula-evaluate-inline
8166 (let* ((field (org-trim (or (org-table-get-field) "")))
8167 named eq)
8168 (when (string-match "^:?=\\(.*\\)" field)
8169 (setq named (equal (string-to-char field) ?:)
8170 eq (match-string 1 field))
8171 (if (fboundp 'calc-eval)
8172 (org-table-eval-formula (if named '(4) nil) eq))))))
8173
8174 (defvar org-recalc-commands nil
8175 "List of commands triggering the reccalculation of a line.
8176 Will be filled automatically during use.")
8177
8178 (defvar org-recalc-marks
8179 '((" " . "Unmarked: no special line, no automatic recalculation")
8180 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8181 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8182 ("!" . "Column name definition line. Reference in formula as $name.")
8183 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8184 ("_" . "Names for values in row below this one.")
8185 ("^" . "Names for values in row above this one.")))
8186
8187 (defun org-table-rotate-recalc-marks (&optional newchar)
8188 "Rotate the recalculation mark in the first column.
8189 If in any row, the first field is not consistent with a mark,
8190 insert a new column for the makers.
8191 When there is an active region, change all the lines in the region,
8192 after prompting for the marking character.
8193 After each change, a message will be displayed indication the meaning
8194 of the new mark."
8195 (interactive)
8196 (unless (org-at-table-p) (error "Not at a table"))
8197 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8198 (beg (org-table-begin))
8199 (end (org-table-end))
8200 (l (org-current-line))
8201 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8202 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8203 (have-col
8204 (save-excursion
8205 (goto-char beg)
8206 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8207 (col (org-table-current-column))
8208 (forcenew (car (assoc newchar org-recalc-marks)))
8209 epos new)
8210 (when l1
8211 (message "Change region to what mark? Type # * ! $ or SPC: ")
8212 (setq newchar (char-to-string (read-char-exclusive))
8213 forcenew (car (assoc newchar org-recalc-marks))))
8214 (if (and newchar (not forcenew))
8215 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8216 newchar))
8217 (if l1 (goto-line l1))
8218 (save-excursion
8219 (beginning-of-line 1)
8220 (unless (looking-at org-table-dataline-regexp)
8221 (error "Not at a table data line")))
8222 (unless have-col
8223 (org-table-goto-column 1)
8224 (org-table-insert-column)
8225 (org-table-goto-column (1+ col)))
8226 (setq epos (point-at-eol))
8227 (save-excursion
8228 (beginning-of-line 1)
8229 (org-table-get-field
8230 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8231 (concat " "
8232 (setq new (or forcenew
8233 (cadr (member (match-string 1) marks))))
8234 " ")
8235 " # ")))
8236 (if (and l1 l2)
8237 (progn
8238 (goto-line l1)
8239 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8240 (and (looking-at org-table-dataline-regexp)
8241 (org-table-get-field 1 (concat " " new " "))))
8242 (goto-line l1)))
8243 (if (not (= epos (point-at-eol))) (org-table-align))
8244 (goto-line l)
8245 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8246
8247 (defun org-table-maybe-recalculate-line ()
8248 "Recompute the current line if marked for it, and if we haven't just done it."
8249 (interactive)
8250 (and org-table-allow-automatic-line-recalculation
8251 (not (and (memq last-command org-recalc-commands)
8252 (equal org-last-recalc-line (org-current-line))))
8253 (save-excursion (beginning-of-line 1)
8254 (looking-at org-table-auto-recalculate-regexp))
8255 (fboundp 'calc-eval)
8256 (org-table-recalculate) t))
8257
8258 (defvar org-table-formula-debug nil
8259 "Non-nil means, debug table formulas.
8260 When nil, simply write \"#ERROR\" in corrupted fields.")
8261
8262 (defvar modes)
8263 (defsubst org-set-calc-mode (var &optional value)
8264 (if (stringp var)
8265 (setq var (assoc var '(("D" calc-angle-mode deg)
8266 ("R" calc-angle-mode rad)
8267 ("F" calc-prefer-frac t)
8268 ("S" calc-symbolic-mode t)))
8269 value (nth 2 var) var (nth 1 var)))
8270 (if (memq var modes)
8271 (setcar (cdr (memq var modes)) value)
8272 (cons var (cons value modes)))
8273 modes)
8274
8275 (defun org-table-eval-formula (&optional arg equation
8276 suppress-align suppress-const
8277 suppress-store)
8278 "Replace the table field value at the cursor by the result of a calculation.
8279
8280 This function makes use of Dave Gillespie's calc package, in my view the
8281 most exciting program ever written for GNU Emacs. So you need to have calc
8282 installed in order to use this function.
8283
8284 In a table, this command replaces the value in the current field with the
8285 result of a formula. It also installes the formula as the \"current\" column
8286 formula, by storing it in a special line below the table. When called
8287 with a `C-u' prefix, the current field must ba a named field, and the
8288 formula is installed as valid in only this specific field.
8289
8290 When called, the command first prompts for a formula, which is read in
8291 the minibuffer. Previously entered formulas are available through the
8292 history list, and the last used formula is offered as a default.
8293 These stored formulas are adapted correctly when moving, inserting, or
8294 deleting columns with the corresponding commands.
8295
8296 The formula can be any algebraic expression understood by the calc package.
8297 For details, see the Org-mode manual.
8298
8299 This function can also be called from Lisp programs and offers
8300 additional Arguments: EQUATION can be the formula to apply. If this
8301 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8302 used to speed-up recursive calls by by-passing unnecessary aligns.
8303 SUPPRESS-CONST suppresses the interpretation of constants in the
8304 formula, assuming that this has been done already outside the fuction.
8305 SUPPRESS-STORE means the formula should not be stored, either because
8306 it is already stored, or because it is a modified equation that should
8307 not overwrite the stored one."
8308 (interactive "P")
8309 (require 'calc)
8310 (org-table-check-inside-data-field)
8311 (org-table-get-specials)
8312 (let* (fields
8313 (ndown (if (integerp arg) arg 1))
8314 (org-table-automatic-realign nil)
8315 (case-fold-search nil)
8316 (down (> ndown 1))
8317 (formula (if (and equation suppress-store)
8318 equation
8319 (org-table-get-formula equation (equal arg '(4)))))
8320 (n0 (org-table-current-column))
8321 (modes (copy-sequence org-calc-default-modes))
8322 n form fmt x ev orig c)
8323 ;; Parse the format string. Since we have a lot of modes, this is
8324 ;; a lot of work. However, I think calc still uses most of the time.
8325 (if (string-match ";" formula)
8326 (let ((tmp (org-split-string formula ";")))
8327 (setq formula (car tmp)
8328 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8329 (nth 1 tmp)))
8330 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
8331 (setq c (string-to-char (match-string 1 fmt))
8332 n (string-to-number (or (match-string 1 fmt) "")))
8333 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
8334 (setq modes (org-set-calc-mode
8335 'calc-float-format
8336 (list (cdr (assoc c '((?n. float) (?f. fix)
8337 (?s. sci) (?e. eng))))
8338 n))))
8339 (setq fmt (replace-match "" t t fmt)))
8340 (while (string-match "[DRFS]" fmt)
8341 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8342 (setq fmt (replace-match "" t t fmt)))
8343 (unless (string-match "\\S-" fmt)
8344 (setq fmt nil))))
8345 (if (and (not suppress-const) org-table-formula-use-constants)
8346 (setq formula (org-table-formula-substitute-names formula)))
8347 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8348 (while (> ndown 0)
8349 (setq fields (org-split-string
8350 (buffer-substring
8351 (point-at-bol) (point-at-eol)) " *| *"))
8352 (if org-table-formula-numbers-only
8353 (setq fields (mapcar
8354 (lambda (x) (number-to-string (string-to-number x)))
8355 fields)))
8356 (setq ndown (1- ndown))
8357 (setq form (copy-sequence formula))
8358 ;; Insert the references to fields in same row
8359 (while (string-match "\\$\\([0-9]+\\)?" form)
8360 (setq n (if (match-beginning 1)
8361 (string-to-number (match-string 1 form))
8362 n0)
8363 x (nth (1- n) fields))
8364 (unless x (error "Invalid field specifier \"%s\""
8365 (match-string 0 form)))
8366 (if (equal x "") (setq x "0"))
8367 (setq form (replace-match (concat "(" x ")") t t form)))
8368 ;; Insert ranges in current column
8369 (while (string-match "\\&[-I0-9]+" form)
8370 (setq form (replace-match
8371 (save-match-data
8372 (org-table-get-vertical-vector (match-string 0 form)
8373 nil n0))
8374 t t form)))
8375 (setq ev (calc-eval (cons form modes)
8376 (if org-table-formula-numbers-only 'num)))
8377
8378 (when org-table-formula-debug
8379 (with-output-to-temp-buffer "*Help*"
8380 (princ (format "Substitution history of formula
8381 Orig: %s
8382 $xyz-> %s
8383 $1-> %s\n" orig formula form))
8384 (if (listp ev)
8385 (princ (format " %s^\nError: %s"
8386 (make-string (car ev) ?\-) (nth 1 ev)))
8387 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8388 ev (or fmt "NONE")
8389 (if fmt (format fmt (string-to-number ev)) ev)))))
8390 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
8391 (unless (and (interactive-p) (not ndown))
8392 (unless (let (inhibit-redisplay)
8393 (y-or-n-p "Debugging Formula. Continue to next? "))
8394 (org-table-align)
8395 (error "Abort"))
8396 (delete-window (get-buffer-window "*Help*"))
8397 (message "")))
8398 (if (listp ev) (setq fmt nil ev "#ERROR"))
8399 (org-table-justify-field-maybe
8400 (if fmt (format fmt (string-to-number ev)) ev))
8401 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8402 (call-interactively 'org-return)
8403 (setq ndown 0)))
8404 (and down (org-table-maybe-recalculate-line))
8405 (or suppress-align (and org-table-may-need-update
8406 (org-table-align)))))
8407
8408 (defun org-table-recalculate (&optional all noalign)
8409 "Recalculate the current table line by applying all stored formulas."
8410 (interactive "P")
8411 (or (memq this-command org-recalc-commands)
8412 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8413 (unless (org-at-table-p) (error "Not at a table"))
8414 (org-table-get-specials)
8415 (let* ((eqlist (sort (org-table-get-stored-formulas)
8416 (lambda (a b) (string< (car a) (car b)))))
8417 (inhibit-redisplay t)
8418 (line-re org-table-dataline-regexp)
8419 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8420 (thiscol (org-table-current-column))
8421 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
8422 ;; Insert constants in all formulas
8423 (setq eqlist
8424 (mapcar (lambda (x)
8425 (setcdr x (org-table-formula-substitute-names (cdr x)))
8426 x)
8427 eqlist))
8428 ;; Split the equation list
8429 (while (setq eq (pop eqlist))
8430 (if (<= (string-to-char (car eq)) ?9)
8431 (push eq eqlnum)
8432 (push eq eqlname)))
8433 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8434 (if all
8435 (progn
8436 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8437 (goto-char (setq beg (org-table-begin)))
8438 (if (re-search-forward org-table-calculate-mark-regexp end t)
8439 ;; This is a table with marked lines, only compute selected lines
8440 (setq line-re org-table-recalculate-regexp)
8441 ;; Move forward to the first non-header line
8442 (if (and (re-search-forward org-table-dataline-regexp end t)
8443 (re-search-forward org-table-hline-regexp end t)
8444 (re-search-forward org-table-dataline-regexp end t))
8445 (setq beg (match-beginning 0))
8446 nil))) ;; just leave beg where it is
8447 (setq beg (point-at-bol)
8448 end (move-marker (make-marker) (1+ (point-at-eol)))))
8449 (goto-char beg)
8450 (and all (message "Re-applying formulas to full table..."))
8451 (while (re-search-forward line-re end t)
8452 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
8453 ;; Unprotected line, recalculate
8454 (and all (message "Re-applying formulas to full table...(line %d)"
8455 (setq cnt (1+ cnt))))
8456 (setq org-last-recalc-line (org-current-line))
8457 (setq eql eqlnum)
8458 (while (setq entry (pop eql))
8459 (goto-line org-last-recalc-line)
8460 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8461 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
8462 (goto-line thisline)
8463 (org-table-goto-column thiscol)
8464 (or noalign (and org-table-may-need-update (org-table-align))
8465 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8466 ;; Now do the names fields
8467 (while (setq eq (pop eqlname))
8468 (setq name (car eq)
8469 a (assoc name org-table-named-field-locations))
8470 (when a
8471 (message "Re-applying formula to named field: %s" name)
8472 (goto-line (nth 1 a))
8473 (org-table-goto-column (nth 2 a))
8474 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
8475 ;; back to initial position
8476 (goto-line thisline)
8477 (org-table-goto-column thiscol)
8478 (or noalign (and org-table-may-need-update (org-table-align))
8479 (and all (message "Re-applying formulas...done")))))
8480
8481 (defun org-table-formula-substitute-names (f)
8482 "Replace $const with values in string F."
8483 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
8484 ;; First, check for column names
8485 (while (setq start (string-match org-table-column-name-regexp f start))
8486 (setq start (1+ start))
8487 (setq a (assoc (match-string 1 f) org-table-column-names))
8488 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8489 ;; Expand ranges to vectors
8490 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
8491 (setq n1 (string-to-number (match-string 1 f))
8492 n2 (string-to-number (match-string 2 f))
8493 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
8494 s (concat "[($" (number-to-string (1- nn1)) ")"))
8495 (loop for i from nn1 upto nn2 do
8496 (setq s (concat s ",($" (int-to-string i) ")")))
8497 (setq s (concat s "]"))
8498 (if (< n2 n1) (setq s (concat "rev(" s ")")))
8499 (setq f (replace-match s t t f)))
8500 ;; Parameters and constants
8501 (setq start 0)
8502 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8503 (setq start (1+ start))
8504 (if (setq a (save-match-data
8505 (org-table-get-constant (match-string 1 f))))
8506 (setq f (replace-match (concat "(" a ")") t t f))))
8507 (if org-table-formula-debug
8508 (put-text-property 0 (length f) :orig-formula f1 f))
8509 f))
8510
8511 (defun org-table-get-constant (const)
8512 "Find the value for a parameter or constant in a formula.
8513 Parameters get priority."
8514 (or (cdr (assoc const org-table-local-parameters))
8515 (cdr (assoc const org-table-formula-constants))
8516 (and (fboundp 'constants-get) (constants-get const))
8517 "#UNDEFINED_NAME"))
8518
8519 (defvar org-edit-formulas-map (make-sparse-keymap))
8520 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
8521 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
8522 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
8523
8524 (defvar org-pos)
8525 (defvar org-window-configuration)
8526
8527 (defun org-table-edit-formulas ()
8528 "Edit the formulas of the current table in a separate buffer."
8529 (interactive)
8530 (unless (org-at-table-p)
8531 (error "Not at a table"))
8532 (org-table-get-specials)
8533 (let ((eql (org-table-get-stored-formulas))
8534 (pos (move-marker (make-marker) (point)))
8535 (wc (current-window-configuration))
8536 entry loc s)
8537 (switch-to-buffer-other-window "*Edit Formulas*")
8538 (erase-buffer)
8539 (fundamental-mode)
8540 (set (make-local-variable 'org-pos) pos)
8541 (set (make-local-variable 'org-window-configuration) wc)
8542 (use-local-map org-edit-formulas-map)
8543 (setq s "# Edit formulas and finish with `C-c C-c'.
8544 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
8545 # Use `C-c ?' to get information about $name at point.
8546 # To cancel editing, press `C-c C-q'.\n")
8547 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8548 (insert s)
8549 (while (setq entry (pop eql))
8550 (when (setq loc (assoc (car entry) org-table-named-field-locations))
8551 (setq s (format "# Named formula, referring to column %d in line %d\n"
8552 (nth 2 loc) (nth 1 loc)))
8553 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
8554 (insert s))
8555 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
8556 (remove-text-properties 0 (length s) '(face nil) s)
8557 (insert s))
8558 (goto-char (point-min))
8559 (message "Edit formulas and finish with `C-c C-c'.")))
8560
8561 (defun org-show-variable ()
8562 "Show the location/value of the $ expression at point."
8563 (interactive)
8564 (let (var (pos org-pos) (win (selected-window)) e)
8565 (save-excursion
8566 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
8567 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
8568 (setq var (match-string 1))
8569 (error "No variable at point")))
8570 (cond
8571 ((setq e (assoc var org-table-named-field-locations))
8572 (switch-to-buffer-other-window (marker-buffer pos))
8573 (goto-line (nth 1 e))
8574 (org-table-goto-column (nth 2 e))
8575 (select-window win)
8576 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8577 ((setq e (assoc var org-table-column-names))
8578 (switch-to-buffer-other-window (marker-buffer pos))
8579 (goto-char pos)
8580 (goto-char (org-table-begin))
8581 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8582 (org-table-end) t)
8583 (progn
8584 (goto-char (match-beginning 1))
8585 (message "Named column (column %s)" (cdr e)))
8586 (error "Column name not found"))
8587 (select-window win))
8588 ((string-match "^[0-9]$" var)
8589 ;; column number
8590 (switch-to-buffer-other-window (marker-buffer pos))
8591 (goto-char pos)
8592 (goto-char (org-table-begin))
8593 (recenter 1)
8594 (if (re-search-forward org-table-dataline-regexp
8595 (org-table-end) t)
8596 (progn
8597 (goto-char (match-beginning 0))
8598 (org-table-goto-column (string-to-number var))
8599 (message "Column %s" var))
8600 (error "Column name not found"))
8601 (select-window win))
8602 ((setq e (assoc var org-table-local-parameters))
8603 (switch-to-buffer-other-window (marker-buffer pos))
8604 (goto-char pos)
8605 (goto-char (org-table-begin))
8606 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8607 (progn
8608 (goto-char (match-beginning 1))
8609 (message "Local parameter."))
8610 (error "Parameter not found"))
8611 (select-window win))
8612 (t
8613 (cond
8614 ((setq e (assoc var org-table-formula-constants))
8615 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
8616 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8617 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
8618 (t (error "Undefined name $%s" var)))))))
8619
8620 (defun org-finish-edit-formulas (&optional arg)
8621 "Parse the buffer for formula definitions and install them.
8622 With prefix ARG, apply the new formulas to the table."
8623 (interactive "P")
8624 (let ((pos org-pos) eql)
8625 (goto-char (point-min))
8626 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
8627 (push (cons (match-string 1) (match-string 2)) eql))
8628 (set-window-configuration org-window-configuration)
8629 (select-window (get-buffer-window (marker-buffer pos)))
8630 (goto-char pos)
8631 (unless (org-at-table-p)
8632 (error "Lost table position - cannot install formulae"))
8633 (org-table-store-formulas eql)
8634 (move-marker pos nil)
8635 (kill-buffer "*Edit Formulas*")
8636 (if arg
8637 (org-table-recalculate 'all)
8638 (message "New formulas installed - press C-u C-c C-c to apply."))))
8639
8640 (defun org-abort-edit-formulas ()
8641 "Abort editing formulas, without installing the changes."
8642 (interactive)
8643 (let ((pos org-pos))
8644 (set-window-configuration org-window-configuration)
8645 (select-window (get-buffer-window (marker-buffer pos)))
8646 (goto-char pos)
8647 (message "Formula editing aborted without installing changes")))
8648
8649 ;;; The orgtbl minor mode
8650
8651 ;; Define a minor mode which can be used in other modes in order to
8652 ;; integrate the org-mode table editor.
8653
8654 ;; This is really a hack, because the org-mode table editor uses several
8655 ;; keys which normally belong to the major mode, for example the TAB and
8656 ;; RET keys. Here is how it works: The minor mode defines all the keys
8657 ;; necessary to operate the table editor, but wraps the commands into a
8658 ;; function which tests if the cursor is currently inside a table. If that
8659 ;; is the case, the table editor command is executed. However, when any of
8660 ;; those keys is used outside a table, the function uses `key-binding' to
8661 ;; look up if the key has an associated command in another currently active
8662 ;; keymap (minor modes, major mode, global), and executes that command.
8663 ;; There might be problems if any of the keys used by the table editor is
8664 ;; otherwise used as a prefix key.
8665
8666 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8667 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8668 ;; addresses this by checking explicitly for both bindings.
8669
8670 ;; The optimized version (see variable `orgtbl-optimized') takes over
8671 ;; all keys which are bound to `self-insert-command' in the *global map*.
8672 ;; Some modes bind other commands to simple characters, for example
8673 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8674 ;; active, this binding is ignored inside tables and replaced with a
8675 ;; modified self-insert.
8676
8677 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
8678 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
8679 In the optimized version, the table editor takes over all simple keys that
8680 normally just insert a character. In tables, the characters are inserted
8681 in a way to minimize disturbing the table structure (i.e. in overwrite mode
8682 for empty fields). Outside tables, the correct binding of the keys is
8683 restored.
8684
8685 The default for this option is t if the optimized version is also used in
8686 Org-mode. See the variable `org-enable-table-editor' for details. Changing
8687 this variable requires a restart of Emacs to become effective."
8688 :group 'org-table
8689 :type 'boolean)
8690
8691 (defvar orgtbl-mode nil
8692 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8693 table editor in arbitrary modes.")
8694 (make-variable-buffer-local 'orgtbl-mode)
8695
8696 (defvar orgtbl-mode-map (make-keymap)
8697 "Keymap for `orgtbl-mode'.")
8698
8699 ;;;###autoload
8700 (defun turn-on-orgtbl ()
8701 "Unconditionally turn on `orgtbl-mode'."
8702 (orgtbl-mode 1))
8703
8704 ;;;###autoload
8705 (defun orgtbl-mode (&optional arg)
8706 "The `org-mode' table editor as a minor mode for use in other modes."
8707 (interactive)
8708 (if (eq major-mode 'org-mode)
8709 ;; Exit without error, in case some hook functions calls this
8710 ;; by accident in org-mode.
8711 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8712 (setq orgtbl-mode
8713 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8714 (if orgtbl-mode
8715 (progn
8716 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8717 ;; Make sure we are first in minor-mode-map-alist
8718 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8719 (and c (setq minor-mode-map-alist
8720 (cons c (delq c minor-mode-map-alist)))))
8721 (set (make-local-variable (quote org-table-may-need-update)) t)
8722 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
8723 (add-hook 'before-change-functions 'org-before-change-function
8724 nil 'local)
8725 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
8726 auto-fill-inhibit-regexp)
8727 (set (make-local-variable 'auto-fill-inhibit-regexp)
8728 (if auto-fill-inhibit-regexp
8729 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
8730 "[ \t]*|"))
8731 (easy-menu-add orgtbl-mode-menu)
8732 (run-hooks 'orgtbl-mode-hook))
8733 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8734 (remove-hook 'before-change-functions 'org-before-change-function t)
8735 (easy-menu-remove orgtbl-mode-menu)
8736 (force-mode-line-update 'all))))
8737
8738 ;; Install it as a minor mode.
8739 (put 'orgtbl-mode :included t)
8740 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8741 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8742
8743 (defun orgtbl-make-binding (fun n &rest keys)
8744 "Create a function for binding in the table minor mode.
8745 FUN is the command to call inside a table. N is used to create a unique
8746 command name. KEYS are keys that should be checked in for a command
8747 to execute outside of tables."
8748 (eval
8749 (list 'defun
8750 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8751 '(arg)
8752 (concat "In tables, run `" (symbol-name fun) "'.\n"
8753 "Outside of tables, run the binding of `"
8754 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8755 "'.")
8756 '(interactive "p")
8757 (list 'if
8758 '(org-at-table-p)
8759 (list 'call-interactively (list 'quote fun))
8760 (list 'let '(orgtbl-mode)
8761 (list 'call-interactively
8762 (append '(or)
8763 (mapcar (lambda (k)
8764 (list 'key-binding k))
8765 keys)
8766 '('orgtbl-error))))))))
8767
8768 (defun orgtbl-error ()
8769 "Error when there is no default binding for a table key."
8770 (interactive)
8771 (error "This key is has no function outside tables"))
8772
8773 (defun orgtbl-setup ()
8774 "Setup orgtbl keymaps."
8775 (let ((nfunc 0)
8776 (bindings
8777 (list
8778 '([(meta shift left)] org-table-delete-column)
8779 '([(meta left)] org-table-move-column-left)
8780 '([(meta right)] org-table-move-column-right)
8781 '([(meta shift right)] org-table-insert-column)
8782 '([(meta shift up)] org-table-kill-row)
8783 '([(meta shift down)] org-table-insert-row)
8784 '([(meta up)] org-table-move-row-up)
8785 '([(meta down)] org-table-move-row-down)
8786 '("\C-c\C-w" org-table-cut-region)
8787 '("\C-c\M-w" org-table-copy-region)
8788 '("\C-c\C-y" org-table-paste-rectangle)
8789 '("\C-c-" org-table-insert-hline)
8790 ; '([(shift tab)] org-table-previous-field)
8791 '("\C-m" org-table-next-row)
8792 (list (org-key 'S-return) 'org-table-copy-down)
8793 '([(meta return)] org-table-wrap-region)
8794 '("\C-c\C-q" org-table-wrap-region)
8795 '("\C-c?" org-table-current-column)
8796 '("\C-c " org-table-blank-field)
8797 '("\C-c+" org-table-sum)
8798 '("\C-c|" org-table-toggle-vline-visibility)
8799 '("\C-c=" org-table-eval-formula)
8800 '("\C-c'" org-table-edit-formulas)
8801 '("\C-c*" org-table-recalculate)
8802 '("\C-c^" org-table-sort-lines)
8803 '([(control ?#)] org-table-rotate-recalc-marks)))
8804 elt key fun cmd)
8805 (while (setq elt (pop bindings))
8806 (setq nfunc (1+ nfunc))
8807 (setq key (car elt)
8808 fun (nth 1 elt)
8809 cmd (orgtbl-make-binding fun nfunc key))
8810 (define-key orgtbl-mode-map key cmd))
8811 ;; Special treatment needed for TAB and RET
8812 (define-key orgtbl-mode-map [(return)]
8813 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8814 (define-key orgtbl-mode-map "\C-m"
8815 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8816 (define-key orgtbl-mode-map [(tab)]
8817 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8818 (define-key orgtbl-mode-map "\C-i"
8819 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
8820 (define-key orgtbl-mode-map "\C-i"
8821 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8822 (define-key orgtbl-mode-map "\C-c\C-c"
8823 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8824 (when orgtbl-optimized
8825 ;; If the user wants maximum table support, we need to hijack
8826 ;; some standard editing functions
8827 (org-remap orgtbl-mode-map
8828 'self-insert-command 'orgtbl-self-insert-command
8829 'delete-char 'orgtbl-delete-char
8830 'delete-backward-char 'orgtbl-delete-backward-char)
8831 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8832 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8833 '("OrgTbl"
8834 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8835 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8836 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8837 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8838 "--"
8839 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8840 ["Copy Field from Above"
8841 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8842 "--"
8843 ("Column"
8844 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8845 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8846 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8847 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8848 ("Row"
8849 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8850 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8851 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8852 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8853 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8854 "--"
8855 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8856 ("Rectangle"
8857 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8858 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8859 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8860 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8861 "--"
8862 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8863 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8864 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8865 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8866 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8867 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8868 ["Sum Column/Rectangle" org-table-sum
8869 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8870 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8871 ["Debug Formulas"
8872 (setq org-table-formula-debug (not org-table-formula-debug))
8873 :style toggle :selected org-table-formula-debug]
8874 ))
8875 t)
8876
8877 (defun orgtbl-tab ()
8878 "Justification and field motion for `orgtbl-mode'."
8879 (interactive)
8880 (org-table-justify-field-maybe)
8881 (org-table-next-field))
8882
8883 (defun orgtbl-ret ()
8884 "Justification and field motion for `orgtbl-mode'."
8885 (interactive)
8886 (org-table-justify-field-maybe)
8887 (org-table-next-row))
8888
8889 (defun orgtbl-self-insert-command (N)
8890 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8891 If the cursor is in a table looking at whitespace, the whitespace is
8892 overwritten, and the table is not marked as requiring realignment."
8893 (interactive "p")
8894 (if (and (org-at-table-p)
8895 (or
8896 (and org-table-auto-blank-field
8897 (member last-command
8898 '(orgtbl-hijacker-command-100
8899 orgtbl-hijacker-command-101
8900 orgtbl-hijacker-command-102
8901 orgtbl-hijacker-command-103
8902 orgtbl-hijacker-command-104
8903 orgtbl-hijacker-command-105))
8904 (org-table-blank-field))
8905 t)
8906 (eq N 1)
8907 (looking-at "[^|\n]* +|"))
8908 (let (org-table-may-need-update)
8909 (goto-char (1- (match-end 0)))
8910 (delete-backward-char 1)
8911 (goto-char (match-beginning 0))
8912 (self-insert-command N))
8913 (setq org-table-may-need-update t)
8914 (let (orgtbl-mode)
8915 (call-interactively (key-binding (vector last-input-event))))))
8916
8917 (defun org-force-self-insert (N)
8918 "Needed to enforce self-insert under remapping."
8919 (interactive "p")
8920 (self-insert-command N))
8921
8922 (defun orgtbl-delete-backward-char (N)
8923 "Like `delete-backward-char', insert whitespace at field end in tables.
8924 When deleting backwards, in tables this function will insert whitespace in
8925 front of the next \"|\" separator, to keep the table aligned. The table will
8926 still be marked for re-alignment, because a narrow field may lead to a
8927 reduced column width."
8928 (interactive "p")
8929 (if (and (org-at-table-p)
8930 (eq N 1)
8931 (string-match "|" (buffer-substring (point-at-bol) (point)))
8932 (looking-at ".*?|"))
8933 (let ((pos (point)))
8934 (backward-delete-char N)
8935 (skip-chars-forward "^|")
8936 (insert " ")
8937 (goto-char (1- pos)))
8938 (delete-backward-char N)))
8939
8940 (defun orgtbl-delete-char (N)
8941 "Like `delete-char', but insert whitespace at field end in tables.
8942 When deleting characters, in tables this function will insert whitespace in
8943 front of the next \"|\" separator, to keep the table aligned. The table
8944 will still be marked for re-alignment, because a narrow field may lead to
8945 a reduced column width."
8946 (interactive "p")
8947 (if (and (org-at-table-p)
8948 (not (bolp))
8949 (not (= (char-after) ?|))
8950 (eq N 1))
8951 (if (looking-at ".*?|")
8952 (let ((pos (point)))
8953 (replace-match (concat
8954 (substring (match-string 0) 1 -1)
8955 " |"))
8956 (goto-char pos)))
8957 (delete-char N)))
8958
8959 ;;; Exporting
8960
8961 (defconst org-level-max 20)
8962
8963 (defun org-export-find-first-heading-line (list)
8964 "Remove all lines from LIST which are before the first headline."
8965 (let ((orig-list list)
8966 (re (concat "^" outline-regexp)))
8967 (while (and list
8968 (not (string-match re (car list))))
8969 (pop list))
8970 (or list orig-list)))
8971
8972 (defun org-skip-comments (lines)
8973 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8974 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8975 (re2 "^\\(\\*+\\)[ \t\n\r]")
8976 rtn line level)
8977 (while (setq line (pop lines))
8978 (cond
8979 ((and (string-match re1 line)
8980 (setq level (- (match-end 1) (match-beginning 1))))
8981 ;; Beginning of a COMMENT subtree. Skip it.
8982 (while (and (setq line (pop lines))
8983 (or (not (string-match re2 line))
8984 (> (- (match-end 1) (match-beginning 1)) level))))
8985 (setq lines (cons line lines)))
8986 ((string-match "^#" line)
8987 ;; an ordinary comment line
8988 )
8989 (t (setq rtn (cons line rtn)))))
8990 (nreverse rtn)))
8991
8992 ;; ASCII
8993
8994 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8995 "Characters for underlining headings in ASCII export.")
8996
8997 (defconst org-html-entities
8998 '(("nbsp")
8999 ("iexcl")
9000 ("cent")
9001 ("pound")
9002 ("curren")
9003 ("yen")
9004 ("brvbar")
9005 ("sect")
9006 ("uml")
9007 ("copy")
9008 ("ordf")
9009 ("laquo")
9010 ("not")
9011 ("shy")
9012 ("reg")
9013 ("macr")
9014 ("deg")
9015 ("plusmn")
9016 ("sup2")
9017 ("sup3")
9018 ("acute")
9019 ("micro")
9020 ("para")
9021 ("middot")
9022 ("odot"."o")
9023 ("star"."*")
9024 ("cedil")
9025 ("sup1")
9026 ("ordm")
9027 ("raquo")
9028 ("frac14")
9029 ("frac12")
9030 ("frac34")
9031 ("iquest")
9032 ("Agrave")
9033 ("Aacute")
9034 ("Acirc")
9035 ("Atilde")
9036 ("Auml")
9037 ("Aring") ("AA"."&Aring;")
9038 ("AElig")
9039 ("Ccedil")
9040 ("Egrave")
9041 ("Eacute")
9042 ("Ecirc")
9043 ("Euml")
9044 ("Igrave")
9045 ("Iacute")
9046 ("Icirc")
9047 ("Iuml")
9048 ("ETH")
9049 ("Ntilde")
9050 ("Ograve")
9051 ("Oacute")
9052 ("Ocirc")
9053 ("Otilde")
9054 ("Ouml")
9055 ("times")
9056 ("Oslash")
9057 ("Ugrave")
9058 ("Uacute")
9059 ("Ucirc")
9060 ("Uuml")
9061 ("Yacute")
9062 ("THORN")
9063 ("szlig")
9064 ("agrave")
9065 ("aacute")
9066 ("acirc")
9067 ("atilde")
9068 ("auml")
9069 ("aring")
9070 ("aelig")
9071 ("ccedil")
9072 ("egrave")
9073 ("eacute")
9074 ("ecirc")
9075 ("euml")
9076 ("igrave")
9077 ("iacute")
9078 ("icirc")
9079 ("iuml")
9080 ("eth")
9081 ("ntilde")
9082 ("ograve")
9083 ("oacute")
9084 ("ocirc")
9085 ("otilde")
9086 ("ouml")
9087 ("divide")
9088 ("oslash")
9089 ("ugrave")
9090 ("uacute")
9091 ("ucirc")
9092 ("uuml")
9093 ("yacute")
9094 ("thorn")
9095 ("yuml")
9096 ("fnof")
9097 ("Alpha")
9098 ("Beta")
9099 ("Gamma")
9100 ("Delta")
9101 ("Epsilon")
9102 ("Zeta")
9103 ("Eta")
9104 ("Theta")
9105 ("Iota")
9106 ("Kappa")
9107 ("Lambda")
9108 ("Mu")
9109 ("Nu")
9110 ("Xi")
9111 ("Omicron")
9112 ("Pi")
9113 ("Rho")
9114 ("Sigma")
9115 ("Tau")
9116 ("Upsilon")
9117 ("Phi")
9118 ("Chi")
9119 ("Psi")
9120 ("Omega")
9121 ("alpha")
9122 ("beta")
9123 ("gamma")
9124 ("delta")
9125 ("epsilon")
9126 ("varepsilon"."&epsilon;")
9127 ("zeta")
9128 ("eta")
9129 ("theta")
9130 ("iota")
9131 ("kappa")
9132 ("lambda")
9133 ("mu")
9134 ("nu")
9135 ("xi")
9136 ("omicron")
9137 ("pi")
9138 ("rho")
9139 ("sigmaf") ("varsigma"."&sigmaf;")
9140 ("sigma")
9141 ("tau")
9142 ("upsilon")
9143 ("phi")
9144 ("chi")
9145 ("psi")
9146 ("omega")
9147 ("thetasym") ("vartheta"."&thetasym;")
9148 ("upsih")
9149 ("piv")
9150 ("bull") ("bullet"."&bull;")
9151 ("hellip") ("dots"."&hellip;")
9152 ("prime")
9153 ("Prime")
9154 ("oline")
9155 ("frasl")
9156 ("weierp")
9157 ("image")
9158 ("real")
9159 ("trade")
9160 ("alefsym")
9161 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9162 ("uarr") ("uparrow"."&uarr;")
9163 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9164 ("darr")("downarrow"."&darr;")
9165 ("harr") ("leftrightarrow"."&harr;")
9166 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9167 ("lArr") ("Leftarrow"."&lArr;")
9168 ("uArr") ("Uparrow"."&uArr;")
9169 ("rArr") ("Rightarrow"."&rArr;")
9170 ("dArr") ("Downarrow"."&dArr;")
9171 ("hArr") ("Leftrightarrow"."&hArr;")
9172 ("forall")
9173 ("part") ("partial"."&part;")
9174 ("exist") ("exists"."&exist;")
9175 ("empty") ("emptyset"."&empty;")
9176 ("nabla")
9177 ("isin") ("in"."&isin;")
9178 ("notin")
9179 ("ni")
9180 ("prod")
9181 ("sum")
9182 ("minus")
9183 ("lowast") ("ast"."&lowast;")
9184 ("radic")
9185 ("prop") ("proptp"."&prop;")
9186 ("infin") ("infty"."&infin;")
9187 ("ang") ("angle"."&ang;")
9188 ("and") ("vee"."&and;")
9189 ("or") ("wedge"."&or;")
9190 ("cap")
9191 ("cup")
9192 ("int")
9193 ("there4")
9194 ("sim")
9195 ("cong") ("simeq"."&cong;")
9196 ("asymp")("approx"."&asymp;")
9197 ("ne") ("neq"."&ne;")
9198 ("equiv")
9199 ("le")
9200 ("ge")
9201 ("sub") ("subset"."&sub;")
9202 ("sup") ("supset"."&sup;")
9203 ("nsub")
9204 ("sube")
9205 ("supe")
9206 ("oplus")
9207 ("otimes")
9208 ("perp")
9209 ("sdot") ("cdot"."&sdot;")
9210 ("lceil")
9211 ("rceil")
9212 ("lfloor")
9213 ("rfloor")
9214 ("lang")
9215 ("rang")
9216 ("loz") ("Diamond"."&loz;")
9217 ("spades") ("spadesuit"."&spades;")
9218 ("clubs") ("clubsuit"."&clubs;")
9219 ("hearts") ("diamondsuit"."&hearts;")
9220 ("diams") ("diamondsuit"."&diams;")
9221 ("quot")
9222 ("amp")
9223 ("lt")
9224 ("gt")
9225 ("OElig")
9226 ("oelig")
9227 ("Scaron")
9228 ("scaron")
9229 ("Yuml")
9230 ("circ")
9231 ("tilde")
9232 ("ensp")
9233 ("emsp")
9234 ("thinsp")
9235 ("zwnj")
9236 ("zwj")
9237 ("lrm")
9238 ("rlm")
9239 ("ndash")
9240 ("mdash")
9241 ("lsquo")
9242 ("rsquo")
9243 ("sbquo")
9244 ("ldquo")
9245 ("rdquo")
9246 ("bdquo")
9247 ("dagger")
9248 ("Dagger")
9249 ("permil")
9250 ("lsaquo")
9251 ("rsaquo")
9252 ("euro")
9253
9254 ("arccos"."arccos")
9255 ("arcsin"."arcsin")
9256 ("arctan"."arctan")
9257 ("arg"."arg")
9258 ("cos"."cos")
9259 ("cosh"."cosh")
9260 ("cot"."cot")
9261 ("coth"."coth")
9262 ("csc"."csc")
9263 ("deg"."deg")
9264 ("det"."det")
9265 ("dim"."dim")
9266 ("exp"."exp")
9267 ("gcd"."gcd")
9268 ("hom"."hom")
9269 ("inf"."inf")
9270 ("ker"."ker")
9271 ("lg"."lg")
9272 ("lim"."lim")
9273 ("liminf"."liminf")
9274 ("limsup"."limsup")
9275 ("ln"."ln")
9276 ("log"."log")
9277 ("max"."max")
9278 ("min"."min")
9279 ("Pr"."Pr")
9280 ("sec"."sec")
9281 ("sin"."sin")
9282 ("sinh"."sinh")
9283 ("sup"."sup")
9284 ("tan"."tan")
9285 ("tanh"."tanh")
9286 )
9287 "Entities for TeX->HTML translation.
9288 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9289 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9290 In that case, \"\\ent\" will be translated to \"&other;\".
9291 The list contains HTML entities for Latin-1, Greek and other symbols.
9292 It is supplemented by a number of commonly used TeX macros with appropriate
9293 translations. There is currently no way for users to extend this.")
9294
9295 (defvar org-last-level nil) ; dynamically scoped variable
9296
9297 (defun org-export-as-ascii (arg)
9298 "Export the outline as a pretty ASCII file.
9299 If there is an active region, export only the region.
9300 The prefix ARG specifies how many levels of the outline should become
9301 underlined headlines. The default is 3."
9302 (interactive "P")
9303 (setq-default org-todo-line-regexp org-todo-line-regexp)
9304 (let* ((region
9305 (buffer-substring
9306 (if (org-region-active-p) (region-beginning) (point-min))
9307 (if (org-region-active-p) (region-end) (point-max))))
9308 (lines (org-export-find-first-heading-line
9309 (org-skip-comments (org-split-string region "[\r\n]"))))
9310 (org-startup-with-deadline-check nil)
9311 (level 0) line txt
9312 (umax nil)
9313 (case-fold-search nil)
9314 (filename (concat (file-name-sans-extension (buffer-file-name))
9315 ".txt"))
9316 (buffer (find-file-noselect filename))
9317 (levels-open (make-vector org-level-max nil))
9318 (date (format-time-string "%Y/%m/%d" (current-time)))
9319 (time (format-time-string "%X" (current-time)))
9320 (author user-full-name)
9321 (title (buffer-name))
9322 (options nil)
9323 (email user-mail-address)
9324 (language org-export-default-language)
9325 (text nil)
9326 (todo nil)
9327 (lang-words nil))
9328
9329 (setq org-last-level 1)
9330 (org-init-section-numbers)
9331
9332 (find-file-noselect filename)
9333
9334 ;; Search for the export key lines
9335 (org-parse-key-lines)
9336
9337 (setq lang-words (or (assoc language org-export-language-setup)
9338 (assoc "en" org-export-language-setup)))
9339 (if org-export-ascii-show-new-buffer
9340 (switch-to-buffer-other-window buffer)
9341 (set-buffer buffer))
9342 (erase-buffer)
9343 (fundamental-mode)
9344 (if options (org-parse-export-options options))
9345 (setq umax (if arg (prefix-numeric-value arg)
9346 org-export-headline-levels))
9347
9348 ;; File header
9349 (if title (org-insert-centered title ?=))
9350 (insert "\n")
9351 (if (or author email)
9352 (insert (concat (nth 1 lang-words) ": " (or author "")
9353 (if email (concat " <" email ">") "")
9354 "\n")))
9355 (if (and date time)
9356 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
9357 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
9358
9359 (insert "\n\n")
9360
9361 (if org-export-with-toc
9362 (progn
9363 (insert (nth 3 lang-words) "\n"
9364 (make-string (length (nth 3 lang-words)) ?=) "\n")
9365 (mapcar '(lambda (line)
9366 (if (string-match org-todo-line-regexp
9367 line)
9368 ;; This is a headline
9369 (progn
9370 (setq level (- (match-end 1) (match-beginning 1))
9371 txt (match-string 3 line)
9372 todo
9373 (or (and (match-beginning 2)
9374 (not (equal (match-string 2 line)
9375 org-done-string)))
9376 ; TODO, not DONE
9377 (and (= level umax)
9378 (org-search-todo-below
9379 line lines level))))
9380 (setq txt (org-html-expand-for-ascii txt))
9381
9382 (if org-export-with-section-numbers
9383 (setq txt (concat (org-section-number level)
9384 " " txt)))
9385 (if (<= level umax)
9386 (progn
9387 (insert
9388 (make-string (* (1- level) 4) ?\ )
9389 (format (if todo "%s (*)\n" "%s\n") txt))
9390 (setq org-last-level level))
9391 ))))
9392 lines)))
9393
9394 (org-init-section-numbers)
9395 (while (setq line (pop lines))
9396 ;; Remove the quoted HTML tags.
9397 (setq line (org-html-expand-for-ascii line))
9398 (cond
9399 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9400 ;; a Headline
9401 (setq level (- (match-end 1) (match-beginning 1))
9402 txt (match-string 2 line))
9403 (org-ascii-level-start level txt umax))
9404 (t (insert line "\n"))))
9405 (normal-mode)
9406 (save-buffer)
9407 (goto-char (point-min))))
9408
9409 (defun org-search-todo-below (line lines level)
9410 "Search the subtree below LINE for any TODO entries."
9411 (let ((rest (cdr (memq line lines)))
9412 (re org-todo-line-regexp)
9413 line lv todo)
9414 (catch 'exit
9415 (while (setq line (pop rest))
9416 (if (string-match re line)
9417 (progn
9418 (setq lv (- (match-end 1) (match-beginning 1))
9419 todo (and (match-beginning 2)
9420 (not (equal (match-string 2 line)
9421 org-done-string))))
9422 ; TODO, not DONE
9423 (if (<= lv level) (throw 'exit nil))
9424 (if todo (throw 'exit t))))))))
9425
9426 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
9427 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
9428 (defun org-html-expand-for-ascii (line)
9429 "Handle quoted HTML for ASCII export."
9430 (if org-export-html-expand
9431 (while (string-match "@<[^<>\n]*>" line)
9432 ;; We just remove the tags for now.
9433 (setq line (replace-match "" nil nil line))))
9434 line)
9435
9436 (defun org-insert-centered (s &optional underline)
9437 "Insert the string S centered and underline it with character UNDERLINE."
9438 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
9439 (insert (make-string ind ?\ ) s "\n")
9440 (if underline
9441 (insert (make-string ind ?\ )
9442 (make-string (length s) underline)
9443 "\n"))))
9444
9445 (defun org-ascii-level-start (level title umax)
9446 "Insert a new level in ASCII export."
9447 (let (char)
9448 (if (> level umax)
9449 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
9450 (if (or (not (equal (char-before) ?\n))
9451 (not (equal (char-before (1- (point))) ?\n)))
9452 (insert "\n"))
9453 (setq char (nth (- umax level) (reverse org-ascii-underline)))
9454 (if org-export-with-section-numbers
9455 (setq title (concat (org-section-number level) " " title)))
9456 (insert title "\n" (make-string (string-width title) char) "\n"))))
9457
9458 (defun org-export-copy-visible ()
9459 "Copy the visible part of the buffer to another buffer, for printing.
9460 Also removes the first line of the buffer if it specifies a mode,
9461 and all options lines."
9462 (interactive)
9463 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
9464 ".txt"))
9465 (buffer (find-file-noselect filename))
9466 (ore (concat
9467 (org-make-options-regexp
9468 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
9469 "STARTUP" "ARCHIVE"
9470 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
9471 (if org-noutline-p "\\(\n\\|$\\)" "")))
9472 s e)
9473 (with-current-buffer buffer
9474 (erase-buffer)
9475 (text-mode))
9476 (save-excursion
9477 (setq s (goto-char (point-min)))
9478 (while (not (= (point) (point-max)))
9479 (goto-char (org-find-invisible))
9480 (append-to-buffer buffer s (point))
9481 (setq s (goto-char (org-find-visible)))))
9482 (switch-to-buffer-other-window buffer)
9483 (newline)
9484 (goto-char (point-min))
9485 (if (looking-at ".*-\\*- mode:.*\n")
9486 (replace-match ""))
9487 (while (re-search-forward ore nil t)
9488 (replace-match ""))
9489 (goto-char (point-min))))
9490
9491 (defun org-find-visible ()
9492 (if (featurep 'noutline)
9493 (let ((s (point)))
9494 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9495 (get-char-property s 'invisible)))
9496 s)
9497 (skip-chars-forward "^\n")
9498 (point)))
9499 (defun org-find-invisible ()
9500 (if (featurep 'noutline)
9501 (let ((s (point)))
9502 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
9503 (not (get-char-property s 'invisible))))
9504 s)
9505 (skip-chars-forward "^\r")
9506 (point)))
9507
9508 ;; HTML
9509
9510 (defun org-get-current-options ()
9511 "Return a string with current options as keyword options.
9512 Does include HTML export options as well as TODO and CATEGORY stuff."
9513 (format
9514 "#+TITLE: %s
9515 #+AUTHOR: %s
9516 #+EMAIL: %s
9517 #+LANGUAGE: %s
9518 #+TEXT: Some descriptive text to be emitted. Several lines OK.
9519 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
9520 #+CATEGORY: %s
9521 #+SEQ_TODO: %s
9522 #+TYP_TODO: %s
9523 #+STARTUP: %s %s
9524 #+ARCHIVE: %s
9525 "
9526 (buffer-name) (user-full-name) user-mail-address org-export-default-language
9527 org-export-headline-levels
9528 org-export-with-section-numbers
9529 org-export-with-toc
9530 org-export-preserve-breaks
9531 org-export-html-expand
9532 org-export-with-fixed-width
9533 org-export-with-tables
9534 org-export-with-sub-superscripts
9535 org-export-with-emphasize
9536 org-export-with-TeX-macros
9537 (file-name-nondirectory (buffer-file-name))
9538 (if (equal org-todo-interpretation 'sequence)
9539 (mapconcat 'identity org-todo-keywords " ")
9540 "TODO FEEDBACK VERIFY DONE")
9541 (if (equal org-todo-interpretation 'type)
9542 (mapconcat 'identity org-todo-keywords " ")
9543 "Me Jason Marie DONE")
9544 (cdr (assoc org-startup-folded
9545 '((nil . "nofold")(t . "fold")(content . "content"))))
9546 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
9547 org-archive-location
9548 ))
9549
9550 (defun org-insert-export-options-template ()
9551 "Insert into the buffer a template with information for exporting."
9552 (interactive)
9553 (if (not (bolp)) (newline))
9554 (let ((s (org-get-current-options)))
9555 (and (string-match "#\\+CATEGORY" s)
9556 (setq s (substring s 0 (match-beginning 0))))
9557 (insert s)))
9558
9559 (defun org-toggle-fixed-width-section (arg)
9560 "Toggle the fixed-width export.
9561 If there is no active region, the QUOTE keyword at the current headline is
9562 inserted or removed. When present, it causes the text between this headline
9563 and the next to be exported as fixed-width text, and unmodified.
9564 If there is an active region, this command adds or removes a colon as the
9565 first character of this line. If the first character of a line is a colon,
9566 this line is also exported in fixed-width font."
9567 (interactive "P")
9568 (let* ((cc 0)
9569 (regionp (org-region-active-p))
9570 (beg (if regionp (region-beginning) (point)))
9571 (end (if regionp (region-end)))
9572 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
9573 (re "[ \t]*\\(:\\)")
9574 off)
9575 (if regionp
9576 (save-excursion
9577 (goto-char beg)
9578 (setq cc (current-column))
9579 (beginning-of-line 1)
9580 (setq off (looking-at re))
9581 (while (> nlines 0)
9582 (setq nlines (1- nlines))
9583 (beginning-of-line 1)
9584 (cond
9585 (arg
9586 (move-to-column cc t)
9587 (insert ":\n")
9588 (forward-line -1))
9589 ((and off (looking-at re))
9590 (replace-match "" t t nil 1))
9591 ((not off) (move-to-column cc t) (insert ":")))
9592 (forward-line 1)))
9593 (save-excursion
9594 (org-back-to-heading)
9595 (if (looking-at (concat outline-regexp
9596 "\\( +\\<" org-quote-string "\\>\\)"))
9597 (replace-match "" t t nil 1)
9598 (if (looking-at outline-regexp)
9599 (progn
9600 (goto-char (match-end 0))
9601 (insert " " org-quote-string))))))))
9602
9603 (defun org-export-as-html-and-open (arg)
9604 "Export the outline as HTML and immediately open it with a browser.
9605 If there is an active region, export only the region.
9606 The prefix ARG specifies how many levels of the outline should become
9607 headlines. The default is 3. Lower levels will become bulleted lists."
9608 (interactive "P")
9609 (org-export-as-html arg 'hidden)
9610 (org-open-file (buffer-file-name)))
9611
9612 (defun org-export-as-html-batch ()
9613 "Call `org-export-as-html', may be used in batch processing as
9614 emacs --batch
9615 --load=$HOME/lib/emacs/org.el
9616 --eval \"(setq org-export-headline-levels 2)\"
9617 --visit=MyFile --funcall org-export-as-html-batch"
9618 (org-export-as-html org-export-headline-levels 'hidden))
9619
9620 (defun org-export-as-html (arg &optional hidden)
9621 "Export the outline as a pretty HTML file.
9622 If there is an active region, export only the region.
9623 The prefix ARG specifies how many levels of the outline should become
9624 headlines. The default is 3. Lower levels will become bulleted lists."
9625 (interactive "P")
9626 (setq-default org-todo-line-regexp org-todo-line-regexp)
9627 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
9628 (setq-default org-done-string org-done-string)
9629 (let* ((style org-export-html-style)
9630 (region-p (org-region-active-p))
9631 (region
9632 (buffer-substring
9633 (if region-p (region-beginning) (point-min))
9634 (if region-p (region-end) (point-max))))
9635 (all_lines
9636 (org-skip-comments (org-split-string region "[\r\n]")))
9637 (lines (org-export-find-first-heading-line all_lines))
9638 (level 0) (line "") (origline "") txt todo
9639 (umax nil)
9640 (filename (concat (file-name-sans-extension (buffer-file-name))
9641 ".html"))
9642 (buffer (find-file-noselect filename))
9643 (levels-open (make-vector org-level-max nil))
9644 (date (format-time-string "%Y/%m/%d" (current-time)))
9645 (time (format-time-string "%X" (current-time)))
9646 (author user-full-name)
9647 (title (buffer-name))
9648 (options nil)
9649 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
9650 (inquote nil)
9651 (infixed nil)
9652 (in-local-list nil)
9653 (local-list-num nil)
9654 (local-list-indent nil)
9655 (llt org-plain-list-ordered-item-terminator)
9656 (email user-mail-address)
9657 (language org-export-default-language)
9658 (text nil)
9659 (lang-words nil)
9660 (head-count 0) cnt
9661 (start 0)
9662 ;; FIXME: The following returns always nil under XEmacs
9663 (coding-system (and (fboundp 'coding-system-get)
9664 (boundp 'buffer-file-coding-system)
9665 buffer-file-coding-system))
9666 (coding-system-for-write (or coding-system coding-system-for-write))
9667 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
9668 (charset (and coding-system
9669 (coding-system-get coding-system 'mime-charset)))
9670 table-open type
9671 table-buffer table-orig-buffer
9672 ind start-is-num starter
9673 )
9674 (message "Exporting...")
9675
9676 (setq org-last-level 1)
9677 (org-init-section-numbers)
9678
9679 ;; Search for the export key lines
9680 (org-parse-key-lines)
9681 (setq lang-words (or (assoc language org-export-language-setup)
9682 (assoc "en" org-export-language-setup)))
9683
9684 ;; Switch to the output buffer
9685 (if (or hidden (not org-export-html-show-new-buffer))
9686 (set-buffer buffer)
9687 (switch-to-buffer-other-window buffer))
9688 (erase-buffer)
9689 (fundamental-mode)
9690 (let ((case-fold-search nil))
9691 (if options (org-parse-export-options options))
9692 (setq umax (if arg (prefix-numeric-value arg)
9693 org-export-headline-levels))
9694
9695 ;; File header
9696 (insert (format
9697 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
9698 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
9699 <html lang=\"%s\"><head>
9700 <title>%s</title>
9701 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
9702 <meta name=generator content=\"Org-mode\">
9703 <meta name=generated content=\"%s %s\">
9704 <meta name=author content=\"%s\">
9705 %s
9706 </head><body>
9707 "
9708 language (org-html-expand title) (or charset "iso-8859-1")
9709 date time author style))
9710 (if title (insert (concat "<H1 class=\"title\">"
9711 (org-html-expand title) "</H1>\n")))
9712 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
9713 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
9714 email "&gt;</a>\n")))
9715 (if (or author email) (insert "<br>\n"))
9716 (if (and date time) (insert (concat (nth 2 lang-words) ": "
9717 date " " time "<br>\n")))
9718 (if text (insert (concat "<p>\n" (org-html-expand text))))
9719 (if org-export-with-toc
9720 (progn
9721 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
9722 (insert "<ul>\n")
9723 (mapcar '(lambda (line)
9724 (if (string-match org-todo-line-regexp line)
9725 ;; This is a headline
9726 (progn
9727 (setq level (- (match-end 1) (match-beginning 1))
9728 txt (save-match-data
9729 (org-html-expand
9730 (match-string 3 line)))
9731 todo
9732 (or (and (match-beginning 2)
9733 (not (equal (match-string 2 line)
9734 org-done-string)))
9735 ; TODO, not DONE
9736 (and (= level umax)
9737 (org-search-todo-below
9738 line lines level))))
9739 (if org-export-with-section-numbers
9740 (setq txt (concat (org-section-number level)
9741 " " txt)))
9742 (if (<= level umax)
9743 (progn
9744 (setq head-count (+ head-count 1))
9745 (if (> level org-last-level)
9746 (progn
9747 (setq cnt (- level org-last-level))
9748 (while (>= (setq cnt (1- cnt)) 0)
9749 (insert "<ul>"))
9750 (insert "\n")))
9751 (if (< level org-last-level)
9752 (progn
9753 (setq cnt (- org-last-level level))
9754 (while (>= (setq cnt (1- cnt)) 0)
9755 (insert "</ul>"))
9756 (insert "\n")))
9757 (insert
9758 (format
9759 (if todo
9760 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
9761 "<li><a href=\"#sec-%d\">%s</a>\n")
9762 head-count txt))
9763 (setq org-last-level level))
9764 ))))
9765 lines)
9766 (while (> org-last-level 0)
9767 (setq org-last-level (1- org-last-level))
9768 (insert "</ul>\n"))
9769 ))
9770 (setq head-count 0)
9771 (org-init-section-numbers)
9772
9773 (while (setq line (pop lines) origline line)
9774 (catch 'nextline
9775
9776 ;; end of quote section?
9777 (when (and inquote (string-match "^\\*+" line))
9778 (insert "</pre>\n")
9779 (setq inquote nil))
9780 ;; inside a quote section?
9781 (when inquote
9782 (insert (org-html-protect line) "\n")
9783 (throw 'nextline nil))
9784
9785 ;; verbatim lines
9786 (when (and org-export-with-fixed-width
9787 (string-match "^[ \t]*:\\(.*\\)" line))
9788 (when (not infixed)
9789 (setq infixed t)
9790 (insert "<pre>\n"))
9791 (insert (org-html-protect (match-string 1 line)) "\n")
9792 (when (and lines
9793 (not (string-match "^[ \t]*\\(:.*\\)"
9794 (car lines))))
9795 (setq infixed nil)
9796 (insert "</pre>\n"))
9797 (throw 'nextline nil))
9798
9799 ;; Protect the links
9800 (setq start 0)
9801 (while (string-match org-link-maybe-angles-regexp line start)
9802 (setq start (match-end 0))
9803 (setq line (replace-match
9804 (concat "\000" (match-string 1 line) "\000")
9805 t t line)))
9806
9807 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
9808 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
9809 (setq line (org-html-expand line))
9810
9811 ;; Format the links
9812 (setq start 0)
9813 (while (string-match org-protected-link-regexp line start)
9814 (setq start (- (match-end 0) 2))
9815 (setq type (match-string 1 line))
9816 (cond
9817 ((member type '("http" "https" "ftp" "mailto" "news"))
9818 ;; standard URL
9819 (setq line (replace-match
9820 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
9821 "<a href=\"\\1:\\2\">\\1:\\2</a>"
9822 nil nil line)))
9823 ((string= type "file")
9824 ;; FILE link
9825 (let* ((filename (match-string 2 line))
9826 (abs-p (file-name-absolute-p filename))
9827 (thefile (if abs-p (expand-file-name filename) filename))
9828 (thefile (save-match-data
9829 (if (string-match ":[0-9]+$" thefile)
9830 (replace-match "" t t thefile)
9831 thefile)))
9832 (file-is-image-p
9833 (save-match-data
9834 (string-match (org-image-file-name-regexp) thefile))))
9835 (setq line (replace-match
9836 (if (and org-export-html-inline-images
9837 file-is-image-p)
9838 (concat "<img src=\"" thefile "\"/>")
9839 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
9840 nil nil line))))
9841
9842 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
9843 (setq line (replace-match
9844 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
9845
9846 ;; TODO items
9847 (if (and (string-match org-todo-line-regexp line)
9848 (match-beginning 2))
9849 (if (equal (match-string 2 line) org-done-string)
9850 (setq line (replace-match
9851 "<span class=\"done\">\\2</span>"
9852 nil nil line 2))
9853 (setq line (replace-match "<span class=\"todo\">\\2</span>"
9854 nil nil line 2))))
9855
9856 ;; DEADLINES
9857 (if (string-match org-deadline-line-regexp line)
9858 (progn
9859 (if (save-match-data
9860 (string-match "<a href"
9861 (substring line 0 (match-beginning 0))))
9862 nil ; Don't do the replacement - it is inside a link
9863 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
9864 nil nil line 1)))))
9865 (cond
9866 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
9867 ;; This is a headline
9868 (setq level (- (match-end 1) (match-beginning 1))
9869 txt (match-string 2 line))
9870 (if (<= level umax) (setq head-count (+ head-count 1)))
9871 (when in-local-list
9872 ;; Close any local lists before inserting a new header line
9873 (while local-list-num
9874 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
9875 (pop local-list-num))
9876 (setq local-list-indent nil
9877 in-local-list nil))
9878 (org-html-level-start level txt umax
9879 (and org-export-with-toc (<= level umax))
9880 head-count)
9881 ;; QUOTES
9882 (when (string-match quote-re line)
9883 (insert "<pre>")
9884 (setq inquote t)))
9885
9886 ((and org-export-with-tables
9887 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
9888 (if (not table-open)
9889 ;; New table starts
9890 (setq table-open t table-buffer nil table-orig-buffer nil))
9891 ;; Accumulate lines
9892 (setq table-buffer (cons line table-buffer)
9893 table-orig-buffer (cons origline table-orig-buffer))
9894 (when (or (not lines)
9895 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
9896 (car lines))))
9897 (setq table-open nil
9898 table-buffer (nreverse table-buffer)
9899 table-orig-buffer (nreverse table-orig-buffer))
9900 (insert (org-format-table-html table-buffer table-orig-buffer))))
9901 (t
9902 ;; Normal lines
9903 (when (and (> org-export-plain-list-max-depth 0)
9904 (string-match
9905 (cond
9906 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9907 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9908 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
9909 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
9910 line))
9911 (setq ind (org-get-string-indentation line)
9912 start-is-num (match-beginning 4)
9913 starter (if (match-beginning 2) (match-string 2 line))
9914 line (substring line (match-beginning 5)))
9915 (unless (string-match "[^ \t]" line)
9916 ;; empty line. Pretend indentation is large.
9917 (setq ind (1+ (or (car local-list-indent) 1))))
9918 (while (and in-local-list
9919 (or (and (= ind (car local-list-indent))
9920 (not starter))
9921 (< ind (car local-list-indent))))
9922 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
9923 (pop local-list-num) (pop local-list-indent)
9924 (setq in-local-list local-list-indent))
9925 (cond
9926 ((and starter
9927 (or (not in-local-list)
9928 (> ind (car local-list-indent)))
9929 (< (length local-list-indent)
9930 org-export-plain-list-max-depth))
9931 ;; Start new (level of ) list
9932 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
9933 (push start-is-num local-list-num)
9934 (push ind local-list-indent)
9935 (setq in-local-list t))
9936 (starter
9937 ;; continue current list
9938 (insert "<li>\n"))))
9939 ;; Empty lines start a new paragraph. If hand-formatted lists
9940 ;; are not fully interpreted, lines starting with "-", "+", "*"
9941 ;; also start a new paragraph.
9942 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
9943 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
9944 ))
9945 (if org-export-html-with-timestamp
9946 (insert org-export-html-html-helper-timestamp))
9947 (insert "</body>\n</html>\n")
9948 (normal-mode)
9949 (save-buffer)
9950 (goto-char (point-min)))))
9951
9952 (defun org-format-table-html (lines olines)
9953 "Find out which HTML converter to use and return the HTML code."
9954 (if (string-match "^[ \t]*|" (car lines))
9955 ;; A normal org table
9956 (org-format-org-table-html lines)
9957 ;; Table made by table.el - test for spanning
9958 (let* ((hlines (delq nil (mapcar
9959 (lambda (x)
9960 (if (string-match "^[ \t]*\\+-" x) x
9961 nil))
9962 lines)))
9963 (first (car hlines))
9964 (ll (and (string-match "\\S-+" first)
9965 (match-string 0 first)))
9966 (re (concat "^[ \t]*" (regexp-quote ll)))
9967 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
9968 hlines))))
9969 (if (and (not spanning)
9970 (not org-export-prefer-native-exporter-for-tables))
9971 ;; We can use my own converter with HTML conversions
9972 (org-format-table-table-html lines)
9973 ;; Need to use the code generator in table.el, with the original text.
9974 (org-format-table-table-html-using-table-generate-source olines)))))
9975
9976 (defun org-format-org-table-html (lines)
9977 "Format a table into html."
9978 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9979 (setq lines (nreverse lines))
9980 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
9981 (setq lines (nreverse lines))
9982 (let ((head (and org-export-highlight-first-table-line
9983 (delq nil (mapcar
9984 (lambda (x) (string-match "^[ \t]*|-" x))
9985 (cdr lines)))))
9986 line fields html)
9987 (setq html (concat org-export-html-table-tag "\n"))
9988 (while (setq line (pop lines))
9989 (catch 'next-line
9990 (if (string-match "^[ \t]*|-" line)
9991 (progn
9992 (setq head nil) ;; head ends here, first time around
9993 ;; ignore this line
9994 (throw 'next-line t)))
9995 ;; Break the line into fields
9996 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9997 (setq html (concat
9998 html
9999 "<tr>"
10000 (mapconcat (lambda (x)
10001 (if head
10002 (concat "<th>" x "</th>")
10003 (concat "<td>" x "</td>")))
10004 fields "")
10005 "</tr>\n"))))
10006 (setq html (concat html "</table>\n"))
10007 html))
10008
10009 (defun org-fake-empty-table-line (line)
10010 "Replace everything except \"|\" with spaces."
10011 (let ((i (length line))
10012 (newstr (copy-sequence line)))
10013 (while (> i 0)
10014 (setq i (1- i))
10015 (if (not (eq (aref newstr i) ?|))
10016 (aset newstr i ?\ )))
10017 newstr))
10018
10019 (defun org-format-table-table-html (lines)
10020 "Format a table generated by table.el into html.
10021 This conversion does *not* use `table-generate-source' from table.el.
10022 This has the advantage that Org-mode's HTML conversions can be used.
10023 But it has the disadvantage, that no cell- or row-spanning is allowed."
10024 (let (line field-buffer
10025 (head org-export-highlight-first-table-line)
10026 fields html empty)
10027 (setq html (concat org-export-html-table-tag "\n"))
10028 (while (setq line (pop lines))
10029 (setq empty "&nbsp")
10030 (catch 'next-line
10031 (if (string-match "^[ \t]*\\+-" line)
10032 (progn
10033 (if field-buffer
10034 (progn
10035 (setq html (concat
10036 html
10037 "<tr>"
10038 (mapconcat
10039 (lambda (x)
10040 (if (equal x "") (setq x empty))
10041 (if head
10042 (concat "<th>" x "</th>\n")
10043 (concat "<td>" x "</td>\n")))
10044 field-buffer "\n")
10045 "</tr>\n"))
10046 (setq head nil)
10047 (setq field-buffer nil)))
10048 ;; Ignore this line
10049 (throw 'next-line t)))
10050 ;; Break the line into fields and store the fields
10051 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10052 (if field-buffer
10053 (setq field-buffer (mapcar
10054 (lambda (x)
10055 (concat x "<br>" (pop fields)))
10056 field-buffer))
10057 (setq field-buffer fields))))
10058 (setq html (concat html "</table>\n"))
10059 html))
10060
10061 (defun org-format-table-table-html-using-table-generate-source (lines)
10062 "Format a table into html, using `table-generate-source' from table.el.
10063 This has the advantage that cell- or row-spanning is allowed.
10064 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10065 (require 'table)
10066 (with-current-buffer (get-buffer-create " org-tmp1 ")
10067 (erase-buffer)
10068 (insert (mapconcat 'identity lines "\n"))
10069 (goto-char (point-min))
10070 (if (not (re-search-forward "|[^+]" nil t))
10071 (error "Error processing table"))
10072 (table-recognize-table)
10073 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10074 (table-generate-source 'html " org-tmp2 ")
10075 (set-buffer " org-tmp2 ")
10076 (buffer-substring (point-min) (point-max))))
10077
10078 (defun org-html-protect (s)
10079 ;; convert & to &amp;, < to &lt; and > to &gt;
10080 (let ((start 0))
10081 (while (string-match "&" s start)
10082 (setq s (replace-match "&amp;" t t s)
10083 start (1+ (match-beginning 0))))
10084 (while (string-match "<" s)
10085 (setq s (replace-match "&lt;" t t s)))
10086 (while (string-match ">" s)
10087 (setq s (replace-match "&gt;" t t s))))
10088 s)
10089
10090 (defun org-html-expand (string)
10091 "Prepare STRING for HTML export. Applies all active conversions."
10092 ;; First check if there is a link in the line - if yes, apply conversions
10093 ;; only before the start of the link.
10094 ;; FIXME: This is no longer correct, because links now have an end.
10095 (let* ((m (string-match org-link-regexp string))
10096 (s (if m (substring string 0 m) string))
10097 (r (if m (substring string m) "")))
10098 ;; convert & to &amp;, < to &lt; and > to &gt;
10099 (setq s (org-html-protect s))
10100 (if org-export-html-expand
10101 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10102 (setq s (replace-match "<\\1>" nil nil s))))
10103 (if org-export-with-emphasize
10104 (setq s (org-export-html-convert-emphasize s)))
10105 (if org-export-with-sub-superscripts
10106 (setq s (org-export-html-convert-sub-super s)))
10107 (if org-export-with-TeX-macros
10108 (let ((start 0) wd ass)
10109 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10110 (setq wd (match-string 1 s))
10111 (if (setq ass (assoc wd org-html-entities))
10112 (setq s (replace-match (or (cdr ass)
10113 (concat "&" (car ass) ";"))
10114 t t s))
10115 (setq start (+ start (length wd)))))))
10116 (concat s r)))
10117
10118 (defun org-create-multibrace-regexp (left right n)
10119 "Create a regular expression which will match a balanced sexp.
10120 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10121 as single character strings.
10122 The regexp returned will match the entire expression including the
10123 delimiters. It will also define a single group which contains the
10124 match except for the outermost delimiters. The maximum depth of
10125 stacked delimiters is N. Escaping delimiters is not possible."
10126 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10127 (or "\\|")
10128 (re nothing)
10129 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10130 (while (> n 1)
10131 (setq n (1- n)
10132 re (concat re or next)
10133 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10134 (concat left "\\(" re "\\)" right)))
10135
10136 (defvar org-match-substring-regexp
10137 (concat
10138 "\\([^\\]\\)\\([_^]\\)\\("
10139 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10140 "\\|"
10141 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10142 "\\|"
10143 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10144 "The regular expression matching a sub- or superscript.")
10145
10146 (defun org-export-html-convert-sub-super (string)
10147 "Convert sub- and superscripts in STRING to HTML."
10148 (let (key c)
10149 (while (string-match org-match-substring-regexp string)
10150 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10151 (setq c (or (match-string 8 string)
10152 (match-string 6 string)
10153 (match-string 5 string)))
10154 (setq string (replace-match
10155 (concat (match-string 1 string)
10156 "<" key ">" c "</" key ">")
10157 t t string)))
10158 (while (string-match "\\\\\\([_^]\\)" string)
10159 (setq string (replace-match (match-string 1 string) t t string))))
10160 string)
10161
10162 (defun org-export-html-convert-emphasize (string)
10163 (while (string-match
10164 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10165 string)
10166 (setq string (replace-match
10167 (concat "<b>" (match-string 3 string) "</b>")
10168 t t string 2)))
10169 (while (string-match
10170 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10171 string)
10172 (setq string (replace-match
10173 (concat "<i>" (match-string 3 string) "</i>")
10174 t t string 2)))
10175 (while (string-match
10176 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10177 string)
10178 (setq string (replace-match
10179 (concat "<u>" (match-string 3 string) "</u>")
10180 t t string 2)))
10181 string)
10182
10183 (defun org-parse-key-lines ()
10184 "Find the special key lines with the information for exporters."
10185 (save-excursion
10186 (goto-char 0)
10187 (let ((re (org-make-options-regexp
10188 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10189 key)
10190 (while (re-search-forward re nil t)
10191 (setq key (match-string 1))
10192 (cond ((string-equal key "TITLE")
10193 (setq title (match-string 2)))
10194 ((string-equal key "AUTHOR")
10195 (setq author (match-string 2)))
10196 ((string-equal key "EMAIL")
10197 (setq email (match-string 2)))
10198 ((string-equal key "LANGUAGE")
10199 (setq language (match-string 2)))
10200 ((string-equal key "TEXT")
10201 (setq text (concat text "\n" (match-string 2))))
10202 ((string-equal key "OPTIONS")
10203 (setq options (match-string 2))))))))
10204
10205 (defun org-parse-export-options (s)
10206 "Parse the export options line."
10207 (let ((op '(("H" . org-export-headline-levels)
10208 ("num" . org-export-with-section-numbers)
10209 ("toc" . org-export-with-toc)
10210 ("\\n" . org-export-preserve-breaks)
10211 ("@" . org-export-html-expand)
10212 (":" . org-export-with-fixed-width)
10213 ("|" . org-export-with-tables)
10214 ("^" . org-export-with-sub-superscripts)
10215 ("*" . org-export-with-emphasize)
10216 ("TeX" . org-export-with-TeX-macros)))
10217 o)
10218 (while (setq o (pop op))
10219 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10220 s)
10221 (set (make-local-variable (cdr o))
10222 (car (read-from-string (match-string 1 s))))))))
10223
10224 (defun org-html-level-start (level title umax with-toc head-count)
10225 "Insert a new level in HTML export."
10226 (let ((l (1+ (max level umax))))
10227 (while (<= l org-level-max)
10228 (if (aref levels-open (1- l))
10229 (progn
10230 (org-html-level-close l)
10231 (aset levels-open (1- l) nil)))
10232 (setq l (1+ l)))
10233 (if (> level umax)
10234 (progn
10235 (if (aref levels-open (1- level))
10236 (insert "<li>" title "<p>\n")
10237 (aset levels-open (1- level) t)
10238 (insert "<ul><li>" title "<p>\n")))
10239 (if org-export-with-section-numbers
10240 (setq title (concat (org-section-number level) " " title)))
10241 (setq level (+ level 1))
10242 (if with-toc
10243 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10244 level head-count title level))
10245 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10246
10247 (defun org-html-level-close (&rest args)
10248 "Terminate one level in HTML export."
10249 (insert "</ul>"))
10250
10251 ;; Variable holding the vector with section numbers
10252 (defvar org-section-numbers (make-vector org-level-max 0))
10253
10254 (defun org-init-section-numbers ()
10255 "Initialize the vector for the section numbers."
10256 (let* ((level -1)
10257 (numbers (nreverse (org-split-string "" "\\.")))
10258 (depth (1- (length org-section-numbers)))
10259 (i depth) number-string)
10260 (while (>= i 0)
10261 (if (> i level)
10262 (aset org-section-numbers i 0)
10263 (setq number-string (or (car numbers) "0"))
10264 (if (string-match "\\`[A-Z]\\'" number-string)
10265 (aset org-section-numbers i
10266 (- (string-to-char number-string) ?A -1))
10267 (aset org-section-numbers i (string-to-number number-string)))
10268 (pop numbers))
10269 (setq i (1- i)))))
10270
10271 (defun org-section-number (&optional level)
10272 "Return a string with the current section number.
10273 When LEVEL is non-nil, increase section numbers on that level."
10274 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10275 (when level
10276 (when (> level -1)
10277 (aset org-section-numbers
10278 level (1+ (aref org-section-numbers level))))
10279 (setq idx (1+ level))
10280 (while (<= idx depth)
10281 (if (not (= idx 1))
10282 (aset org-section-numbers idx 0))
10283 (setq idx (1+ idx))))
10284 (setq idx 0)
10285 (while (<= idx depth)
10286 (setq n (aref org-section-numbers idx))
10287 (setq string (concat string (if (not (string= string "")) "." "")
10288 (int-to-string n)))
10289 (setq idx (1+ idx)))
10290 (save-match-data
10291 (if (string-match "\\`\\([@0]\\.\\)+" string)
10292 (setq string (replace-match "" nil nil string)))
10293 (if (string-match "\\(\\.0\\)+\\'" string)
10294 (setq string (replace-match "" nil nil string))))
10295 string))
10296
10297
10298 (defun org-export-icalendar-this-file ()
10299 "Export current file as an iCalendar file.
10300 The iCalendar file will be located in the same directory as the Org-mode
10301 file, but with extension `.ics'."
10302 (interactive)
10303 (org-export-icalendar nil (buffer-file-name)))
10304
10305 ;;;###autoload
10306 (defun org-export-icalendar-all-agenda-files ()
10307 "Export all files in `org-agenda-files' to iCalendar .ics files.
10308 Each iCalendar file will be located in the same directory as the Org-mode
10309 file, but with extension `.ics'."
10310 (interactive)
10311 (apply 'org-export-icalendar nil org-agenda-files))
10312
10313 ;;;###autoload
10314 (defun org-export-icalendar-combine-agenda-files ()
10315 "Export all files in `org-agenda-files' to a single combined iCalendar file.
10316 The file is stored under the name `org-combined-agenda-icalendar-file'."
10317 (interactive)
10318 (apply 'org-export-icalendar t org-agenda-files))
10319
10320 (defun org-export-icalendar (combine &rest files)
10321 "Create iCalendar files for all elements of FILES.
10322 If COMBINE is non-nil, combine all calendar entries into a single large
10323 file and store it under the name `org-combined-agenda-icalendar-file'."
10324 (save-excursion
10325 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
10326 (when combine
10327 (setq ical-file org-combined-agenda-icalendar-file
10328 ical-buffer (org-get-agenda-file-buffer ical-file))
10329 (set-buffer ical-buffer) (erase-buffer))
10330 (while (setq file (pop files))
10331 (catch 'nextfile
10332 (org-check-agenda-file file)
10333 (unless combine
10334 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
10335 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
10336 (set-buffer ical-buffer) (erase-buffer))
10337 (set-buffer (org-get-agenda-file-buffer file))
10338 (setq category (or org-category
10339 (file-name-sans-extension
10340 (file-name-nondirectory (buffer-file-name)))))
10341 (if (symbolp category) (setq category (symbol-name category)))
10342 (let ((standard-output ical-buffer))
10343 (if combine
10344 (and (not started) (setq started t)
10345 (org-start-icalendar-file org-icalendar-combined-name))
10346 (org-start-icalendar-file category))
10347 (org-print-icalendar-entries combine category)
10348 (when (or (and combine (not files)) (not combine))
10349 (org-finish-icalendar-file)
10350 (set-buffer ical-buffer)
10351 (save-buffer)
10352 (run-hooks 'org-after-save-iCalendar-file-hook)))))
10353 (org-release-buffers org-agenda-new-buffers))))
10354
10355 (defvar org-after-save-iCalendar-file-hook nil
10356 "Hook run after an iCalendar file has been saved.
10357 The iCalendar buffer is still current when this hook is run.
10358 A good way to use this is to tell a desktop calenndar application to re-read
10359 the iCalendar file.")
10360
10361 (defun org-print-icalendar-entries (&optional combine category)
10362 "Print iCalendar entries for the current Org-mode file to `standard-output'.
10363 When COMBINE is non nil, add the category to each line."
10364 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
10365 (dts (org-ical-ts-to-string
10366 (format-time-string (cdr org-time-stamp-formats) (current-time))
10367 "DTSTART"))
10368 hd ts ts2 state (inc t) pos scheduledp deadlinep donep tmp pri)
10369 (save-excursion
10370 (goto-char (point-min))
10371 (while (re-search-forward org-ts-regexp nil t)
10372 (setq pos (match-beginning 0)
10373 ts (match-string 0)
10374 inc t
10375 hd (org-get-heading))
10376 (if (looking-at re2)
10377 (progn
10378 (goto-char (match-end 0))
10379 (setq ts2 (match-string 1) inc nil))
10380 (setq ts2 ts
10381 tmp (buffer-substring (max (point-min)
10382 (- pos org-ds-keyword-length))
10383 pos)
10384 deadlinep (string-match org-deadline-regexp tmp)
10385 scheduledp (string-match org-scheduled-regexp tmp)
10386 donep (org-entry-is-done-p)))
10387 (if (or (string-match org-tr-regexp hd)
10388 (string-match org-ts-regexp hd))
10389 (setq hd (replace-match "" t t hd)))
10390 (if combine
10391 (setq hd (concat hd " (category " category ")")))
10392 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
10393 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
10394 (princ (format "BEGIN:VEVENT
10395 %s
10396 %s
10397 SUMMARY:%s
10398 END:VEVENT\n"
10399 (org-ical-ts-to-string ts "DTSTART")
10400 (org-ical-ts-to-string ts2 "DTEND" inc)
10401 hd)))
10402 (when org-icalendar-include-todo
10403 (goto-char (point-min))
10404 (while (re-search-forward org-todo-line-regexp nil t)
10405 (setq state (match-string 1))
10406 (unless (equal state org-done-string)
10407 (setq hd (match-string 3))
10408 (if (string-match org-priority-regexp hd)
10409 (setq pri (string-to-char (match-string 2 hd))
10410 hd (concat (substring hd 0 (match-beginning 1))
10411 (substring hd (- (match-end 1)))))
10412 (setq pri org-default-priority))
10413 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
10414 (- org-lowest-priority ?A))))))
10415
10416 (princ (format "BEGIN:VTODO
10417 %s
10418 SUMMARY:%s
10419 SEQUENCE:1
10420 PRIORITY:%d
10421 END:VTODO\n"
10422 dts hd pri))))))))
10423
10424 (defun org-start-icalendar-file (name)
10425 "Start an iCalendar file by inserting the header."
10426 (let ((user user-full-name)
10427 (calname "something")
10428 (name (or name "unknown"))
10429 (timezone "Europe/Amsterdam")) ;; FIXME: How can I get the real timezone?
10430 (princ
10431 (format "BEGIN:VCALENDAR
10432 VERSION:2.0
10433 X-WR-CALNAME:%s
10434 PRODID:-//%s//Emacs with Org-mode//EN
10435 X-WR-TIMEZONE:%s
10436 CALSCALE:GREGORIAN\n" name user timezone))))
10437
10438 (defun org-finish-icalendar-file ()
10439 "Finish an iCalendar file by inserting the END statement."
10440 (princ "END:VCALENDAR\n"))
10441
10442 (defun org-ical-ts-to-string (s keyword &optional inc)
10443 "Take a time string S and convert it to iCalendar format.
10444 KEYWORD is added in front, to make a complete line like DTSTART....
10445 When INC is non-nil, increase the hour by two (if time string contains
10446 a time), or the day by one (if it does not contain a time)."
10447 (let ((t1 (org-parse-time-string s 'nodefault))
10448 t2 fmt have-time time)
10449 (if (and (car t1) (nth 1 t1) (nth 2 t1))
10450 (setq t2 t1 have-time t)
10451 (setq t2 (org-parse-time-string s)))
10452 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
10453 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
10454 (when inc
10455 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
10456 (setq time (encode-time s mi h d m y)))
10457 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
10458 (concat keyword (format-time-string fmt time))))
10459
10460
10461 ;;; Key bindings
10462
10463 ;; - Bindings in Org-mode map are currently
10464 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
10465 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
10466 ;; e (?) useful from outline-mode
10467 ;; i k @ expendable from outline-mode
10468 ;; 0123456789 ! %^& ()_{} " `' free
10469
10470 ;; Make `C-c C-x' a prefix key
10471 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
10472
10473 ;; TAB key with modifiers
10474 (define-key org-mode-map "\C-i" 'org-cycle)
10475 (define-key org-mode-map [(meta tab)] 'org-complete)
10476 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
10477 ;; The following line is necessary under Suse GNU/Linux
10478 (unless org-xemacs-p
10479 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
10480 (define-key org-mode-map [(shift tab)] 'org-shifttab)
10481
10482 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
10483 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
10484 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
10485 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
10486 (define-key org-mode-map [(meta return)] 'org-meta-return)
10487 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
10488 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
10489
10490 ;; Cursor keys with modifiers
10491 (define-key org-mode-map [(meta left)] 'org-metaleft)
10492 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
10493 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
10494 (define-key org-mode-map [(meta right)] 'org-metaright)
10495 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
10496 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
10497 (define-key org-mode-map [(meta up)] 'org-metaup)
10498 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
10499 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
10500 (define-key org-mode-map [(meta down)] 'org-metadown)
10501 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
10502 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
10503
10504 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
10505 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
10506 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
10507 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
10508 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
10509 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
10510 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
10511 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
10512 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
10513 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
10514 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
10515 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
10516 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
10517 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
10518 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
10519 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
10520
10521 ;; All the other keys
10522 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
10523 (define-key org-mode-map "\C-c\C-j" 'org-goto)
10524 (define-key org-mode-map "\C-c\C-t" 'org-todo)
10525 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
10526 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
10527 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
10528 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
10529 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
10530 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
10531 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
10532 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
10533 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
10534 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
10535 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
10536 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
10537 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
10538 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
10539 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
10540 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
10541 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
10542 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
10543 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
10544 (define-key org-mode-map "\C-c]" 'org-remove-file)
10545 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
10546 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
10547 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
10548 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
10549 (define-key org-mode-map "\C-m" 'org-return)
10550 (define-key org-mode-map "\C-c?" 'org-table-current-column)
10551 (define-key org-mode-map "\C-c " 'org-table-blank-field)
10552 (define-key org-mode-map "\C-c+" 'org-table-sum)
10553 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
10554 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
10555 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
10556 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
10557 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
10558 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
10559 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
10560 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
10561 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
10562 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
10563 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
10564 ;; OPML support is only an option for the future
10565 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
10566 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
10567 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
10568 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
10569 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
10570 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
10571 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
10572 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
10573 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
10574 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
10575 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
10576
10577 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
10578 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
10579 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
10580
10581 (defsubst org-table-p () (org-at-table-p))
10582
10583 (defun org-self-insert-command (N)
10584 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10585 If the cursor is in a table looking at whitespace, the whitespace is
10586 overwritten, and the table is not marked as requiring realignment."
10587 (interactive "p")
10588 (if (and (org-table-p)
10589 (or
10590 (and org-table-auto-blank-field
10591 (member last-command
10592 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
10593 (org-table-blank-field))
10594 t)
10595 (eq N 1)
10596 (looking-at "[^|\n]* +|"))
10597 (let (org-table-may-need-update)
10598 (goto-char (1- (match-end 0)))
10599 (delete-backward-char 1)
10600 (goto-char (match-beginning 0))
10601 (self-insert-command N))
10602 (setq org-table-may-need-update t)
10603 (self-insert-command N)))
10604
10605 ;; FIXME:
10606 ;; The following two functions might still be optimized to trigger
10607 ;; re-alignment less frequently.
10608
10609 (defun org-delete-backward-char (N)
10610 "Like `delete-backward-char', insert whitespace at field end in tables.
10611 When deleting backwards, in tables this function will insert whitespace in
10612 front of the next \"|\" separator, to keep the table aligned. The table will
10613 still be marked for re-alignment, because a narrow field may lead to a
10614 reduced column width."
10615 (interactive "p")
10616 (if (and (org-table-p)
10617 (eq N 1)
10618 (string-match "|" (buffer-substring (point-at-bol) (point)))
10619 (looking-at ".*?|"))
10620 (let ((pos (point)))
10621 (backward-delete-char N)
10622 (skip-chars-forward "^|")
10623 (insert " ")
10624 (goto-char (1- pos)))
10625 (backward-delete-char N)))
10626
10627 (defun org-delete-char (N)
10628 "Like `delete-char', but insert whitespace at field end in tables.
10629 When deleting characters, in tables this function will insert whitespace in
10630 front of the next \"|\" separator, to keep the table aligned. The table
10631 will still be marked for re-alignment, because a narrow field may lead to
10632 a reduced column width."
10633 (interactive "p")
10634 (if (and (org-table-p)
10635 (not (bolp))
10636 (not (= (char-after) ?|))
10637 (eq N 1))
10638 (if (looking-at ".*?|")
10639 (let ((pos (point)))
10640 (replace-match (concat
10641 (substring (match-string 0) 1 -1)
10642 " |"))
10643 (goto-char pos)))
10644 (delete-char N)))
10645
10646 ;; How to do this: Measure non-white length of current string
10647 ;; If equal to column width, we should realign.
10648
10649 (defun org-remap (map &rest commands)
10650 "In MAP, remap the functions given in COMMANDS.
10651 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
10652 (let (new old)
10653 (while commands
10654 (setq old (pop commands) new (pop commands))
10655 (if (fboundp 'command-remapping)
10656 (define-key map (vector 'remap old) new)
10657 (substitute-key-definition old new map global-map)))))
10658
10659 (when (eq org-enable-table-editor 'optimized)
10660 ;; If the user wants maximum table support, we need to hijack
10661 ;; some standard editing functions
10662 (org-remap org-mode-map
10663 'self-insert-command 'org-self-insert-command
10664 'delete-char 'org-delete-char
10665 'delete-backward-char 'org-delete-backward-char)
10666 (define-key org-mode-map "|" 'org-force-self-insert))
10667
10668 (defun org-shiftcursor-error ()
10669 "Throw an error because Shift-Cursor command was applied in wrong context."
10670 (error "This command is active in special context like tables, headlines or timestamps"))
10671
10672 (defun org-shifttab ()
10673 "Global visibility cycling or move to previous table field.
10674 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
10675 See the individual commands for more information."
10676 (interactive)
10677 (cond
10678 ((org-at-table-p) (org-table-previous-field))
10679 (t (org-cycle '(4)))))
10680
10681 (defun org-shiftmetaleft ()
10682 "Promote subtree or delete table column.
10683 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
10684 See the individual commands for more information."
10685 (interactive)
10686 (cond
10687 ((org-at-table-p) (org-table-delete-column))
10688 ((org-on-heading-p) (org-promote-subtree))
10689 ((org-at-item-p) (call-interactively 'org-outdent-item))
10690 (t (org-shiftcursor-error))))
10691
10692 (defun org-shiftmetaright ()
10693 "Demote subtree or insert table column.
10694 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
10695 See the individual commands for more information."
10696 (interactive)
10697 (cond
10698 ((org-at-table-p) (org-table-insert-column))
10699 ((org-on-heading-p) (org-demote-subtree))
10700 ((org-at-item-p) (call-interactively 'org-indent-item))
10701 (t (org-shiftcursor-error))))
10702
10703 (defun org-shiftmetaup (&optional arg)
10704 "Move subtree up or kill table row.
10705 Calls `org-move-subtree-up' or `org-table-kill-row' or
10706 `org-move-item-up' depending on context. See the individual commands
10707 for more information."
10708 (interactive "P")
10709 (cond
10710 ((org-at-table-p) (org-table-kill-row))
10711 ((org-on-heading-p) (org-move-subtree-up arg))
10712 ((org-at-item-p) (org-move-item-up arg))
10713 (t (org-shiftcursor-error))))
10714 (defun org-shiftmetadown (&optional arg)
10715 "Move subtree down or insert table row.
10716 Calls `org-move-subtree-down' or `org-table-insert-row' or
10717 `org-move-item-down', depending on context. See the individual
10718 commands for more information."
10719 (interactive "P")
10720 (cond
10721 ((org-at-table-p) (org-table-insert-row arg))
10722 ((org-on-heading-p) (org-move-subtree-down arg))
10723 ((org-at-item-p) (org-move-item-down arg))
10724 (t (org-shiftcursor-error))))
10725
10726 (defun org-metaleft (&optional arg)
10727 "Promote heading or move table column to left.
10728 Calls `org-do-promote' or `org-table-move-column', depending on context.
10729 With no specific context, calls the Emacs default `backward-word'.
10730 See the individual commands for more information."
10731 (interactive "P")
10732 (cond
10733 ((org-at-table-p) (org-table-move-column 'left))
10734 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
10735 (t (backward-word (prefix-numeric-value arg)))))
10736
10737 (defun org-metaright (&optional arg)
10738 "Demote subtree or move table column to right.
10739 Calls `org-do-demote' or `org-table-move-column', depending on context.
10740 With no specific context, calls the Emacs default `forward-word'.
10741 See the individual commands for more information."
10742 (interactive "P")
10743 (cond
10744 ((org-at-table-p) (org-table-move-column nil))
10745 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
10746 (t (forward-word (prefix-numeric-value arg)))))
10747
10748 (defun org-metaup (&optional arg)
10749 "Move subtree up or move table row up.
10750 Calls `org-move-subtree-up' or `org-table-move-row' or
10751 `org-move-item-up', depending on context. See the individual commands
10752 for more information."
10753 (interactive "P")
10754 (cond
10755 ((org-at-table-p) (org-table-move-row 'up))
10756 ((org-on-heading-p) (org-move-subtree-up arg))
10757 ((org-at-item-p) (org-move-item-up arg))
10758 (t (org-shiftcursor-error))))
10759
10760 (defun org-metadown (&optional arg)
10761 "Move subtree down or move table row down.
10762 Calls `org-move-subtree-down' or `org-table-move-row' or
10763 `org-move-item-down', depending on context. See the individual
10764 commands for more information."
10765 (interactive "P")
10766 (cond
10767 ((org-at-table-p) (org-table-move-row nil))
10768 ((org-on-heading-p) (org-move-subtree-down arg))
10769 ((org-at-item-p) (org-move-item-down arg))
10770 (t (org-shiftcursor-error))))
10771
10772 (defun org-shiftup (&optional arg)
10773 "Increase item in timestamp or increase priority of current item.
10774 Calls `org-timestamp-up' or `org-priority-up', depending on context.
10775 See the individual commands for more information."
10776 (interactive "P")
10777 (cond
10778 ((org-at-timestamp-p) (org-timestamp-up arg))
10779 (t (org-priority-up))))
10780
10781 (defun org-shiftdown (&optional arg)
10782 "Decrease item in timestamp or decrease priority of current item.
10783 Calls `org-timestamp-down' or `org-priority-down', depending on context.
10784 See the individual commands for more information."
10785 (interactive "P")
10786 (cond
10787 ((org-at-timestamp-p) (org-timestamp-down arg))
10788 (t (org-priority-down))))
10789
10790 (defun org-shiftright ()
10791 "Next TODO keyword or timestamp one day later, depending on context."
10792 (interactive)
10793 (cond
10794 ((org-at-timestamp-p) (org-timestamp-up-day))
10795 ((org-on-heading-p) (org-todo 'right))
10796 (t (org-shiftcursor-error))))
10797
10798 (defun org-shiftleft ()
10799 "Previous TODO keyword or timestamp one day earlier, depending on context."
10800 (interactive)
10801 (cond
10802 ((org-at-timestamp-p) (org-timestamp-down-day))
10803 ((org-on-heading-p) (org-todo 'left))
10804 (t (org-shiftcursor-error))))
10805
10806 (defun org-copy-special ()
10807 "Copy region in table or copy current subtree.
10808 Calls `org-table-copy' or `org-copy-subtree', depending on context.
10809 See the individual commands for more information."
10810 (interactive)
10811 (call-interactively
10812 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
10813
10814 (defun org-cut-special ()
10815 "Cut region in table or cut current subtree.
10816 Calls `org-table-copy' or `org-cut-subtree', depending on context.
10817 See the individual commands for more information."
10818 (interactive)
10819 (call-interactively
10820 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
10821
10822 (defun org-paste-special (arg)
10823 "Paste rectangular region into table, or past subtree relative to level.
10824 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
10825 See the individual commands for more information."
10826 (interactive "P")
10827 (if (org-at-table-p)
10828 (org-table-paste-rectangle)
10829 (org-paste-subtree arg)))
10830
10831 (defun org-ctrl-c-ctrl-c (&optional arg)
10832 "Call realign table, or recognize a table.el table, or update keywords.
10833 When the cursor is inside a table created by the table.el package,
10834 activate that table. Otherwise, if the cursor is at a normal table
10835 created with org.el, re-align that table. This command works even if
10836 the automatic table editor has been turned off.
10837 If the cursor is in one of the special #+KEYWORD lines, this triggers
10838 scanning the buffer for these lines and updating the information.
10839 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
10840 (interactive "P")
10841 (let ((org-enable-table-editor t))
10842 (cond
10843 ((org-at-table.el-p)
10844 (require 'table)
10845 (beginning-of-line 1)
10846 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
10847 (table-recognize-table))
10848 ((org-at-table-p)
10849 (org-table-maybe-eval-formula)
10850 (if arg
10851 (org-table-recalculate t)
10852 (org-table-maybe-recalculate-line))
10853 (org-table-align))
10854 ((org-at-item-p)
10855 (org-renumber-ordered-list (prefix-numeric-value arg)))
10856 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
10857 (cond
10858 ((equal (match-string 1) "TBLFM")
10859 ;; Recalculate the table before this line
10860 (save-excursion
10861 (beginning-of-line 1)
10862 (skip-chars-backward " \r\n\t")
10863 (if (org-at-table-p) (org-table-recalculate t))))
10864 (t
10865 (org-mode-restart))))
10866 ((org-region-active-p)
10867 (org-table-convert-region (region-beginning) (region-end) arg))
10868 ((condition-case nil
10869 (and (region-beginning) (region-end))
10870 (error nil))
10871 (if (y-or-n-p "Convert inactive region to table? ")
10872 (org-table-convert-region (region-beginning) (region-end) arg)
10873 (error "Abort")))
10874 (t (error "C-c C-c can do nothing useful at this location.")))))
10875
10876 (defun org-mode-restart ()
10877 "Restart Org-mode, to scan again for special lines.
10878 Also updates the keyword regular expressions."
10879 (interactive)
10880 (let ((org-inhibit-startup t)) (org-mode))
10881 (message "Org-mode restarted to refresh keyword and special line setup"))
10882
10883 (defun org-return ()
10884 "Goto next table row or insert a newline.
10885 Calls `org-table-next-row' or `newline', depending on context.
10886 See the individual commands for more information."
10887 (interactive)
10888 (cond
10889 ((org-at-table-p)
10890 (org-table-justify-field-maybe)
10891 (org-table-next-row))
10892 (t (newline))))
10893
10894 (defun org-meta-return (&optional arg)
10895 "Insert a new heading or wrap a region in a table.
10896 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
10897 See the individual commands for more information."
10898 (interactive "P")
10899 (cond
10900 ((org-at-table-p)
10901 (org-table-wrap-region arg))
10902 (t (org-insert-heading))))
10903
10904 ;;; Menu entries
10905
10906 ;; Define the Org-mode menus
10907 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
10908 '("Tbl"
10909 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
10910 ["Next Field" org-cycle (org-at-table-p)]
10911 ["Previous Field" org-shifttab (org-at-table-p)]
10912 ["Next Row" org-return (org-at-table-p)]
10913 "--"
10914 ["Blank Field" org-table-blank-field (org-at-table-p)]
10915 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
10916 "--"
10917 ("Column"
10918 ["Move Column Left" org-metaleft (org-at-table-p)]
10919 ["Move Column Right" org-metaright (org-at-table-p)]
10920 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
10921 ["Insert Column" org-shiftmetaright (org-at-table-p)])
10922 ("Row"
10923 ["Move Row Up" org-metaup (org-at-table-p)]
10924 ["Move Row Down" org-metadown (org-at-table-p)]
10925 ["Delete Row" org-shiftmetaup (org-at-table-p)]
10926 ["Insert Row" org-shiftmetadown (org-at-table-p)]
10927 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
10928 "--"
10929 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
10930 ("Rectangle"
10931 ["Copy Rectangle" org-copy-special (org-at-table-p)]
10932 ["Cut Rectangle" org-cut-special (org-at-table-p)]
10933 ["Paste Rectangle" org-paste-special (org-at-table-p)]
10934 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
10935 "--"
10936 ("Calculate"
10937 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
10938 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10939 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
10940 "--"
10941 ["Recalculate line" org-table-recalculate (org-at-table-p)]
10942 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
10943 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
10944 "--"
10945 ["Sum Column/Rectangle" org-table-sum
10946 (or (org-at-table-p) (org-region-active-p))]
10947 ["Which Column?" org-table-current-column (org-at-table-p)])
10948 ["Debug Formulas"
10949 (setq org-table-formula-debug (not org-table-formula-debug))
10950 :style toggle :selected org-table-formula-debug]
10951 "--"
10952 ["Invisible Vlines" org-table-toggle-vline-visibility
10953 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
10954 "--"
10955 ["Create" org-table-create (and (not (org-at-table-p))
10956 org-enable-table-editor)]
10957 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
10958 ["Import from File" org-table-import (not (org-at-table-p))]
10959 ["Export to File" org-table-export (org-at-table-p)]
10960 "--"
10961 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
10962
10963 (easy-menu-define org-org-menu org-mode-map "Org menu"
10964 '("Org"
10965 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
10966 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
10967 ["Sparse Tree" org-occur t]
10968 ["Show All" show-all t]
10969 "--"
10970 ["New Heading" org-insert-heading t]
10971 ("Navigate Headings"
10972 ["Up" outline-up-heading t]
10973 ["Next" outline-next-visible-heading t]
10974 ["Previous" outline-previous-visible-heading t]
10975 ["Next Same Level" outline-forward-same-level t]
10976 ["Previous Same Level" outline-backward-same-level t]
10977 "--"
10978 ["Jump" org-goto t])
10979 ("Edit Structure"
10980 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
10981 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
10982 "--"
10983 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
10984 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
10985 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
10986 "--"
10987 ["Promote Heading" org-metaleft (not (org-at-table-p))]
10988 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
10989 ["Demote Heading" org-metaright (not (org-at-table-p))]
10990 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
10991 "--"
10992 ["Archive Subtree" org-archive-subtree t])
10993 "--"
10994 ("TODO Lists"
10995 ["TODO/DONE/-" org-todo t]
10996 ["Show TODO Tree" org-show-todo-tree t]
10997 ["Global TODO list" org-todo-list t]
10998 "--"
10999 ["Set Priority" org-priority t]
11000 ["Priority Up" org-shiftup t]
11001 ["Priority Down" org-shiftdown t])
11002 ("Dates and Scheduling"
11003 ["Timestamp" org-time-stamp t]
11004 ["Timestamp (inactive)" org-time-stamp-inactive t]
11005 ("Change Date"
11006 ["1 Day Later" org-timestamp-up-day t]
11007 ["1 Day Earlier" org-timestamp-down-day t]
11008 ["1 ... Later" org-shiftup t]
11009 ["1 ... Earlier" org-shiftdown t])
11010 ["Compute Time Range" org-evaluate-time-range t]
11011 ["Schedule Item" org-schedule t]
11012 ["Deadline" org-deadline t]
11013 "--"
11014 ["Goto Calendar" org-goto-calendar t]
11015 ["Date from Calendar" org-date-from-calendar t])
11016 "--"
11017 ("Timeline/Agenda"
11018 ["Show TODO Tree this File" org-show-todo-tree t]
11019 ["Check Deadlines this File" org-check-deadlines t]
11020 ["Timeline Current File" org-timeline t]
11021 "--"
11022 ["Agenda" org-agenda t])
11023 ("File List for Agenda")
11024 "--"
11025 ("Hyperlinks"
11026 ["Store Link (Global)" org-store-link t]
11027 ["Insert Link" org-insert-link t]
11028 ["Follow Link" org-open-at-point t])
11029 "--"
11030 ("Export"
11031 ["ASCII" org-export-as-ascii t]
11032 ["Extract Visible Text" org-export-copy-visible t]
11033 ["HTML" org-export-as-html t]
11034 ["HTML and Open" org-export-as-html-and-open t]
11035 ; ["OPML" org-export-as-opml nil]
11036 "--"
11037 ["iCalendar this file" org-export-icalendar-this-file t]
11038 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11039 :active t :keys "C-c C-x C-i"]
11040 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11041 "--"
11042 ["Option Template" org-insert-export-options-template t]
11043 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11044 "--"
11045 ("Documentation"
11046 ["Show Version" org-version t]
11047 ["Info Documentation" org-info t])
11048 ("Customize"
11049 ["Browse Org Group" org-customize t]
11050 "--"
11051 ["Build Full Customize Menu" org-create-customize-menu
11052 (fboundp 'customize-menu-create)])
11053 "--"
11054 ["Refresh setup" org-mode-restart t]
11055 ))
11056
11057 (defun org-info (&optional node)
11058 "Read documentation for Org-mode in the info system.
11059 With optional NODE, go directly to that node."
11060 (interactive)
11061 (require 'info)
11062 (Info-goto-node (format "(org)%s" (or node ""))))
11063
11064 (defun org-install-agenda-files-menu ()
11065 (easy-menu-change
11066 '("Org") "File List for Agenda"
11067 (append
11068 (list
11069 ["Edit File List" (customize-variable 'org-agenda-files) t]
11070 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11071 ["Remove Current File from List" org-remove-file t]
11072 ["Cycle through agenda files" org-cycle-agenda-files t]
11073 "--")
11074 (mapcar 'org-file-menu-entry org-agenda-files))))
11075
11076 ;;; Documentation
11077
11078 (defun org-customize ()
11079 "Call the customize function with org as argument."
11080 (interactive)
11081 (customize-browse 'org))
11082
11083 (defun org-create-customize-menu ()
11084 "Create a full customization menu for Org-mode, insert it into the menu."
11085 (interactive)
11086 (if (fboundp 'customize-menu-create)
11087 (progn
11088 (easy-menu-change
11089 '("Org") "Customize"
11090 `(["Browse Org group" org-customize t]
11091 "--"
11092 ,(customize-menu-create 'org)
11093 ["Set" Custom-set t]
11094 ["Save" Custom-save t]
11095 ["Reset to Current" Custom-reset-current t]
11096 ["Reset to Saved" Custom-reset-saved t]
11097 ["Reset to Standard Settings" Custom-reset-standard t]))
11098 (message "\"Org\"-menu now contains full customization menu"))
11099 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11100
11101 ;;; Miscellaneous stuff
11102
11103 (defun org-move-line-down (arg)
11104 "Move the current line down. With prefix argument, move it past ARG lines."
11105 (interactive "p")
11106 (let ((col (current-column))
11107 beg end pos)
11108 (beginning-of-line 1) (setq beg (point))
11109 (beginning-of-line 2) (setq end (point))
11110 (beginning-of-line (+ 1 arg))
11111 (setq pos (move-marker (make-marker) (point)))
11112 (insert (delete-and-extract-region beg end))
11113 (goto-char pos)
11114 (move-to-column col)))
11115
11116 (defun org-move-line-up (arg)
11117 "Move the current line up. With prefix argument, move it past ARG lines."
11118 (interactive "p")
11119 (let ((col (current-column))
11120 beg end pos)
11121 (beginning-of-line 1) (setq beg (point))
11122 (beginning-of-line 2) (setq end (point))
11123 (beginning-of-line (- arg))
11124 (setq pos (move-marker (make-marker) (point)))
11125 (insert (delete-and-extract-region beg end))
11126 (goto-char pos)
11127 (move-to-column col)))
11128
11129 ;; Paragraph filling stuff.
11130 ;; We want this to be just right, so use the full arsenal.
11131 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11132 ;; filladapt package works slightly differently.
11133
11134 (defun org-set-autofill-regexps ()
11135 (interactive)
11136 ;; In the paragraph separator we include headlines, because filling
11137 ;; text in a line directly attached to a headline would otherwise
11138 ;; fill the headline as well.
11139 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11140 ;; The paragraph starter includes hand-formatted lists.
11141 (set (make-local-variable 'paragraph-start)
11142 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11143 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11144 ;; But only if the user has not turned off tables or fixed-width regions
11145 (set (make-local-variable 'auto-fill-inhibit-regexp)
11146 (concat "\\*\\|#"
11147 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11148 (concat
11149 "\\|[ \t]*["
11150 (if org-enable-table-editor "|" "")
11151 (if org-enable-fixed-width-editor ":" "")
11152 "]"))))
11153 ;; We use our own fill-paragraph function, to make sure that tables
11154 ;; and fixed-width regions are not wrapped. That function will pass
11155 ;; through to `fill-paragraph' when appropriate.
11156 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11157 ;; Adaptive filling: To get full control, first make sure that
11158 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11159 (setq adaptive-fill-regexp "\000")
11160 (setq adaptive-fill-function 'org-adaptive-fill-function))
11161
11162 (defun org-fill-paragraph (&optional justify)
11163 "Re-align a table, pass through to fill-paragraph if no table."
11164 (let ((table-p (org-at-table-p))
11165 (table.el-p (org-at-table.el-p)))
11166 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11167 (table.el-p t) ; skip table.el tables
11168 (table-p (org-table-align) t) ; align org-mode tables
11169 (t nil)))) ; call paragraph-fill
11170
11171 ;; For reference, this is the default value of adaptive-fill-regexp
11172 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11173
11174 (defun org-adaptive-fill-function ()
11175 "Return a fill prefix for org-mode files.
11176 In particular, this makes sure hanging paragraphs for hand-formatted lists
11177 work correctly."
11178 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11179 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11180
11181 ;; Functions needed for Emacs/XEmacs region compatibility
11182
11183 (defun org-region-active-p ()
11184 "Is `transient-mark-mode' on and the region active?
11185 Works on both Emacs and XEmacs."
11186 (if org-ignore-region
11187 nil
11188 (if org-xemacs-p
11189 (and zmacs-regions (region-active-p))
11190 (and transient-mark-mode mark-active))))
11191
11192 (defun org-add-to-invisibility-spec (arg)
11193 "Add elements to `buffer-invisibility-spec'.
11194 See documentation for `buffer-invisibility-spec' for the kind of elements
11195 that can be added."
11196 (cond
11197 ((fboundp 'add-to-invisibility-spec)
11198 (add-to-invisibility-spec arg))
11199 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11200 (setq buffer-invisibility-spec (list arg)))
11201 (t
11202 (setq buffer-invisibility-spec
11203 (cons arg buffer-invisibility-spec)))))
11204
11205 (defun org-remove-from-invisibility-spec (arg)
11206 "Remove elements from `buffer-invisibility-spec'."
11207 (if (fboundp 'remove-from-invisibility-spec)
11208 (remove-from-invisibility-spec arg)
11209 (if (consp buffer-invisibility-spec)
11210 (setq buffer-invisibility-spec
11211 (delete arg buffer-invisibility-spec)))))
11212
11213 (defun org-in-invisibility-spec-p (arg)
11214 "Is ARG a member of `buffer-invisibility-spec'?."
11215 (if (consp buffer-invisibility-spec)
11216 (member arg buffer-invisibility-spec)
11217 nil))
11218
11219 (defun org-image-file-name-regexp ()
11220 "Return regexp matching the file names of images."
11221 (if (fboundp 'image-file-name-regexp)
11222 (image-file-name-regexp)
11223 (let ((image-file-name-extensions
11224 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11225 "xbm" "xpm" "pbm" "pgm" "ppm")))
11226 (concat "\\."
11227 (regexp-opt (nconc (mapcar 'upcase
11228 image-file-name-extensions)
11229 image-file-name-extensions)
11230 t)
11231 "\\'"))))
11232
11233 ;; Functions needed for compatibility with old outline.el
11234
11235 ;; The following functions capture almost the entire compatibility code
11236 ;; between the different versions of outline-mode. The only other place
11237 ;; where this is important are the font-lock-keywords. Search for
11238 ;; `org-noutline-p' to find it.
11239
11240 ;; C-a should go to the beginning of a *visible* line, also in the
11241 ;; new outline.el. I guess this should be patched into Emacs?
11242 (defun org-beginning-of-line ()
11243 "Go to the beginning of the current line. If that is invisible, continue
11244 to a visible line beginning. This makes the function of C-a more intuitive."
11245 (interactive)
11246 (beginning-of-line 1)
11247 (if (bobp)
11248 nil
11249 (backward-char 1)
11250 (if (org-invisible-p)
11251 (while (and (not (bobp)) (org-invisible-p))
11252 (backward-char 1)
11253 (beginning-of-line 1))
11254 (forward-char 1))))
11255 (when org-noutline-p
11256 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11257
11258 (defun org-invisible-p ()
11259 "Check if point is at a character currently not visible."
11260 (if org-noutline-p
11261 ;; Early versions of noutline don't have `outline-invisible-p'.
11262 (if (fboundp 'outline-invisible-p)
11263 (outline-invisible-p)
11264 (get-char-property (point) 'invisible))
11265 (save-excursion
11266 (skip-chars-backward "^\r\n")
11267 (equal (char-before) ?\r))))
11268
11269 (defun org-back-to-heading (&optional invisible-ok)
11270 "Move to previous heading line, or beg of this line if it's a heading.
11271 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11272 (if org-noutline-p
11273 (outline-back-to-heading invisible-ok)
11274 (if (looking-at outline-regexp)
11275 t
11276 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11277 outline-regexp)
11278 nil t)
11279 (if invisible-ok
11280 (progn (goto-char (match-end 1))
11281 (looking-at outline-regexp)))
11282 (error "Before first heading")))))
11283
11284 (defun org-on-heading-p (&optional invisible-ok)
11285 "Return t if point is on a (visible) heading line.
11286 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
11287 (if org-noutline-p
11288 (outline-on-heading-p 'invisible-ok)
11289 (save-excursion
11290 (skip-chars-backward "^\n\r")
11291 (and (looking-at outline-regexp)
11292 (or invisible-ok
11293 (bobp)
11294 (equal (char-before) ?\n))))))
11295
11296 (defun org-up-heading-all (arg)
11297 "Move to the heading line of which the present line is a subheading.
11298 This function considers both visible and invisible heading lines.
11299 With argument, move up ARG levels."
11300 (if org-noutline-p
11301 (if (fboundp 'outline-up-heading-all)
11302 (outline-up-heading-all arg) ; emacs 21 version of outline.el
11303 (outline-up-heading arg t)) ; emacs 22 version of outline.el
11304 (org-back-to-heading t)
11305 (looking-at outline-regexp)
11306 (if (<= (- (match-end 0) (match-beginning 0)) arg)
11307 (error "Cannot move up %d levels" arg)
11308 (re-search-backward
11309 (concat "[\n\r]" (regexp-quote
11310 (make-string (- (match-end 0) (match-beginning 0) arg)
11311 ?*))
11312 "[^*]"))
11313 (forward-char 1))))
11314
11315 (defun org-show-hidden-entry ()
11316 "Show an entry where even the heading is hidden."
11317 (save-excursion
11318 (if (not org-noutline-p)
11319 (progn
11320 (org-back-to-heading t)
11321 (org-flag-heading nil)))
11322 (org-show-entry)))
11323
11324 (defun org-check-occur-regexp (regexp)
11325 "If REGEXP starts with \"^\", modify it to check for \\r as well.
11326 Of course, only for the old outline mode."
11327 (if org-noutline-p
11328 regexp
11329 (if (string-match "^\\^" regexp)
11330 (concat "[\n\r]" (substring regexp 1))
11331 regexp)))
11332
11333 (defun org-flag-heading (flag &optional entry)
11334 "Flag the current heading. FLAG non-nil means make invisible.
11335 When ENTRY is non-nil, show the entire entry."
11336 (save-excursion
11337 (org-back-to-heading t)
11338 (if (not org-noutline-p)
11339 ;; Make the current headline visible
11340 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
11341 ;; Check if we should show the entire entry
11342 (if entry
11343 (progn
11344 (org-show-entry)
11345 (save-excursion ;; FIXME: Is this the fix for points in the -|
11346 ;; middle of text? |
11347 (and (outline-next-heading) ;; |
11348 (org-flag-heading nil)))) ; show the next heading _|
11349 (outline-flag-region (max 1 (1- (point)))
11350 (save-excursion (outline-end-of-heading) (point))
11351 (if org-noutline-p
11352 flag
11353 (if flag ?\r ?\n))))))
11354
11355 (defun org-show-subtree ()
11356 "Show everything after this heading at deeper levels."
11357 (outline-flag-region
11358 (point)
11359 (save-excursion
11360 (outline-end-of-subtree) (outline-next-heading) (point))
11361 (if org-noutline-p nil ?\n)))
11362
11363 (defun org-show-entry ()
11364 "Show the body directly following this heading.
11365 Show the heading too, if it is currently invisible."
11366 (interactive)
11367 (save-excursion
11368 (org-back-to-heading t)
11369 (outline-flag-region
11370 (1- (point))
11371 (save-excursion
11372 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
11373 (or (match-beginning 1) (point-max)))
11374 (if org-noutline-p nil ?\n))))
11375
11376
11377 (defun org-make-options-regexp (kwds)
11378 "Make a regular expression for keyword lines."
11379 (concat
11380 (if org-noutline-p "^" "[\n\r]")
11381 "#?[ \t]*\\+\\("
11382 (mapconcat 'regexp-quote kwds "\\|")
11383 "\\):[ \t]*"
11384 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
11385
11386 ;; Make `bookmark-jump' show the jump location if it was hidden.
11387 (eval-after-load "bookmark"
11388 '(if (boundp 'bookmark-after-jump-hook)
11389 ;; We can use the hook
11390 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
11391 ;; Hook not available, use advice
11392 (defadvice bookmark-jump (after org-make-visible activate)
11393 "Make the position visible."
11394 (org-bookmark-jump-unhide))))
11395
11396 (defun org-bookmark-jump-unhide ()
11397 "Unhide the current position, to show the bookmark location."
11398 (and (eq major-mode 'org-mode)
11399 (or (org-invisible-p)
11400 (save-excursion (goto-char (max (point-min) (1- (point))))
11401 (org-invisible-p)))
11402 (org-show-hierarchy-above)))
11403
11404 ;;; Finish up
11405
11406 (provide 'org)
11407
11408 (run-hooks 'org-load-hook)
11409
11410 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
11411 ;;; org.el ends here
11412