]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-end-of-subtree): New function.
[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, 2006 Free Software Foundation
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.02
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
81 ;;
82 ;; Changes since version 4.00:
83 ;; ---------------------------
84 ;; Version 4.02
85 ;; - Minor bug fixes and improvements around tag searches.
86 ;; - XEmacs compatibility fixes.
87 ;;
88 ;; Version 4.01
89 ;; - Tags can also be set remotely from agenda buffer.
90 ;; - Boolean logic for tag searches.
91 ;; - Additional agenda commands can be configured through the variable
92 ;; `org-agenda-custom-commands'.
93 ;; - Minor bug fixes.
94 ;;
95 ;;; Code:
96
97 (eval-when-compile (require 'cl) (require 'calendar))
98 (require 'outline)
99 (require 'time-date)
100 (require 'easymenu)
101
102 (defvar calc-embedded-close-formula)
103 (defvar calc-embedded-open-formula)
104 (defvar font-lock-unfontify-region-function)
105
106 ;;; Customization variables
107
108 (defvar org-version "4.01"
109 "The version number of the file org.el.")
110 (defun org-version ()
111 (interactive)
112 (message "Org-mode version %s" org-version))
113
114 ;; The following two constants are for compatibility with different Emacs
115 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
116 ;; The compatibility code in org.el is based on these two constants.
117 (defconst org-xemacs-p (featurep 'xemacs)
118 "Are we running xemacs?")
119 (defconst org-noutline-p (featurep 'noutline)
120 "Are we using the new outline mode?")
121
122 (defgroup org nil
123 "Outline-based notes management and organizer "
124 :tag "Org"
125 :group 'outlines
126 :group 'hypermedia
127 :group 'calendar)
128
129 (defgroup org-startup nil
130 "Options concerning startup of Org-mode."
131 :tag "Org Startup"
132 :group 'org)
133
134 (defcustom org-CUA-compatible nil
135 "Non-nil means use alternative key bindings for S-<cursor movement>.
136 Org-mode used S-<cursor movement> for changing timestamps and priorities.
137 S-<cursor movement> is also used for example by `CUA-mode' to select text.
138 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
139 alternative bindings. Setting this variable to t will replace the following
140 keys both in Org-mode and in the Org-agenda buffer.
141
142 S-RET -> C-S-RET
143 S-up -> M-p
144 S-down -> M-n
145 S-left -> M--
146 S-right -> M-+
147
148 If you do not like the alternative keys, take a look at the variable
149 `org-disputed-keys'.
150
151 This option is only relevant at load-time of Org-mode. Changing it requires
152 a restart of Emacs to become effective."
153 :group 'org-startup
154 :type 'boolean)
155
156 (defvar org-disputed-keys
157 '((S-up [(shift up)] [(meta ?p)])
158 (S-down [(shift down)] [(meta ?n)])
159 (S-left [(shift left)] [(meta ?-)])
160 (S-right [(shift right)] [(meta ?+)])
161 (S-return [(shift return)] [(control shift return)]))
162 "Keys for which Org-mode and other modes compete.
163 This is an alist, cars are symbols for lookup, 1st element is the default key,
164 second element will be used when `org-CUA-compatible' is t.")
165
166 (defun org-key (key)
167 "Select a key according to `org-CUA-compatible'."
168 (nth (if org-CUA-compatible 2 1)
169 (or (assq key org-disputed-keys)
170 (error "Invalid Key %s in `org-key'" key))))
171
172 (defcustom org-startup-folded t
173 "Non-nil means, entering Org-mode will switch to OVERVIEW.
174 This can also be configured on a per-file basis by adding one of
175 the following lines anywhere in the buffer:
176
177 #+STARTUP: fold
178 #+STARTUP: nofold
179 #+STARTUP: content"
180 :group 'org-startup
181 :type '(choice
182 (const :tag "nofold: show all" nil)
183 (const :tag "fold: overview" t)
184 (const :tag "content: all headlines" content)))
185
186 (defcustom org-startup-truncated t
187 "Non-nil means, entering Org-mode will set `truncate-lines'.
188 This is useful since some lines containing links can be very long and
189 uninteresting. Also tables look terrible when wrapped."
190 :group 'org-startup
191 :type 'boolean)
192
193 (defcustom org-startup-with-deadline-check nil
194 "Non-nil means, entering Org-mode will run the deadline check.
195 This means, if you start editing an org file, you will get an
196 immediate reminder of any due deadlines.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
199
200 #+STARTUP: dlcheck
201 #+STARTUP: nodlcheck"
202 :group 'org-startup
203 :type 'boolean)
204
205 (defcustom org-insert-mode-line-in-empty-file nil
206 "Non-nil means insert the first line setting Org-mode in empty files.
207 When the function `org-mode' is called interactively in an empty file, this
208 normally means that the file name does not automatically trigger Org-mode.
209 To ensure that the file will always be in Org-mode in the future, a
210 line enforcing Org-mode will be inserted into the buffer, if this option
211 has been set."
212 :group 'org-startup
213 :type 'boolean)
214
215 (defgroup org-keywords nil
216 "Options concerning TODO items in Org-mode."
217 :tag "Org Keywords"
218 :group 'org)
219
220 (defcustom org-todo-keywords '("TODO" "DONE")
221 "List of TODO entry keywords.
222 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
223 considered to mean that the entry is \"done\". All the other mean that
224 action is required, and will make the entry show up in todo lists, diaries
225 etc.
226 The command \\[org-todo] cycles an entry through these states, and an
227 additional state where no keyword is present. For details about this
228 cycling, see also the variable `org-todo-interpretation'
229 Changes become only effective after restarting Emacs."
230 :group 'org-keywords
231 :type '(repeat (string :tag "Keyword")))
232
233 (defcustom org-todo-interpretation 'sequence
234 "Controls how TODO keywords are interpreted.
235 \\<org-mode-map>Possible values are `sequence' and `type'.
236 This variable is only relevant if `org-todo-keywords' contains more than two
237 states. There are two ways how these keywords can be used:
238
239 - As a sequence in the process of working on a TODO item, for example
240 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
241 org-todo-interpretation 'sequence)
242
243 - As different types of TODO items, for example
244 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
245 org-todo-interpretation 'type)
246
247 When the states are interpreted as a sequence, \\[org-todo] always cycles
248 to the next state, in order to walk through all different states. So with
249 \\[org-todo], you turn an empty entry into the state TODO. When you started
250 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
251 later to VERIFY and finally to DONE.
252
253 When the states are interpreted as types, \\[org-todo] still cycles through
254 when it is called several times in direct succession, in order to initially
255 select the type. However, if not called immediately after a previous
256 \\[org-todo], it switches from each type directly to DONE. So with the
257 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
258 RELAXED. If you later return to this entry and press \\[org-todo] again,
259 RELAXED will not be changed REMIND, but directly to DONE.
260
261 You can create a large number of types. To initially select a
262 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
263 type with completion. Of course, you can also type the keyword
264 directly into the buffer. M-TAB completes TODO keywords at the
265 beginning of a headline."
266 :group 'org-keywords
267 :type '(choice (const sequence)
268 (const type)))
269
270 (defcustom org-default-priority ?B
271 "The default priority of TODO items.
272 This is the priority an item get if no explicit priority is given."
273 :group 'org-keywords
274 :type 'character)
275
276 (defcustom org-lowest-priority ?C
277 "The lowest priority of TODO items. A character like ?A, ?B etc."
278 :group 'org-keywords
279 :type 'character)
280
281 (defcustom org-deadline-string "DEADLINE:"
282 "String to mark deadline entries.
283 A deadline is this string, followed by a time stamp. Should be a word,
284 terminated by a colon. You can insert a schedule keyword and
285 a timestamp with \\[org-deadline].
286 Changes become only effective after restarting Emacs."
287 :group 'org-keywords
288 :type 'string)
289
290 (defcustom org-scheduled-string "SCHEDULED:"
291 "String to mark scheduled TODO entries.
292 A schedule is this string, followed by a time stamp. Should be a word,
293 terminated by a colon. You can insert a schedule keyword and
294 a timestamp with \\[org-schedule].
295 Changes become only effective after restarting Emacs."
296 :group 'org-keywords
297 :type 'string)
298
299 (defcustom org-closed-string "CLOSED:"
300 "String ued as the prefix for timestamps logging closing a TODO entry."
301 :group 'org-keywords
302 :type 'string)
303
304 (defcustom org-comment-string "COMMENT"
305 "Entries starting with this keyword will never be exported.
306 An entry can be toggled between COMMENT and normal with
307 \\[org-toggle-comment].
308 Changes become only effective after restarting Emacs."
309 :group 'org-keywords
310 :type 'string)
311
312 (defcustom org-quote-string "QUOTE"
313 "Entries starting with this keyword will be exported in fixed-width font.
314 Quoting applies only to the text in the entry following the headline, and does
315 not extend beyond the next headline, even if that is lower level.
316 An entry can be toggled between QUOTE and normal with
317 \\[org-toggle-fixed-width-section]"
318 :group 'org-keywords
319 :type 'string)
320
321 (defcustom org-after-todo-state-change-hook nil
322 "Hook which is run after the state of a TODO item was changed.
323 The new state (a string with a todo keyword, or nil) is available in the
324 Lisp variable `state'."
325 :group 'org-keywords
326 :type 'hook)
327
328 ;; Variables for pre-computed regular expressions, all buffer local
329 (defvar org-todo-kwd-priority-p nil
330 "Do TODO items have priorities?")
331 (make-variable-buffer-local 'org-todo-kwd-priority-p)
332 (defvar org-todo-kwd-max-priority nil
333 "Maximum priority of TODO items.")
334 (make-variable-buffer-local 'org-todo-kwd-max-priority)
335 (defvar org-ds-keyword-length 12
336 "Maximum length of the Deadline and SCHEDULED keywords.")
337 (make-variable-buffer-local 'org-ds-keyword-length)
338 (defvar org-done-string nil
339 "The last string in `org-todo-keywords', indicating an item is DONE.")
340 (make-variable-buffer-local 'org-done-string)
341 (defvar org-todo-regexp nil
342 "Matches any of the TODO state keywords.")
343 (make-variable-buffer-local 'org-todo-regexp)
344 (defvar org-not-done-regexp nil
345 "Matches any of the TODO state keywords except the last one.")
346 (make-variable-buffer-local 'org-not-done-regexp)
347 (defvar org-todo-line-regexp nil
348 "Matches a headline and puts TODO state into group 2 if present.")
349 (make-variable-buffer-local 'org-todo-line-regexp)
350 (defvar org-nl-done-regexp nil
351 "Matches newline followed by a headline with the DONE keyword.")
352 (make-variable-buffer-local 'org-nl-done-regexp)
353 (defvar org-looking-at-done-regexp nil
354 "Matches the DONE keyword a point.")
355 (make-variable-buffer-local 'org-looking-at-done-regexp)
356 (defvar org-deadline-regexp nil
357 "Matches the DEADLINE keyword.")
358 (make-variable-buffer-local 'org-deadline-regexp)
359 (defvar org-deadline-time-regexp nil
360 "Matches the DEADLINE keyword together with a time stamp.")
361 (make-variable-buffer-local 'org-deadline-time-regexp)
362 (defvar org-deadline-line-regexp nil
363 "Matches the DEADLINE keyword and the rest of the line.")
364 (make-variable-buffer-local 'org-deadline-line-regexp)
365 (defvar org-scheduled-regexp nil
366 "Matches the SCHEDULED keyword.")
367 (make-variable-buffer-local 'org-scheduled-regexp)
368 (defvar org-scheduled-time-regexp nil
369 "Matches the SCHEDULED keyword together with a time stamp.")
370 (make-variable-buffer-local 'org-scheduled-time-regexp)
371
372 (defvar org-category nil
373 "Variable used by org files to set a category for agenda display.
374 Such files should use a file variable to set it, for example
375
376 -*- mode: org; org-category: \"ELisp\"
377
378 or contain a special line
379
380 #+CATEGORY: ELisp
381
382 If the file does not specify a category, then file's base name
383 is used instead.")
384 (make-variable-buffer-local 'org-category)
385
386 (defgroup org-time nil
387 "Options concerning time stamps and deadlines in Org-mode."
388 :tag "Org Time"
389 :group 'org)
390
391 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
392 "Formats for `format-time-string' which are used for time stamps.
393 It is not recommended to change this constant.")
394
395
396 (defcustom org-deadline-warning-days 30
397 "No. of days before expiration during which a deadline becomes active.
398 This variable governs the display in the org file."
399 :group 'org-time
400 :type 'number)
401
402 (defcustom org-popup-calendar-for-date-prompt t
403 "Non-nil means, pop up a calendar when prompting for a date.
404 In the calendar, the date can be selected with mouse-1. However, the
405 minibuffer will also be active, and you can simply enter the date as well.
406 When nil, only the minibuffer will be available."
407 :group 'org-time
408 :type 'number)
409
410 (defcustom org-calendar-follow-timestamp-change t
411 "Non-nil means, make the calendar window follow timestamp changes.
412 When a timestamp is modified and the calendar window is visible, it will be
413 moved to the new date."
414 :group 'org-time
415 :type 'boolean)
416
417 (defcustom org-log-done nil
418 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
419 When the state of an entry is changed from nothing to TODO, remove a previous
420 closing date."
421 :group 'org-time
422 :type 'boolean)
423
424 (defgroup org-agenda nil
425 "Options concerning agenda display Org-mode."
426 :tag "Org Agenda"
427 :group 'org)
428
429 (defcustom org-agenda-files nil
430 "A list of org files for agenda/diary display.
431 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
432 \\[org-remove-file]. You can also use customize to edit the list."
433 :group 'org-agenda
434 :type '(repeat file))
435
436 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
437 "Custom commands for the agenda.
438 These commands will be offered on the splash screen displayed by the
439 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
440
441 key The key (a single char as a string) to be associated with the command.
442 type The command type, any of the following symbols:
443 todo Entries with a specific TODO keyword, in all agenda files.
444 tags Tags match in all agenda files.
445 todo-tree Sparse tree of specific TODO keyword in *current* file.
446 tags-tree Sparse tree with all tags matches in *current* file.
447 occur-tree Occur sparse tree for current file.
448 match What to search for:
449 - a single keyword for TODO keyword searches
450 - a tags match expression for tags searches
451 - a regular expression for occur searches"
452 :group 'org-agenda
453 :type '(repeat
454 (list (string :tag "Key")
455 (choice :tag "Type"
456 (const :tag "Tags search in all agenda files" tags)
457 (const :tag "TODO keyword search in all agenda files" todo)
458 (const :tag "Tags sparse tree in current buffer" tags-tree)
459 (const :tag "TODO keyword tree in current buffer" todo-tree)
460 (const :tag "Occur tree in current buffer" occur-tree))
461 (string :tag "Match"))))
462
463 (defcustom org-select-timeline-window t
464 "Non-nil means, after creating a timeline, move cursor into Timeline window.
465 When nil, cursor will remain in the current window."
466 :group 'org-agenda
467 :type 'boolean)
468
469 (defcustom org-select-agenda-window t
470 "Non-nil means, after creating an agenda, move cursor into Agenda window.
471 When nil, cursor will remain in the current window."
472 :group 'org-agenda
473 :type 'boolean)
474
475 (defcustom org-fit-agenda-window t
476 "Non-nil means, change window size of agenda to fit content."
477 :group 'org-agenda
478 :type 'boolean)
479
480 (defcustom org-agenda-show-all-dates t
481 "Non-nil means, `org-agenda' shows every day in the selected range.
482 When nil, only the days which actually have entries are shown."
483 :group 'org-agenda
484 :type 'boolean)
485
486 ;; FIXME: First day of month works only for current month because it would
487 ;; require a variable ndays treatment.
488 (defcustom org-agenda-start-on-weekday 1
489 "Non-nil means, start the overview always on the specified weekday.
490 0 Denotes Sunday, 1 denotes Monday etc.
491 When nil, always start on the current day."
492 :group 'org-agenda
493 :type '(choice (const :tag "Today" nil)
494 (const :tag "First day of month" t)
495 (number :tag "Weekday No.")))
496
497 (defcustom org-agenda-ndays 7
498 "Number of days to include in overview display."
499 :group 'org-agenda
500 :type 'number)
501
502 (defcustom org-agenda-include-all-todo t
503 "Non-nil means, the agenda will always contain all TODO entries.
504 When nil, date-less entries will only be shown if `org-agenda' is called
505 with a prefix argument.
506 When non-nil, the TODO entries will be listed at the top of the agenda, before
507 the entries for specific days."
508 :group 'org-agenda
509 :type 'boolean)
510
511 (defcustom org-agenda-include-diary nil
512 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
513 :group 'org-agenda
514 :type 'boolean)
515
516 (defcustom org-calendar-to-agenda-key [?c]
517 "The key to be installed in `calendar-mode-map' for switching to the agenda.
518 The command `org-calendar-goto-agenda' will be bound to this key. The
519 default is the character `c' because then`c' can be used to switch back and
520 force between agenda and calendar."
521 :group 'org-agenda
522 :type 'sexp)
523
524 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
525 "Sorting structure for the agenda items of a single day.
526 This is a list of symbols which will be used in sequence to determine
527 if an entry should be listed before another entry. The following
528 symbols are recognized.
529
530 time-up Put entries with time-of-day indications first, early first
531 time-down Put entries with time-of-day indications first, late first
532 category-keep Keep the default order of categories, corresponding to the
533 sequence in `org-agenda-files'.
534 category-up Sort alphabetically by category, A-Z.
535 category-down Sort alphabetically by category, Z-A.
536 priority-up Sort numerically by priority, high priority last.
537 priority-down Sort numerically by priority, high priority first.
538
539 The different possibilities will be tried in sequence, and testing stops
540 if one comparison returns a \"not-equal\". For example, the default
541 '(time-up category-keep priority-down)
542 means: Pull out all entries having a specified time of day and sort them,
543 in order to make a time schedule for the current day the first thing in the
544 agenda listing for the day. Of the entries without a time indication, keep
545 the grouped in categories, don't sort the categories, but keep them in
546 the sequence given in `org-agenda-files'. Within each category sort by
547 priority.
548
549 Leaving out `category-keep' would mean that items will be sorted across
550 categories by priority."
551 :group 'org-agenda
552 :type '(repeat
553 (choice
554 (const time-up)
555 (const time-down)
556 (const category-keep)
557 (const category-up)
558 (const category-down)
559 (const priority-up)
560 (const priority-down))))
561
562 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
563 "Format specification for the prefix of items in the agenda buffer.
564 This format works similar to a printf format, with the following meaning:
565
566 %c the category of the item, \"Diary\" for entries from the diary, or
567 as given by the CATEGORY keyword or derived from the file name.
568 %t the time-of-day specification if one applies to the entry, in the
569 format HH:MM
570 %s Scheduling/Deadline information, a short string
571
572 All specifiers work basically like the standard `%s' of printf, but may
573 contain two additional characters: A question mark just after the `%' and
574 a whitespace/punctuation character just before the final letter.
575
576 If the first character after `%' is a question mark, the entire field
577 will only be included if the corresponding value applies to the
578 current entry. This is useful for fields which should have fixed
579 width when present, but zero width when absent. For example,
580 \"%?-12t\" will result in a 12 character time field if a time of the
581 day is specified, but will completely disappear in entries which do
582 not contain a time.
583
584 If there is punctuation or whitespace character just before the final
585 format letter, this character will be appended to the field value if
586 the value is not empty. For example, the format \"%-12:c\" leads to
587 \"Diary: \" if the category is \"Diary\". If the category were be
588 empty, no additional colon would be interted.
589
590 The default value of this option is \" %-12:c%?-12t% s\", meaning:
591 - Indent the line with two space characters
592 - Give the category in a 12 chars wide field, padded with whitespace on
593 the right (because of `-'). Append a colon if there is a category
594 (because of `:').
595 - If there is a time-of-day, put it into a 12 chars wide field. If no
596 time, don't put in an empty field, just skip it (because of '?').
597 - Finally, put the scheduling information and append a whitespace.
598
599 As another example, if you don't want the time-of-day of entries in
600 the prefix, you could use:
601
602 (setq org-agenda-prefix-format \" %-11:c% s\")
603
604 See also the variable `org-agenda-remove-times-when-in-prefix'."
605 :type 'string
606 :group 'org-agenda)
607
608 (defcustom org-timeline-prefix-format " % s"
609 "Like `org-agenda-prefix-format', but for the timeline of a single file."
610 :type 'string
611 :group 'org-agenda)
612
613 (defvar org-prefix-format-compiled nil
614 "The compiled version of the most recently used prefix format.
615 Depending on which command was used last, this may be the compiled version
616 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
617
618 (defcustom org-agenda-use-time-grid t
619 "Non-nil means, show a time grid in the agenda schedule.
620 A time grid is a set of lines for specific times (like every two hours between
621 8:00 and 20:00. The items scheduled for a day at specific times are
622 sorted in between these lines.
623 For deails about when the grid will be shown, and what it will look like, see
624 the variable `org-agenda-time-grid'."
625 :group 'org-agenda
626 :type 'boolean)
627
628 (defcustom org-agenda-time-grid
629 '((daily today require-timed)
630 "----------------"
631 (800 1000 1200 1400 1600 1800 2000))
632
633 "The settings for time grid for agenda display.
634 This is a list of three items. The first item is again a list. It contains
635 symbols specifying conditions when the grid should be displayed:
636
637 daily if the agenda shows a single day
638 weekly if the agenda shows an entire week
639 today show grid on current date, independent of daily/weekly display
640 require-timed show grid only if at least on item has a time specification
641
642 The second item is a string which will be places behing the grid time.
643
644 The third item is a list of integers, indicating the times that should have
645 a grid line."
646 :group 'org-agenda
647 :type
648 '(list
649 (set :greedy t :tag "Grid Display Options"
650 (const :tag "Show grid in single day agenda display" daily)
651 (const :tag "Show grid in weekly agenda display" weekly)
652 (const :tag "Always show grid for today" today)
653 (const :tag "Show grid only if any timed entries are present"
654 require-timed)
655 (const :tag "Skip grid times already present in an entry"
656 remove-match))
657 (string :tag "Grid String")
658 (repeat :tag "Grid Times" (integer :tag "Time"))))
659
660 (defcustom org-agenda-remove-times-when-in-prefix t
661 "Non-nil means, remove duplicate time specifications in agenda items.
662 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
663 time-of-day specification in a headline or diary entry is extracted and
664 placed into the prefix. If this option is non-nil, the original specification
665 \(a timestamp or -range, or just a plain time(range) specification like
666 11:30-4pm) will be removed for agenda display. This makes the agenda less
667 cluttered.
668 The option can be t or nil. It may also be the symbol `beg', indicating
669 that the time should only be removed what it is located at the beginning of
670 the headline/diary entry."
671 :group 'org-agenda
672 :type '(choice
673 (const :tag "Always" t)
674 (const :tag "Never" nil)
675 (const :tag "When at beginning of entry" beg)))
676
677 (defcustom org-sort-agenda-notime-is-late t
678 "Non-nil means, items without time are considered late.
679 This is only relevant for sorting. When t, items which have no explicit
680 time like 15:30 will be considered as 24:01, i.e. later than any items which
681 do have a time. When nil, the default time is before 0:00. You can use this
682 option to decide if the schedule for today should come before or after timeless
683 agenda entries."
684 :group 'org-agenda
685 :type 'boolean)
686
687 (defgroup org-structure nil
688 "Options concerning structure editing in Org-mode."
689 :tag "Org Structure"
690 :group 'org)
691
692 (defcustom org-cycle-include-plain-lists nil
693 "Non-nil means, include plain lists into visibility cycling.
694 This means that during cycling, plain list items will *temporarily* be
695 interpreted as outline headlines with a level given by 1000+i where i is the
696 indentation of the bullet. In all other operations, plain list items are
697 not seen as headlines. For example, you cannot assign a TODO keyword to
698 such an item."
699 :group 'org-structure
700 :type 'boolean)
701
702 (defcustom org-cycle-emulate-tab t
703 "Where should `org-cycle' emulate TAB.
704 nil Never
705 white Only in completely white lines
706 t Everywhere except in headlines"
707 :group 'org-structure
708 :type '(choice (const :tag "Never" nil)
709 (const :tag "Only in completely white lines" white)
710 (const :tag "Everywhere except in headlines" t)
711 ))
712
713 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
714 "Hook that is run after `org-cycle' has changed the buffer visibility.
715 The function(s) in this hook must accept a single argument which indicates
716 the new state that was set by the most recent `org-cycle' command. The
717 argument is a symbol. After a global state change, it can have the values
718 `overview', `content', or `all'. After a local state change, it can have
719 the values `folded', `children', or `subtree'."
720 :group 'org-structure
721 :type 'hook)
722
723 (defcustom org-highlight-sparse-tree-matches t
724 "Non-nil means, highlight all matches that define a sparse tree.
725 The highlights will automatically disappear the next time the buffer is
726 changed by an edit command."
727 :group 'org-structure
728 :type 'boolean)
729
730 (defcustom org-show-hierarchy-above t
731 "Non-nil means, show full hierarchy when showing a spot in the tree.
732 Turning this off makes sparse trees more compact, but also less clear."
733 :group 'org-structure
734 :type 'boolean)
735
736 (defcustom org-show-following-heading t
737 "Non-nil means, show heading following match in `org-occur'.
738 When doing an `org-occur' it is useful to show the headline which
739 follows the match, even if they do not match the regexp. This makes it
740 easier to edit directly inside the sparse tree. However, if you use
741 org-occur mainly as an overview, the following headlines are
742 unnecessary clutter."
743 :group 'org-structure
744 :type 'boolean)
745
746 (defcustom org-occur-hook '(org-first-headline-recenter)
747 "Hook that is run after `org-occur' has constructed a sparse tree.
748 This can be used to recenter the window to show as much of the structure
749 as possible."
750 :group 'org-structure
751 :type 'hook)
752
753 (defcustom org-level-color-stars-only nil
754 "Non-nil means fontify only the stars in each headline.
755 When nil, the entire headline is fontified.
756 After changin this, requires restart of Emacs to become effective."
757 :group 'org-structure
758 :type 'boolean)
759
760 (defcustom org-adapt-indentation t
761 "Non-nil means, adapt indentation when promoting and demoting.
762 When this is set and the *entire* text in an entry is indented, the
763 indentation is increased by one space in a demotion command, and
764 decreased by one in a promotion command. If any line in the entry
765 body starts at column 0, indentation is not changed at all."
766 :group 'org-structure
767 :type 'boolean)
768
769 (defcustom org-plain-list-ordered-item-terminator t
770 "The character that makes a line with leading number an ordered list item.
771 Valid values are ?. and ?\). To get both terminators, use t. While
772 ?. may look nicer, it creates the danger that a line with leading
773 number may be incorrectly interpreted as an item. ?\) therefore is
774 the safe choice."
775 :group 'org-structure
776 :type '(choice (const :tag "dot like in \"2.\"" ?.)
777 (const :tag "paren like in \"2)\"" ?\))
778 (const :tab "both" t)))
779
780 (defcustom org-auto-renumber-ordered-lists t
781 "Non-nil means, automatically renumber ordered plain lists.
782 Renumbering happens when the sequence have been changed with
783 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
784 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
785 :group 'org-structure
786 :type 'boolean)
787
788 (defcustom org-enable-fixed-width-editor t
789 "Non-nil means, lines starting with \":\" are treated as fixed-width.
790 This currently only means, they are never auto-wrapped.
791 When nil, such lines will be treated like ordinary lines.
792 See also the QUOTE keyword."
793 :group 'org-structure
794 :type 'boolean)
795
796 (defcustom org-archive-location "%s_archive::"
797 "The location where subtrees should be archived.
798 This string consists of two parts, separated by a double-colon.
799
800 The first part is a file name - when omitted, archiving happens in the same
801 file. %s will be replaced by the current file name (without directory part).
802 Archiving to a different file is useful to keep archived entries from
803 contributing to the Org-mode Agenda.
804
805 The part after the double colon is a headline. The archived entries will be
806 filed under that headline. When omitted, the subtrees are simply filed away
807 at the end of the file, as top-level entries.
808
809 Here are a few examples:
810 \"%s_archive::\"
811 If the current file is Projects.org, archive in file
812 Projects.org_archive, as top-level trees. This is the default.
813
814 \"::* Archived Tasks\"
815 Archive in the current file, under the top-level headline
816 \"* Archived Tasks\".
817
818 \"~/org/archive.org::\"
819 Archive in file ~/org/archive.org (absolute path), as top-level trees.
820
821 \"basement::** Finished Tasks\"
822 Archive in file ./basement (relative path), as level 3 trees
823 below the level 2 heading \"** Finished Tasks\".
824
825 You may set this option on a per-file basis by adding to the buffer a
826 line like
827
828 #+ARCHIVE: basement::** Finished Tasks"
829 :group 'org-structure
830 :type 'string)
831
832 (defcustom org-archive-mark-done t
833 "Non-nil means, mark archived entries as DONE."
834 :group 'org-structure
835 :type 'boolean)
836
837 (defcustom org-archive-stamp-time t
838 "Non-nil means, add a time stamp to archived entries.
839 The time stamp will be added directly after the TODO state keyword in the
840 first line, so it is probably best to use this in combinations with
841 `org-archive-mark-done'."
842 :group 'org-structure
843 :type 'boolean)
844
845 (defgroup org-tags nil
846 "Options concerning startup of Org-mode."
847 :tag "Org Tags"
848 :group 'org)
849
850 (defcustom org-tags-column 48
851 "The column to which tags should be indented in a headline.
852 If this number is positive, it specified the column. If it is negative,
853 it means that the tags should be flushright to that column. For example,
854 -79 works well for a normal 80 character screen."
855 :group 'org-tags
856 :type 'integer)
857
858 (defcustom org-auto-align-tags t
859 "Non-nil means, realign tags after pro/demotion of TODO state change.
860 These operations change the length of a headline and therefore shift
861 the tags around. With this options turned on, after each such operation
862 the tags are again aligned to `org-tags-column'."
863 :group 'org-tags
864 :type 'boolean)
865
866 (defcustom org-use-tag-inheritance t
867 "Non-nil means, tags in levels apply also for sublevels.
868 When nil, only the tags directly give in a specific line apply there.
869 If you turn off this option, you very likely want to turn on the
870 companion option `org-tags-match-list-sublevels'."
871 :group 'org-tags
872 :type 'boolean)
873
874 (defcustom org-tags-match-list-sublevels nil
875 "Non-nil means list also sublevels of headlines matching tag search.
876 Because of tag inheritance (see variable `org-use-tag-inheritance'),
877 the sublevels of a headline matching a tag search often also match
878 the same search. Listing all of them can create very long lists.
879 Setting this variable to nil causes subtrees to be skipped.
880 This option is off by default, because inheritance in on. If you turn
881 inheritance off, you very likely want to turn this option on.
882
883 As a special case, if the tag search is restricted to TODO items, the
884 value of this variable is ignored and sublevels are always checked, to
885 make sure all corresponding TODO items find their way into the list."
886 :group 'org-tags
887 :type 'boolean)
888
889 (defvar org-tags-history nil
890 "History of minibuffer reads for tags.")
891 (defvar org-last-tags-completion-table nil
892 "The last used completion table for tags.")
893
894 (defgroup org-link nil
895 "Options concerning links in Org-mode."
896 :tag "Org Link"
897 :group 'org)
898
899 (defcustom org-tab-follows-link nil
900 "Non-nil means, on links TAB will follow the link.
901 Needs to be set before org.el is loaded."
902 :group 'org-link
903 :type 'boolean)
904
905 (defcustom org-return-follows-link nil
906 "Non-nil means, on links RET will follow the link.
907 Needs to be set before org.el is loaded."
908 :group 'org-link
909 :type 'boolean)
910
911 (defcustom org-link-format "<%s>"
912 "Default format for linkes in the buffer.
913 This is a format string for printf, %s will be replaced by the link text.
914 If you want to make sure that your link is always properly terminated,
915 include angle brackets into this format, like \"<%s>\". Some people also
916 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
917 :group 'org-link
918 :type '(choice
919 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
920 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
921 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
922 (string :tag "Other" :value "<%s>")))
923
924 (defcustom org-allow-space-in-links t
925 "Non-nil means, file names in links may contain space characters.
926 When nil, it becomes possible to put several links into a line.
927 Note that in tables, a link never extends accross fields, so in a table
928 it is always possible to put several links into a line.
929 Changing this varable requires a re-launch of Emacs of become effective."
930 :group 'org-link
931 :type 'boolean)
932
933 (defcustom org-context-in-file-links t
934 "Non-nil means, file links from `org-store-link' contain context.
935 The line number will be added to the file name with :: as separator and
936 used to find the context when the link is activated by the command
937 `org-open-at-point'.
938 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
939 negates this setting for the duration of the command."
940 :group 'org-link
941 :type 'boolean)
942
943 (defcustom org-keep-stored-link-after-insertion nil
944 "Non-nil means, keep link in list for entire session.
945
946 The command `org-store-link' adds a link pointing to the current
947 location to an internal list. These links accumulate during a session.
948 The command `org-insert-link' can be used to insert links into any
949 Org-mode file (offering completion for all stored links). When this
950 option is nil, every link which has been inserted once using \\[org-insert-link]
951 will be removed from the list, to make completing the unused links
952 more efficient."
953 :group 'org-link
954 :type 'boolean)
955
956 (defcustom org-link-frame-setup
957 '((vm . vm-visit-folder-other-frame)
958 (gnus . gnus-other-frame)
959 (file . find-file-other-window))
960 "Setup the frame configuration for following links.
961 When following a link with Emacs, it may often be useful to display
962 this link in another window or frame. This variable can be used to
963 set this up for the different types of links.
964 For VM, use any of
965 `vm-visit-folder'
966 `vm-visit-folder-other-frame'
967 For Gnus, use any of
968 `gnus'
969 `gnus-other-frame'
970 For FILE, use any of
971 `find-file'
972 `find-file-other-window'
973 `find-file-other-frame'
974 For the calendar, use the variable `calendar-setup'.
975 For BBDB, it is currently only possible to display the matches in
976 another window."
977 :group 'org-link
978 :type '(list
979 (cons (const vm)
980 (choice
981 (const vm-visit-folder)
982 (const vm-visit-folder-other-window)
983 (const vm-visit-folder-other-frame)))
984 (cons (const gnus)
985 (choice
986 (const gnus)
987 (const gnus-other-frame)))
988 (cons (const file)
989 (choice
990 (const find-file)
991 (const find-file-other-window)
992 (const find-file-other-frame)))))
993
994 (defcustom org-usenet-links-prefer-google nil
995 "Non-nil means, `org-store-link' will create web links to google groups.
996 When nil, Gnus will be used for such links.
997 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
998 negates this setting for the duration of the command."
999 :group 'org-link
1000 :type 'boolean)
1001
1002 (defcustom org-open-non-existing-files nil
1003 "Non-nil means, `org-open-file' will open non-existing file.
1004 When nil, an error will be generated."
1005 :group 'org-link
1006 :type 'boolean)
1007
1008 (defcustom org-confirm-shell-links t
1009 "Non-nil means, ask for confirmation before executing shell links.
1010 The default is true, to keep new users from shooting into their own foot."
1011 :group 'org-link
1012 :type 'boolean)
1013
1014 (defconst org-file-apps-defaults-gnu
1015 '((t . emacs)
1016 ("jpg" . "xv %s")
1017 ("gif" . "xv %s")
1018 ("ppm" . "xv %s")
1019 ("pgm" . "xv %s")
1020 ("pbm" . "xv %s")
1021 ("tif" . "xv %s")
1022 ("png" . "xv %s")
1023 ("ps" . "gv %s")
1024 ("ps.gz" . "gv %s")
1025 ("eps" . "gv %s")
1026 ("eps.gz" . "gv %s")
1027 ("dvi" . "xdvi %s")
1028 ("mpeg" . "plaympeg %s")
1029 ("mp3" . "plaympeg %s")
1030 ("fig" . "xfig %s")
1031 ("pdf" . "acroread %s")
1032 ("doc" . "soffice %s")
1033 ("ppt" . "soffice %s")
1034 ("pps" . "soffice %s")
1035 ("html" . "netscape -remote openURL(%s,new-window)")
1036 ("htm" . "netscape -remote openURL(%s,new-window)")
1037 ("xs" . "soffice %s"))
1038 "Default file applications on a UNIX/LINUX system.
1039 See `org-file-apps'.")
1040
1041 (defconst org-file-apps-defaults-macosx
1042 '((t . "open %s")
1043 ("ps" . "gv %s")
1044 ("ps.gz" . "gv %s")
1045 ("eps" . "gv %s")
1046 ("eps.gz" . "gv %s")
1047 ("dvi" . "xdvi %s")
1048 ("fig" . "xfig %s"))
1049 "Default file applications on a MacOS X system.
1050 The system \"open\" is known as a default, but we use X11 applications
1051 for some files for which the OS does not have a good default.
1052 See `org-file-apps'.")
1053
1054 (defconst org-file-apps-defaults-windowsnt
1055 '((t . (w32-shell-execute "open" file)))
1056 "Default file applications on a Windows NT system.
1057 The system \"open\" is used for most files.
1058 See `org-file-apps'.")
1059
1060 (defcustom org-file-apps
1061 '(
1062 ("txt" . emacs)
1063 ("tex" . emacs)
1064 ("ltx" . emacs)
1065 ("org" . emacs)
1066 ("el" . emacs)
1067 )
1068 "External applications for opening `file:path' items in a document.
1069 Org-mode uses system defaults for different file types, but
1070 you can use this variable to set the application for a given file
1071 extension. The entries in this list are cons cells with a file extension
1072 and the corresponding command. Possible values for the command are:
1073 `emacs' The file will be visited by the current Emacs process.
1074 `default' Use the default application for this file type.
1075 string A command to be executed by a shell; %s will be replaced
1076 by the path to the file.
1077 sexp A Lisp form which will be evaluated. The file path will
1078 be available in the Lisp variable `file'.
1079 For more examples, see the system specific constants
1080 `org-file-apps-defaults-macosx'
1081 `org-file-apps-defaults-windowsnt'
1082 `org-file-apps-defaults-gnu'."
1083 :group 'org-link
1084 :type '(repeat
1085 (cons (string :tag "Extension")
1086 (choice :value ""
1087 (const :tag "Visit with Emacs" 'emacs)
1088 (const :tag "Use system default" 'default)
1089 (string :tag "Command")
1090 (sexp :tag "Lisp form")))))
1091
1092
1093 (defgroup org-remember nil
1094 "Options concerning interaction with remember.el."
1095 :tag "Org Remember"
1096 :group 'org)
1097
1098 (defcustom org-directory "~/org"
1099 "Directory with org files.
1100 This directory will be used as default to prompt for org files.
1101 Used by the hooks for remember.el."
1102 :group 'org-remember
1103 :type 'directory)
1104
1105 (defcustom org-default-notes-file "~/.notes"
1106 "Default target for storing notes.
1107 Used by the hooks for remember.el. This can be a string, or nil to mean
1108 the value of `remember-data-file'."
1109 :group 'org-remember
1110 :type '(choice
1111 (const :tag "Default from remember-data-file" nil)
1112 file))
1113
1114 (defcustom org-reverse-note-order nil
1115 "Non-nil means, store new notes at the beginning of a file or entry.
1116 When nil, new notes will be filed to the end of a file or entry."
1117 :group 'org-remember
1118 :type '(choice
1119 (const :tag "Reverse always" t)
1120 (const :tag "Reverse never" nil)
1121 (repeat :tag "By file name regexp"
1122 (cons regexp boolean))))
1123
1124 (defgroup org-table nil
1125 "Options concerning tables in Org-mode."
1126 :tag "Org Table"
1127 :group 'org)
1128
1129 (defcustom org-enable-table-editor 'optimized
1130 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1131 When nil, such lines will be treated like ordinary lines.
1132
1133 When equal to the symbol `optimized', the table editor will be optimized to
1134 do the following
1135 - Use automatic overwrite mode in front of whitespace in table fields.
1136 This make the structure of the table stay in tact as long as the edited
1137 field does not exceed the column width.
1138 - Minimize the number of realigns. Normally, the table is aligned each time
1139 TAB or RET are pressed to move to another field. With optimization this
1140 happens only if changes to a field might have changed the column width.
1141 Optimization requires replacing the functions `self-insert-command',
1142 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1143 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1144 very good at guessing when a re-align will be necessary, but you can always
1145 force one with \\[org-ctrl-c-ctrl-c].
1146
1147 If you would like to use the optimized version in Org-mode, but the
1148 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1149
1150 This variable can be used to turn on and off the table editor during a session,
1151 but in order to toggle optimization, a restart is required.
1152
1153 See also the variable `org-table-auto-blank-field'."
1154 :group 'org-table
1155 :type '(choice
1156 (const :tag "off" nil)
1157 (const :tag "on" t)
1158 (const :tag "on, optimized" optimized)))
1159
1160 ;; FIXME: We could have a third option which makes it jump only over the first
1161 ;; hline in a table.
1162 (defcustom org-table-tab-jumps-over-hlines t
1163 "Non-nil means, tab in the last column of a table with jump over a hline.
1164 If a horizontal separator line is following the current line,
1165 `org-table-next-field' can either create a new row before that line, or jump
1166 over the line. When this option is nil, a new line will be created before
1167 this line."
1168 :group 'org-table
1169 :type 'boolean)
1170
1171 (defcustom org-table-auto-blank-field t
1172 "Non-nil means, automatically blank table field when starting to type into it.
1173 This only happens when typing immediately after a field motion
1174 command (TAB, S-TAB or RET).
1175 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1176 :group 'org-table
1177 :type 'boolean)
1178
1179 (defcustom org-table-default-size "5x2"
1180 "The default size for newly created tables, Columns x Rows."
1181 :group 'org-table
1182 :type 'string)
1183
1184 (defcustom org-table-automatic-realign t
1185 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1186 When nil, aligning is only done with \\[org-table-align], or after column
1187 removal/insertion."
1188 :group 'org-table
1189 :type 'boolean)
1190
1191 (defcustom org-table-spaces-around-separators '(1 . 1)
1192 "The number of spaces to be placed before and after separators."
1193 :group 'org-table
1194 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1195
1196 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1197 "The number of spaces to be placed before and after separators.
1198 This option applies when the column separators have been made invisible."
1199 :group 'org-table
1200 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1201
1202 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1203 "Regular expression for recognizing numbers in table columns.
1204 If a table column contains mostly numbers, it will be aligned to the
1205 right. If not, it will be aligned to the left.
1206
1207 The default value of this option is a regular expression which allows
1208 anything which looks remotely like a number as used in scientific
1209 context. For example, all of the following will be considered a
1210 number:
1211 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1212
1213 Other options offered by the customize interface are more restrictive."
1214 :group 'org-table
1215 :type '(choice
1216 (const :tag "Positive Integers"
1217 "^[0-9]+$")
1218 (const :tag "Integers"
1219 "^[-+]?[0-9]+$")
1220 (const :tag "Floating Point Numbers"
1221 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1222 (const :tag "Floating Point Number or Integer"
1223 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1224 (const :tag "Exponential, Floating point, Integer"
1225 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1226 (const :tag "Very General Number-Like"
1227 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1228 (string :tag "Regexp:")))
1229
1230 (defcustom org-table-number-fraction 0.5
1231 "Fraction of numbers in a column required to make the column align right.
1232 In a column all non-white fields are considered. If at least this
1233 fraction of fields is matched by `org-table-number-fraction',
1234 alignment to the right border applies."
1235 :group 'org-table
1236 :type 'number)
1237
1238 (defcustom org-export-highlight-first-table-line t
1239 "Non-nil means, highlight the first table line.
1240 In HTML export, this means use <th> instead of <td>.
1241 In tables created with table.el, this applies to the first table line.
1242 In Org-mode tables, all lines before the first horizontal separator
1243 line will be formatted with <th> tags."
1244 :group 'org-table
1245 :type 'boolean)
1246
1247 (defcustom org-table-tab-recognizes-table.el t
1248 "Non-nil means, TAB will automatically notice a table.el table.
1249 When it sees such a table, it moves point into it and - if necessary -
1250 calls `table-recognize-table'."
1251 :group 'org-table
1252 :type 'boolean)
1253
1254 (defgroup org-table-calculation nil
1255 "Options concerning tables in Org-mode."
1256 :tag "Org Table Calculation"
1257 :group 'org)
1258
1259 (defcustom org-table-copy-increment t
1260 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1261 :group 'org-table-calculation
1262 :type 'boolean)
1263
1264 (defcustom org-calc-default-modes
1265 '(calc-internal-prec 12
1266 calc-float-format (float 5)
1267 calc-angle-mode deg
1268 calc-prefer-frac nil
1269 calc-symbolic-mode nil
1270 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1271 calc-display-working-message t
1272 )
1273 "List with Calc mode settings for use in calc-eval for table formulas.
1274 The list must contain alternating symbols (calc modes variables and values.
1275 Don't remove any of the default settings, just change the values. Org-mode
1276 relies on the variables to be present in the list."
1277 :group 'org-table-calculation
1278 :type 'plist)
1279
1280 (defcustom org-table-formula-evaluate-inline t
1281 "Non-nil means, TAB and RET evaluate a formula in current table field.
1282 If the current field starts with an equal sign, it is assumed to be a formula
1283 which should be evaluated as described in the manual and in the documentation
1284 string of the command `org-table-eval-formula'. This feature requires the
1285 Emacs calc package.
1286 When this variable is nil, formula calculation is only available through
1287 the command \\[org-table-eval-formula]."
1288 :group 'org-table-calculation
1289 :type 'boolean)
1290
1291
1292 (defcustom org-table-formula-use-constants t
1293 "Non-nil means, interpret constants in formulas in tables.
1294 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1295 by the value given in `org-table-formula-constants', or by a value obtained
1296 from the `constants.el' package."
1297 :group 'org-table-calculation
1298 :type 'boolean)
1299
1300 (defcustom org-table-formula-constants nil
1301 "Alist with constant names and values, for use in table formulas.
1302 The car of each element is a name of a constant, without the `$' before it.
1303 The cdr is the value as a string. For example, if you'd like to use the
1304 speed of light in a formula, you would configure
1305
1306 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1307
1308 and then use it in an equation like `$1*$c'."
1309 :group 'org-table-calculation
1310 :type '(repeat
1311 (cons (string :tag "name")
1312 (string :tag "value"))))
1313
1314 (defcustom org-table-formula-numbers-only nil
1315 "Non-nil means, calculate only with numbers in table formulas.
1316 Then all input fields will be converted to a number, and the result
1317 must also be a number. When nil, calc's full potential is available
1318 in table calculations, including symbolics etc."
1319 :group 'org-table-calculation
1320 :type 'boolean)
1321
1322 (defcustom org-table-allow-automatic-line-recalculation t
1323 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1324 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1325 :group 'org-table-calculation
1326 :type 'boolean)
1327
1328 (defgroup org-export nil
1329 "Options for exporting org-listings."
1330 :tag "Org Export"
1331 :group 'org)
1332
1333 (defcustom org-export-language-setup
1334 '(("en" "Author" "Date" "Table of Contents")
1335 ("da" "Ophavsmand" "Dato" "Indhold")
1336 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1337 ("es" "Autor" "Fecha" "\xccndice")
1338 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1339 ("it" "Autore" "Data" "Indice")
1340 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1341 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1342 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1343 "Terms used in export text, translated to different languages.
1344 Use the variable `org-export-default-language' to set the language,
1345 or use the +OPTION lines for a per-file setting."
1346 :group 'org-export
1347 :type '(repeat
1348 (list
1349 (string :tag "HTML language tag")
1350 (string :tag "Author")
1351 (string :tag "Date")
1352 (string :tag "Table of Contents"))))
1353
1354 (defcustom org-export-default-language "en"
1355 "The default language of HTML export, as a string.
1356 This should have an association in `org-export-language-setup'."
1357 :group 'org-export
1358 :type 'string)
1359
1360 (defcustom org-export-html-style
1361 "<style type=\"text/css\">
1362 html {
1363 font-family: Times, serif;
1364 font-size: 12pt;
1365 }
1366 .title { text-align: center; }
1367 .todo, .deadline { color: red; }
1368 .done { color: green; }
1369 pre {
1370 border: 1pt solid #AEBDCC;
1371 background-color: #F3F5F7;
1372 padding: 5pt;
1373 font-family: courier, monospace;
1374 }
1375 table { border-collapse: collapse; }
1376 td, th {
1377 vertical-align: top;
1378 border: 1pt solid #ADB9CC;
1379 }
1380 </style>"
1381 "The default style specification for exported HTML files.
1382 Since there are different ways of setting style information, this variable
1383 needs to contain the full HTML structure to provide a style, including the
1384 surrounding HTML tags. The style specifications should include definiitons
1385 for new classes todo, done, title, and deadline. For example, legal values
1386 would be.
1387
1388 <style type=\"text/css\">
1389 p {font-weight: normal; color: gray; }
1390 h1 {color: black; }
1391 .title { text-align: center; }
1392 .todo, .deadline { color: red; }
1393 .done { color: green; }
1394 </style>
1395
1396 or, if you want to keep the style in a file,
1397
1398 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1399
1400 As the value of this option simply gets inserted into the HTML <head> header,
1401 you can \"misuse\" it to add arbitrary text to the header."
1402 :group 'org-export
1403 :type 'string)
1404
1405 (defcustom org-export-headline-levels 3
1406 "The last level which is still exported as a headline.
1407 Inferior levels will produce itemize lists when exported.
1408 Note that a numeric prefix argument to an exporter function overrides
1409 this setting.
1410
1411 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1412 :group 'org-export
1413 :type 'number)
1414
1415 (defcustom org-export-with-section-numbers t
1416 "Non-nil means, add section numbers to headlines when exporting.
1417
1418 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1419 :group 'org-export
1420 :type 'boolean)
1421
1422 (defcustom org-export-with-toc t
1423 "Non-nil means, create a table of contents in exported files.
1424 The TOC contains headlines with levels up to`org-export-headline-levels'.
1425
1426 Headlines which contain any TODO items will be marked with \"(*)\" in
1427 ASCII export, and with red color in HTML output.
1428
1429 In HTML output, the TOC will be clickable.
1430
1431 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1432 :group 'org-export
1433 :type 'boolean)
1434
1435 (defcustom org-export-plain-list-max-depth 20
1436 "Maximum depth of hand-formatted lists in HTML export.
1437
1438 Org-mode parses hand-formatted enumeration and bullet lists and
1439 transforms them to HTML open export. Different indentation of the
1440 bullet or number indicates different list nesting levels. To avoid
1441 confusion, only a single level is allowed by default. When this is
1442 larger than 1, deeper indentation leads to deeper list nesting. For
1443 example, the default value of 3 allows the following list to be
1444 formatted correctly in HTML:
1445
1446 * Fruit
1447 - Apple
1448 - Banana
1449 1. from Africa
1450 2. from South America
1451 - Pineapple
1452 * Bread
1453 * Dairy products"
1454 :group 'org-export
1455 :type 'integer)
1456
1457 (defcustom org-export-preserve-breaks nil
1458 "Non-nil means, preserve all line breaks when exporting.
1459 Normally, in HTML output paragraphs will be reformatted. In ASCII
1460 export, line breaks will always be preserved, regardless of this variable.
1461
1462 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1463 :group 'org-export
1464 :type 'boolean)
1465
1466 (defcustom org-export-html-inline-images t
1467 "Non-nil means, inline images into exported HTML pages.
1468 The link will still be to the original location of the image file.
1469 So if you are moving the page, lets say to your public HTML site,
1470 you will have to move the image and maybe change the link."
1471 :group 'org-export
1472 :type 'boolean)
1473
1474 (defcustom org-export-html-expand t
1475 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1476 When nil, these tags will be exported as plain text and therefore
1477 not be interpreted by a browser.
1478
1479 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1480 :group 'org-export
1481 :type 'boolean)
1482
1483 (defcustom org-export-with-fixed-width t
1484 "Non-nil means, lines starting with \":\" will be in fixed width font.
1485 This can be used to have pre-formatted text, fragments of code etc. For
1486 example
1487 : ;; Some Lisp examples
1488 : (while (defc cnt)
1489 : (ding))
1490 will be looking just like this in also HTML. In ASCII export, this option
1491 has no effect.
1492
1493 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1494 :group 'org-export
1495 :type 'boolean)
1496
1497 (defcustom org-export-with-tables t
1498 "If non-nil, lines starting with \"|\" define a table.
1499 For example:
1500
1501 | Name | Address | Birthday |
1502 |-------------+----------+-----------|
1503 | Arthur Dent | England | 29.2.2100 |
1504
1505 In ASCII export, this option has no effect.
1506
1507 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1508 :group 'org-export
1509 :type 'boolean)
1510
1511 (defcustom org-export-prefer-native-exporter-for-tables nil
1512 "Non-nil means, always export tables created with table.el natively.
1513 Natively means, use the HTML code generator in table.el.
1514 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1515 the table does not use row- or column-spanning). This has the
1516 advantage, that the automatic HTML conversions for math symbols and
1517 sub/superscripts can be applied. Org-mode's HTML generator is also
1518 much faster."
1519 :group 'org-export
1520 :type 'boolean)
1521
1522 (defcustom org-export-html-table-tag
1523 "<table border=1 cellspacing=0 cellpadding=6>"
1524 "The HTML tag used to start a table.
1525 This must be a <table> tag, but you may change the options like
1526 borders and spacing."
1527 :group 'org-export
1528 :type 'string)
1529
1530 (defcustom org-export-with-emphasize t
1531 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1532 If the export target supports emphasizing text, the word will be
1533 typeset in bold, italic, or underlined, respectively. Works only for
1534 single words, but you can say: I *really* *mean* *this*.
1535 In ASCII export, this option has no effect.
1536
1537 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1538 :group 'org-export
1539 :type 'boolean)
1540
1541 (defcustom org-match-sexp-depth 3
1542 "Number of stacked braces for sub/superscript matching.
1543 This has to be set before loading org.el to be effective."
1544 :group 'org-export
1545 :type 'integer)
1546
1547 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1548 (defcustom org-export-with-sub-superscripts t
1549 "Non-nil means, interpret \"_\" and \"^\" for export.
1550 When this option is turned on, you can use TeX-like syntax for sub- and
1551 superscripts. Several characters after \"_\" or \"^\" will be
1552 considered as a single item - so grouping with {} is normally not
1553 needed. For example, the following things will be parsed as single
1554 sub- or superscripts.
1555
1556 10^24 or 10^tau several digits will be considered 1 item
1557 10^-12 or 10^-tau a leading sign with digits or a word
1558 x^2-y^3 will be read as x^2 - y^3, because items are
1559 terminated by almost any nonword/nondigit char.
1560 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1561
1562 Still, ambiguity is possible - so when in doubt use {} to enclose the
1563 sub/superscript.
1564 In ASCII export, this option has no effect.
1565
1566 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1567 :group 'org-export
1568 :type 'boolean)
1569
1570 (defcustom org-export-with-TeX-macros t
1571 "Non-nil means, interpret simple TeX-like macros when exporting.
1572 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1573 No only real TeX macros will work here, but the standard HTML entities
1574 for math can be used as macro names as well. For a list of supported
1575 names in HTML export, see the constant `org-html-entities'.
1576 In ASCII export, this option has no effect.
1577
1578 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1579 :group 'org-export
1580 :type 'boolean)
1581
1582 (defcustom org-export-html-with-timestamp nil
1583 "If non-nil, write `org-export-html-html-helper-timestamp'
1584 into the exported html text. Otherwise, the buffer will just be saved
1585 to a file."
1586 :group 'org-export
1587 :type 'boolean)
1588
1589 (defcustom org-export-html-html-helper-timestamp
1590 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1591 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1592 :group 'org-export
1593 :type 'string)
1594
1595 (defcustom org-export-ascii-show-new-buffer t
1596 "Non-nil means, popup buffer containing the exported ASCII text.
1597 Otherwise the buffer will just be saved to a file and stay hidden."
1598 :group 'org-export
1599 :type 'boolean)
1600
1601 (defcustom org-export-html-show-new-buffer nil
1602 "Non-nil means, popup buffer containing the exported html text.
1603 Otherwise, the buffer will just be saved to a file and stay hidden."
1604 :group 'org-export
1605 :type 'boolean)
1606
1607 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1608 "The file name for the iCalendar file covering all agenda files.
1609 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1610 :group 'org-export
1611 :type 'file)
1612
1613 (defcustom org-icalendar-include-todo nil
1614 "Non-nil means, export to iCalendar files should also cover TODO items."
1615 :group 'org-export
1616 :type 'boolean)
1617
1618 (defcustom org-icalendar-combined-name "OrgMode"
1619 "Calendar name for the combined iCalendar representing all agenda files."
1620 :group 'org-export
1621 :type 'string)
1622
1623 (defgroup org-faces nil
1624 "Faces for highlighting in Org-mode."
1625 :tag "Org Faces"
1626 :group 'org)
1627
1628 (defface org-level-1 ;; font-lock-function-name-face
1629 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1630 (((class color) (background light)) (:foreground "Blue"))
1631 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1632 (t (:inverse-video t :bold t)))
1633 "Face used for level 1 headlines."
1634 :group 'org-faces)
1635
1636 (defface org-level-2 ;; font-lock-variable-name-face
1637 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1638 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1639 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1640 (t (:bold t :italic t)))
1641 "Face used for level 2 headlines."
1642 :group 'org-faces)
1643
1644 (defface org-level-3 ;; font-lock-keyword-face
1645 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1646 (((class color) (background light)) (:foreground "Purple"))
1647 (((class color) (background dark)) (:foreground "Cyan"))
1648 (t (:bold t)))
1649 "Face used for level 3 headlines."
1650 :group 'org-faces)
1651
1652 (defface org-level-4 ;; font-lock-comment-face
1653 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1654 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1655 (((class color) (background light)) (:foreground "Firebrick"))
1656 (((class color) (background dark)) (:foreground "chocolate1"))
1657 (t (:bold t :italic t)))
1658 "Face used for level 4 headlines."
1659 :group 'org-faces)
1660
1661 (defface org-level-5 ;; font-lock-type-face
1662 '((((type tty) (class color)) (:foreground "green"))
1663 (((class color) (background light)) (:foreground "ForestGreen"))
1664 (((class color) (background dark)) (:foreground "PaleGreen"))
1665 (t (:bold t :underline t)))
1666 "Face used for level 5 headlines."
1667 :group 'org-faces)
1668
1669 (defface org-level-6 ;; font-lock-constant-face
1670 '((((type tty) (class color)) (:foreground "magenta"))
1671 (((class color) (background light)) (:foreground "CadetBlue"))
1672 (((class color) (background dark)) (:foreground "Aquamarine"))
1673 (t (:bold t :underline t)))
1674 "Face used for level 6 headlines."
1675 :group 'org-faces)
1676
1677 (defface org-level-7 ;; font-lock-builtin-face
1678 '((((type tty) (class color)) (:foreground "blue" :weight light))
1679 (((class color) (background light)) (:foreground "Orchid"))
1680 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1681 (t (:bold t)))
1682 "Face used for level 7 headlines."
1683 :group 'org-faces)
1684
1685 (defface org-level-8 ;; font-lock-string-face
1686 '((((type tty) (class color)) (:foreground "green"))
1687 (((class color) (background light)) (:foreground "RosyBrown"))
1688 (((class color) (background dark)) (:foreground "LightSalmon"))
1689 (t (:italic t)))
1690 "Face used for level 8 headlines."
1691 :group 'org-faces)
1692
1693 (defface org-special-keyword ;; font-lock-string-face
1694 '((((type tty) (class color)) (:foreground "green"))
1695 (((class color) (background light)) (:foreground "RosyBrown"))
1696 (((class color) (background dark)) (:foreground "LightSalmon"))
1697 (t (:italic t)))
1698 "Face used for level 8 headlines."
1699 :group 'org-faces)
1700
1701 (defface org-warning ;; font-lock-warning-face
1702 '((((type tty) (class color)) (:foreground "red"))
1703 (((class color) (background light)) (:foreground "Red" :bold t))
1704 (((class color) (background dark)) (:foreground "Red1" :bold t))
1705 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1706 (t (:inverse-video t :bold t)))
1707 "Face for deadlines and TODO keywords."
1708 :group 'org-faces)
1709
1710 (defcustom org-fontify-done-headline nil
1711 "Non-nil means, change the face of a headline if it is marked DONE.
1712 Normally, only the TODO/DONE keyword indicates the state of a headline.
1713 When this is non-nil, the headline after the keyword is set to the
1714 `org-headline-done' as an additional indication."
1715 :group 'org-faces
1716 :type 'boolean)
1717
1718 (defface org-headline-done ;; font-lock-string-face
1719 '((((type tty) (class color)) (:foreground "green"))
1720 (((class color) (background light)) (:foreground "RosyBrown"))
1721 (((class color) (background dark)) (:foreground "LightSalmon"))
1722 (t (:italic t)))
1723 "Face used to indicate that a headline is DONE. See also the variable
1724 `org-fontify-done-headline'."
1725 :group 'org-faces)
1726
1727 ;; Inheritance does not yet work for xemacs. So we just copy...
1728
1729 (defface org-deadline-announce
1730 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1731 (((class color) (background light)) (:foreground "Blue"))
1732 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1733 (t (:inverse-video t :bold t)))
1734 "Face for upcoming deadlines."
1735 :group 'org-faces)
1736
1737 (defface org-scheduled-today
1738 '((((type tty) (class color)) (:foreground "green"))
1739 (((class color) (background light)) (:foreground "DarkGreen"))
1740 (((class color) (background dark)) (:foreground "PaleGreen"))
1741 (t (:bold t :underline t)))
1742 "Face for items scheduled for a certain day."
1743 :group 'org-faces)
1744
1745 (defface org-scheduled-previously
1746 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1747 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1748 (((class color) (background light)) (:foreground "Firebrick"))
1749 (((class color) (background dark)) (:foreground "chocolate1"))
1750 (t (:bold t :italic t)))
1751 "Face for items scheduled previously, and not yet done."
1752 :group 'org-faces)
1753
1754 (defface org-formula
1755 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1756 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1757 (((class color) (background light)) (:foreground "Firebrick"))
1758 (((class color) (background dark)) (:foreground "chocolate1"))
1759 (t (:bold t :italic t)))
1760 "Face for items scheduled previously, and not yet done."
1761 :group 'org-faces)
1762
1763 (defface org-link
1764 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1765 (((class color) (background light)) (:foreground "Purple"))
1766 (((class color) (background dark)) (:foreground "Cyan"))
1767 (t (:bold t)))
1768 "Face for links."
1769 :group 'org-faces)
1770
1771 (defface org-done ;; font-lock-type-face
1772 '((((type tty) (class color)) (:foreground "green"))
1773 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1774 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1775 (t (:bold t :underline t)))
1776 "Face used for DONE."
1777 :group 'org-faces)
1778
1779 (defface org-table ;; font-lock-function-name-face
1780 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1781 (((class color) (background light)) (:foreground "Blue"))
1782 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1783 (t (:inverse-video t :bold t)))
1784 "Face used for tables."
1785 :group 'org-faces)
1786
1787 (defface org-time-grid ;; font-lock-variable-name-face
1788 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1789 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1790 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1791 (t (:bold t :italic t)))
1792 "Face used for level 2 headlines."
1793 :group 'org-faces)
1794
1795 (defvar org-level-faces
1796 '(
1797 org-level-1
1798 org-level-2
1799 org-level-3
1800 org-level-4
1801 org-level-5
1802 org-level-6
1803 org-level-7
1804 org-level-8
1805 ))
1806 (defvar org-n-levels (length org-level-faces))
1807
1808 (defun org-set-regexps-and-options ()
1809 "Precompute regular expressions for current buffer."
1810 (when (eq major-mode 'org-mode)
1811 (let ((re (org-make-options-regexp
1812 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1813 "STARTUP" "ARCHIVE")))
1814 (splitre "[ \t]+")
1815 kwds int key value cat arch)
1816 (save-excursion
1817 (save-restriction
1818 (widen)
1819 (goto-char (point-min))
1820 (while (re-search-forward re nil t)
1821 (setq key (match-string 1) value (match-string 2))
1822 (cond
1823 ((equal key "CATEGORY")
1824 (if (string-match "[ \t]+$" value)
1825 (setq value (replace-match "" t t value)))
1826 (setq cat (intern value)))
1827 ((equal key "SEQ_TODO")
1828 (setq int 'sequence
1829 kwds (append kwds (org-split-string value splitre))))
1830 ((equal key "PRI_TODO")
1831 (setq int 'priority
1832 kwds (append kwds (org-split-string value splitre))))
1833 ((equal key "TYP_TODO")
1834 (setq int 'type
1835 kwds (append kwds (org-split-string value splitre))))
1836 ((equal key "STARTUP")
1837 (let ((opts (org-split-string value splitre))
1838 (set '(("fold" org-startup-folded t)
1839 ("nofold" org-startup-folded nil)
1840 ("content" org-startup-folded content)
1841 ("dlcheck" org-startup-with-deadline-check t)
1842 ("nodlcheck" org-startup-with-deadline-check nil)))
1843 l var val)
1844 (while (setq l (assoc (pop opts) set))
1845 (setq var (nth 1 l) val (nth 2 l))
1846 (set (make-local-variable var) val))))
1847 ((equal key "ARCHIVE")
1848 (string-match " *$" value)
1849 (setq arch (replace-match "" t t value))
1850 (remove-text-properties 0 (length arch)
1851 '(face t fontified t) arch)))
1852 )))
1853 (and cat (set (make-local-variable 'org-category) cat))
1854 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1855 (and arch (set (make-local-variable 'org-archive-location) arch))
1856 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1857 ;; Compute the regular expressions and other local variables
1858 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1859 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1860 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1861 (length org-scheduled-string)))
1862 org-done-string
1863 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1864 org-todo-regexp
1865 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1866 "\\|") "\\)\\>")
1867 org-not-done-regexp
1868 (concat "\\<\\("
1869 (mapconcat 'regexp-quote
1870 (nreverse (cdr (reverse org-todo-keywords)))
1871 "\\|")
1872 "\\)\\>")
1873 org-todo-line-regexp
1874 (concat "^\\(\\*+\\)[ \t]*\\("
1875 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1876 "\\)? *\\(.*\\)")
1877 org-nl-done-regexp
1878 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1879 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1880 org-deadline-regexp (concat "\\<" org-deadline-string)
1881 org-deadline-time-regexp
1882 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1883 org-deadline-line-regexp
1884 (concat "\\<\\(" org-deadline-string "\\).*")
1885 org-scheduled-regexp
1886 (concat "\\<" org-scheduled-string)
1887 org-scheduled-time-regexp
1888 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1889 (org-set-font-lock-defaults)))
1890
1891 ;; Tell the compiler about dynamically scoped variables,
1892 ;; and variables from other packages
1893 (eval-when-compile
1894 (defvar zmacs-regions)
1895 (defvar original-date)
1896 (defvar org-transient-mark-mode)
1897 (defvar org-old-auto-fill-inhibit-regexp)
1898 (defvar orgtbl-mode-menu)
1899 (defvar org-html-entities)
1900 (defvar org-goto-start-pos)
1901 (defvar org-cursor-color)
1902 (defvar org-time-was-given)
1903 (defvar org-ts-what)
1904 (defvar mark-active)
1905 (defvar timecnt)
1906 (defvar levels-open)
1907 (defvar title)
1908 (defvar author)
1909 (defvar email)
1910 (defvar text)
1911 (defvar entry)
1912 (defvar date)
1913 (defvar language)
1914 (defvar options)
1915 (defvar ans1)
1916 (defvar ans2)
1917 (defvar starting-day)
1918 (defvar include-all-loc)
1919 (defvar vm-message-pointer)
1920 (defvar vm-folder-directory)
1921 (defvar wl-summary-buffer-elmo-folder)
1922 (defvar wl-summary-buffer-folder-name)
1923 (defvar gnus-group-name)
1924 (defvar gnus-article-current)
1925 (defvar w3m-current-url)
1926 (defvar org-selected-point)
1927 (defvar calendar-mode-map)
1928 (defvar remember-save-after-remembering)
1929 (defvar remember-data-file))
1930
1931
1932 ;;; Define the mode
1933
1934 (defvar org-mode-map (copy-keymap outline-mode-map)
1935 "Keymap for Org-mode.")
1936
1937 (defvar org-struct-menu)
1938 (defvar org-org-menu)
1939 (defvar org-tbl-menu)
1940
1941 ;; We use a before-change function to check if a table might need
1942 ;; an update.
1943 (defvar org-table-may-need-update t
1944 "Indicates of a table might need an update.
1945 This variable is set by `org-before-change-function'. `org-table-align'
1946 sets it back to nil.")
1947 (defvar org-mode-hook nil)
1948 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1950
1951
1952 ;;;###autoload
1953 (define-derived-mode org-mode outline-mode "Org"
1954 "Outline-based notes management and organizer, alias
1955 \"Carstens outline-mode for keeping track of everything.\"
1956
1957 Org-mode develops organizational tasks around a NOTES file which
1958 contains information about projects as plain text. Org-mode is
1959 implemented on top of outline-mode, which is ideal to keep the content
1960 of large files well structured. It supports ToDo items, deadlines and
1961 time stamps, which magically appear in the diary listing of the Emacs
1962 calendar. Tables are easily created with a built-in table editor.
1963 Plain text URL-like links connect to websites, emails (VM), Usenet
1964 messages (Gnus), BBDB entries, and any files related to the project.
1965 For printing and sharing of notes, an Org-mode file (or a part of it)
1966 can be exported as a structured ASCII or HTML file.
1967
1968 The following commands are available:
1969
1970 \\{org-mode-map}"
1971 (easy-menu-add org-org-menu)
1972 (easy-menu-add org-tbl-menu)
1973 (org-install-agenda-files-menu)
1974 (setq outline-regexp "\\*+")
1975 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1976 (setq outline-level 'org-outline-level)
1977 (if org-startup-truncated (setq truncate-lines t))
1978 (org-set-regexps-and-options)
1979 (set (make-local-variable 'font-lock-unfontify-region-function)
1980 'org-unfontify-region)
1981 ;; Activate before-change-function
1982 (set (make-local-variable 'org-table-may-need-update) t)
1983 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1984 (add-hook 'before-change-functions 'org-before-change-function nil
1985 'local)
1986 ;; FIXME: The following does not work because isearch-mode-end-hook
1987 ;; is called *before* the visibility overlays as removed.
1988 ;; There should be another hook then for me to be used.
1989 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1990 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1991 ;; 'local)
1992 ;; Paragraphs and auto-filling
1993 (org-set-autofill-regexps)
1994 ;; Settings for Calc embedded mode
1995 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1996 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1997 (if (and org-insert-mode-line-in-empty-file
1998 (interactive-p)
1999 (= (point-min) (point-max)))
2000 (insert " -*- mode: org -*-\n\n"))
2001
2002 ;; Get rid of Outline menus, they are not needed
2003 ;; Need to do this here because define-derived-mode sets up
2004 ;; the keymap so late.
2005 (if org-xemacs-p
2006 (progn
2007 (delete-menu-item '("Headings"))
2008 (delete-menu-item '("Show"))
2009 (delete-menu-item '("Hide"))
2010 (set-menubar-dirty-flag))
2011 (define-key org-mode-map [menu-bar headings] 'undefined)
2012 (define-key org-mode-map [menu-bar hide] 'undefined)
2013 (define-key org-mode-map [menu-bar show] 'undefined))
2014
2015 (unless org-inhibit-startup
2016 (if org-startup-with-deadline-check
2017 (call-interactively 'org-check-deadlines)
2018 (cond
2019 ((eq org-startup-folded t)
2020 (org-cycle '(4)))
2021 ((eq org-startup-folded 'content)
2022 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2023 (org-cycle '(4)) (org-cycle '(4))))))))
2024
2025 (defsubst org-current-line (&optional pos)
2026 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2027
2028
2029 ;; FIXME: Do we need to copy?
2030 (defun org-string-props (string &rest properties)
2031 "Add PROPERTIES to string."
2032 (add-text-properties 0 (length string) properties string)
2033 string)
2034
2035 ;;; Font-Lock stuff
2036
2037 (defvar org-mouse-map (make-sparse-keymap))
2038 (define-key org-mouse-map
2039 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2040 (define-key org-mouse-map
2041 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2042 (when org-tab-follows-link
2043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2045 (when org-return-follows-link
2046 (define-key org-mouse-map [(return)] 'org-open-at-point)
2047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2048
2049 (require 'font-lock)
2050
2051 (defconst org-non-link-chars "\t\n\r|<>\000")
2052 (defconst org-link-regexp
2053 (if org-allow-space-in-links
2054 (concat
2055 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2056 (concat
2057 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2058 )
2059 "Regular expression for matching links.")
2060 (defconst org-link-maybe-angles-regexp
2061 (concat "<?\\(" org-link-regexp "\\)>?")
2062 "Matches a link and optionally surrounding angle brackets.")
2063 (defconst org-protected-link-regexp
2064 (concat "\000" org-link-regexp "\000")
2065 "Matches a link and optionally surrounding angle brackets.")
2066
2067 (defconst org-ts-lengths
2068 (cons (length (format-time-string (car org-time-stamp-formats)))
2069 (length (format-time-string (cdr org-time-stamp-formats))))
2070 "This holds the lengths of the two different time formats.")
2071 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2072 "Regular expression for fast time stamp matching.")
2073 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2074 "Regular expression for fast time stamp matching.")
2075 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2076 "Regular expression matching time strings for analysis.")
2077 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2078 "Regular expression matching time stamps, with groups.")
2079 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2080 "Regular expression matching a time stamp range.")
2081 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2082 org-ts-regexp "\\)?")
2083 "Regular expression matching a time stamp or time stamp range.")
2084
2085 (defun org-activate-links (limit)
2086 "Run through the buffer and add overlays to links."
2087 (if (re-search-forward org-link-regexp limit t)
2088 (progn
2089 (add-text-properties (match-beginning 0) (match-end 0)
2090 (list 'mouse-face 'highlight
2091 'keymap org-mouse-map))
2092 t)))
2093
2094 (defun org-activate-dates (limit)
2095 "Run through the buffer and add overlays to dates."
2096 (if (re-search-forward org-tsr-regexp limit t)
2097 (progn
2098 (add-text-properties (match-beginning 0) (match-end 0)
2099 (list 'mouse-face 'highlight
2100 'keymap org-mouse-map))
2101 t)))
2102
2103 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2104 "Matches CamelCase words, possibly with a star before it.")
2105 (defun org-activate-camels (limit)
2106 "Run through the buffer and add overlays to dates."
2107 (if (re-search-forward org-camel-regexp limit t)
2108 (progn
2109 (add-text-properties (match-beginning 0) (match-end 0)
2110 (list 'mouse-face 'highlight
2111 'keymap org-mouse-map))
2112 t)))
2113
2114 (defun org-activate-tags (limit)
2115 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2116 (progn
2117 (add-text-properties (match-beginning 1) (match-end 1)
2118 (list 'mouse-face 'highlight
2119 'keymap org-mouse-map))
2120 t)))
2121
2122 (defun org-font-lock-level ()
2123 (save-excursion
2124 (org-back-to-heading t)
2125 (- (match-end 0) (match-beginning 0))))
2126
2127 (defun org-outline-level ()
2128 (save-excursion
2129 (looking-at outline-regexp)
2130 (if (match-beginning 1)
2131 (+ (org-get-string-indentation (match-string 1)) 1000)
2132 (- (match-end 0) (match-beginning 0)))))
2133
2134 (defvar org-font-lock-keywords nil)
2135
2136 (defun org-set-font-lock-defaults ()
2137 (let ((org-font-lock-extra-keywords
2138 (list
2139 '(org-activate-links (0 'org-link t))
2140 '(org-activate-dates (0 'org-link t))
2141 '(org-activate-camels (0 'org-link t))
2142 '(org-activate-tags (1 'org-link t))
2143 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2144 '(1 'org-warning t))
2145 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2146 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2147 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2148 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2149 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2150 ;; (3 'bold))
2151 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2152 ;; (3 'italic))
2153 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2154 ;; (3 'underline))
2155 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2156 ; '(1 'org-warning t))
2157 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2158 "\\|" org-quote-string "\\)\\>")
2159 '(1 'org-special-keyword t))
2160 '("^#.*" (0 'font-lock-comment-face t))
2161 (if org-fontify-done-headline
2162 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2163 '(1 'org-done t) '(2 'org-headline-done t))
2164 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2165 '(1 'org-done t)))
2166 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2167 (1 'org-table t))
2168 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2169 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2170 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2171 )))
2172 (set (make-local-variable 'org-font-lock-keywords)
2173 (append
2174 (if org-noutline-p ; FIXME: I am not sure if eval will work
2175 ; on XEmacs if noutline is ever ported
2176 `((eval . (list "^\\(\\*+\\).*"
2177 ,(if org-level-color-stars-only 1 0)
2178 '(nth
2179 (% (- (match-end 1) (match-beginning 1) 1)
2180 org-n-levels)
2181 org-level-faces)
2182 nil t)))
2183 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2184 (,(if org-level-color-stars-only 2 0)
2185 (nth (% (- (match-end 2) (match-beginning 2) 1)
2186 org-n-levels)
2187 org-level-faces)
2188 nil t))))
2189 org-font-lock-extra-keywords))
2190 (set (make-local-variable 'font-lock-defaults)
2191 '(org-font-lock-keywords t nil nil backward-paragraph))
2192 (kill-local-variable 'font-lock-keywords) nil))
2193
2194 (defun org-unfontify-region (beg end &optional maybe_loudly)
2195 "Remove fontification and activation overlays from links."
2196 (font-lock-default-unfontify-region beg end)
2197 (let* ((buffer-undo-list t)
2198 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2199 (inhibit-modification-hooks t)
2200 deactivate-mark buffer-file-name buffer-file-truename)
2201 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2202
2203 ;;; Visibility cycling
2204
2205 (defvar org-cycle-global-status nil)
2206 (defvar org-cycle-subtree-status nil)
2207 (defun org-cycle (&optional arg)
2208 "Visibility cycling for Org-mode.
2209
2210 - When this function is called with a prefix argument, rotate the entire
2211 buffer through 3 states (global cycling)
2212 1. OVERVIEW: Show only top-level headlines.
2213 2. CONTENTS: Show all headlines of all levels, but no body text.
2214 3. SHOW ALL: Show everything.
2215
2216 - When point is at the beginning of a headline, rotate the subtree started
2217 by this line through 3 different states (local cycling)
2218 1. FOLDED: Only the main headline is shown.
2219 2. CHILDREN: The main headline and the direct children are shown. From
2220 this state, you can move to one of the children and
2221 zoom in further.
2222 3. SUBTREE: Show the entire subtree, including body text.
2223
2224 - When there is a numeric prefix, go up to a heading with level ARG, do
2225 a `show-subtree' and return to the previous cursor position. If ARG
2226 is negative, go up that many levels.
2227
2228 - When point is not at the beginning of a headline, execute
2229 `indent-relative', like TAB normally does. See the option
2230 `org-cycle-emulate-tab' for details.
2231
2232 - Special case: if point is the the beginning of the buffer and there is
2233 no headline in line 1, this function will act as if called with prefix arg."
2234 (interactive "P")
2235
2236 (if (or (and (bobp) (not (looking-at outline-regexp)))
2237 (equal arg '(4)))
2238 ;; special case: use global cycling
2239 (setq arg t))
2240
2241 (let ((outline-regexp
2242 (if org-cycle-include-plain-lists
2243 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2244 outline-regexp)))
2245
2246 (cond
2247
2248 ((org-at-table-p 'any)
2249 ;; Enter the table or move to the next field in the table
2250 (or (org-table-recognize-table.el)
2251 (progn
2252 (org-table-justify-field-maybe)
2253 (org-table-next-field))))
2254
2255 ((eq arg t) ;; Global cycling
2256
2257 (cond
2258 ((and (eq last-command this-command)
2259 (eq org-cycle-global-status 'overview))
2260 ;; We just created the overview - now do table of contents
2261 ;; This can be slow in very large buffers, so indicate action
2262 (message "CONTENTS...")
2263 (save-excursion
2264 ;; Visit all headings and show their offspring
2265 (goto-char (point-max))
2266 (catch 'exit
2267 (while (and (progn (condition-case nil
2268 (outline-previous-visible-heading 1)
2269 (error (goto-char (point-min))))
2270 t)
2271 (looking-at outline-regexp))
2272 (show-branches)
2273 (if (bobp) (throw 'exit nil))))
2274 (message "CONTENTS...done"))
2275 (setq org-cycle-global-status 'contents)
2276 (run-hook-with-args 'org-cycle-hook 'contents))
2277
2278 ((and (eq last-command this-command)
2279 (eq org-cycle-global-status 'contents))
2280 ;; We just showed the table of contents - now show everything
2281 (show-all)
2282 (message "SHOW ALL")
2283 (setq org-cycle-global-status 'all)
2284 (run-hook-with-args 'org-cycle-hook 'all))
2285
2286 (t
2287 ;; Default action: go to overview
2288 (hide-sublevels 1)
2289 (message "OVERVIEW")
2290 (setq org-cycle-global-status 'overview)
2291 (run-hook-with-args 'org-cycle-hook 'overview))))
2292
2293 ((integerp arg)
2294 ;; Show-subtree, ARG levels up from here.
2295 (save-excursion
2296 (org-back-to-heading)
2297 (outline-up-heading (if (< arg 0) (- arg)
2298 (- (outline-level) arg)))
2299 (org-show-subtree)))
2300
2301 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2302 ;; At a heading: rotate between three different views
2303 (org-back-to-heading)
2304 (let ((goal-column 0) eoh eol eos)
2305 ;; First, some boundaries
2306 (save-excursion
2307 (org-back-to-heading)
2308 (save-excursion
2309 (beginning-of-line 2)
2310 (while (and (not (eobp)) ;; this is like `next-line'
2311 (get-char-property (1- (point)) 'invisible))
2312 (beginning-of-line 2)) (setq eol (point)))
2313 (outline-end-of-heading) (setq eoh (point))
2314 (org-end-of-subtree t) (setq eos (point))
2315 (outline-next-heading))
2316 ;; Find out what to do next and set `this-command'
2317 (cond
2318 ((= eos eoh)
2319 ;; Nothing is hidden behind this heading
2320 (message "EMPTY ENTRY")
2321 (setq org-cycle-subtree-status nil))
2322 ((>= eol eos)
2323 ;; Entire subtree is hidden in one line: open it
2324 (org-show-entry)
2325 (show-children)
2326 (message "CHILDREN")
2327 (setq org-cycle-subtree-status 'children)
2328 (run-hook-with-args 'org-cycle-hook 'children))
2329 ((and (eq last-command this-command)
2330 (eq org-cycle-subtree-status 'children))
2331 ;; We just showed the children, now show everything.
2332 (org-show-subtree)
2333 (message "SUBTREE")
2334 (setq org-cycle-subtree-status 'subtree)
2335 (run-hook-with-args 'org-cycle-hook 'subtree))
2336 (t
2337 ;; Default action: hide the subtree.
2338 (hide-subtree)
2339 (message "FOLDED")
2340 (setq org-cycle-subtree-status 'folded)
2341 (run-hook-with-args 'org-cycle-hook 'folded)))))
2342
2343 ;; TAB emulation
2344 (buffer-read-only (org-back-to-heading))
2345 ((if (and (eq org-cycle-emulate-tab 'white)
2346 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2347 t
2348 (eq org-cycle-emulate-tab t))
2349 (if (and (looking-at "[ \n\r\t]")
2350 (string-match "^[ \t]*$" (buffer-substring
2351 (point-at-bol) (point))))
2352 (progn
2353 (beginning-of-line 1)
2354 (and (looking-at "[ \t]+") (replace-match ""))))
2355 (indent-relative))
2356
2357 (t (save-excursion
2358 (org-back-to-heading)
2359 (org-cycle))))))
2360
2361 (defun org-optimize-window-after-visibility-change (state)
2362 "Adjust the window after a change in outline visibility.
2363 This function is the default value of the hook `org-cycle-hook'."
2364 (cond
2365 ((eq state 'overview) (org-first-headline-recenter 1))
2366 ((eq state 'content) nil)
2367 ((eq state 'all) nil)
2368 ((eq state 'folded) nil)
2369 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2370 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2371
2372 (defun org-subtree-end-visible-p ()
2373 "Is the end of the current subtree visible?"
2374 (pos-visible-in-window-p
2375 (save-excursion (org-end-of-subtree t) (point))))
2376
2377 (defun org-first-headline-recenter (&optional N)
2378 "Move cursor to the first headline and recenter the headline.
2379 Optional argument N means, put the headline into the Nth line of the window."
2380 (goto-char (point-min))
2381 (when (re-search-forward (concat "^" outline-regexp) nil t)
2382 (beginning-of-line)
2383 (recenter (prefix-numeric-value N))))
2384
2385 (defvar org-goto-window-configuration nil)
2386 (defvar org-goto-marker nil)
2387 (defvar org-goto-map (make-sparse-keymap))
2388 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2389 (while (setq cmd (pop cmds))
2390 (substitute-key-definition cmd cmd org-goto-map global-map)))
2391 (define-key org-goto-map "\C-m" 'org-goto-ret)
2392 (define-key org-goto-map [(left)] 'org-goto-left)
2393 (define-key org-goto-map [(right)] 'org-goto-right)
2394 (define-key org-goto-map [(?q)] 'org-goto-quit)
2395 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2396 (define-key org-goto-map "\C-i" 'org-cycle)
2397 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2398 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2399 (define-key org-goto-map "n" 'outline-next-visible-heading)
2400 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2401 (define-key org-goto-map "f" 'outline-forward-same-level)
2402 (define-key org-goto-map "b" 'outline-backward-same-level)
2403 (define-key org-goto-map "u" 'outline-up-heading)
2404 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2405 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2406 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2407 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2408 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2409 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2410 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2411
2412 (defconst org-goto-help
2413 "Select a location to jump to, press RET
2414 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2415
2416 (defun org-goto ()
2417 "Go to a different location of the document, keeping current visibility.
2418
2419 When you want to go to a different location in a document, the fastest way
2420 is often to fold the entire buffer and then dive into the tree. This
2421 method has the disadvantage, that the previous location will be folded,
2422 which may not be what you want.
2423
2424 This command works around this by showing a copy of the current buffer in
2425 overview mode. You can dive into the tree in that copy, to find the
2426 location you want to reach. When pressing RET, the command returns to the
2427 original buffer in which the visibility is still unchanged. It then jumps
2428 to the new location, making it and the headline hierarchy above it visible."
2429 (interactive)
2430 (let* ((org-goto-start-pos (point))
2431 (selected-point
2432 (org-get-location (current-buffer) org-goto-help)))
2433 (if selected-point
2434 (progn
2435 (goto-char selected-point)
2436 (if (org-invisible-p) (org-show-hierarchy-above)))
2437 (error "Quit"))))
2438
2439 (defun org-get-location (buf help)
2440 "Let the user select a location in the Org-mode buffer BUF.
2441 This function uses a recursive edit. It returns the selected position
2442 or nil."
2443 (let (org-selected-point)
2444 (save-excursion
2445 (save-window-excursion
2446 (delete-other-windows)
2447 (switch-to-buffer (get-buffer-create "*org-goto*"))
2448 (with-output-to-temp-buffer "*Help*"
2449 (princ help))
2450 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2451 (setq buffer-read-only nil)
2452 (erase-buffer)
2453 (insert-buffer-substring buf)
2454 (let ((org-startup-truncated t)
2455 (org-startup-folded t)
2456 (org-startup-with-deadline-check nil))
2457 (org-mode))
2458 (setq buffer-read-only t)
2459 (if (boundp 'org-goto-start-pos)
2460 (goto-char org-goto-start-pos)
2461 (goto-char (point-min)))
2462 (org-beginning-of-line)
2463 (message "Select location and press RET")
2464 ;; now we make sure that during selection, ony very few keys work
2465 ;; and that it is impossible to switch to another window.
2466 (let ((gm (current-global-map))
2467 (overriding-local-map org-goto-map))
2468 (unwind-protect
2469 (progn
2470 (use-global-map org-goto-map)
2471 (recursive-edit))
2472 (use-global-map gm)))))
2473 (kill-buffer "*org-goto*")
2474 org-selected-point))
2475
2476 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2477 (defun org-goto-ret (&optional arg)
2478 "Finish org-goto by going to the new location."
2479 (interactive "P")
2480 (setq org-selected-point (point)
2481 current-prefix-arg arg)
2482 (throw 'exit nil))
2483
2484 (defun org-goto-left ()
2485 "Finish org-goto by going to the new location."
2486 (interactive)
2487 (if (org-on-heading-p)
2488 (progn
2489 (beginning-of-line 1)
2490 (setq org-selected-point (point)
2491 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2492 (throw 'exit nil))
2493 (error "Not on a heading")))
2494
2495 (defun org-goto-right ()
2496 "Finish org-goto by going to the new location."
2497 (interactive)
2498 (if (org-on-heading-p)
2499 (progn
2500 (outline-end-of-subtree)
2501 (or (eobp) (forward-char 1))
2502 (setq org-selected-point (point)
2503 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2504 (throw 'exit nil))
2505 (error "Not on a heading")))
2506
2507 (defun org-goto-quit ()
2508 "Finish org-goto without cursor motion."
2509 (interactive)
2510 (setq org-selected-point nil)
2511 (throw 'exit nil))
2512
2513 ;;; Promotion, Demotion, Inserting new headlines
2514
2515 (defvar org-ignore-region nil
2516 "To temporarily disable the active region.")
2517
2518 (defun org-insert-heading (&optional force-heading)
2519 "Insert a new heading or item with same depth at point.
2520 If ARG is non-nil"
2521 (interactive "P")
2522 (when (or force-heading (not (org-insert-item)))
2523 (let* ((head (save-excursion
2524 (condition-case nil
2525 (org-back-to-heading)
2526 (error (outline-next-heading)))
2527 (prog1 (match-string 0)
2528 (funcall outline-level)))))
2529 (unless (bolp) (newline))
2530 (insert head)
2531 (unless (eolp)
2532 (save-excursion (newline-and-indent)))
2533 (unless (equal (char-before) ?\ )
2534 (insert " "))
2535 (run-hooks 'org-insert-heading-hook))))
2536
2537 (defun org-insert-item ()
2538 "Insert a new item at the current level.
2539 Return t when tings worked, nil when we are not in an item."
2540 (when (save-excursion
2541 (condition-case nil
2542 (progn
2543 (org-beginning-of-item)
2544 (org-at-item-p)
2545 t)
2546 (error nil)))
2547 (unless (bolp) (newline))
2548 (insert (match-string 0))
2549 (org-maybe-renumber-ordered-list)
2550 t))
2551
2552 (defun org-insert-todo-heading (arg)
2553 "Insert a new heading with the same level and TODO state as current heading.
2554 If the heading has no TODO state, or if the state is DONE, use the first
2555 state (TODO by default). Also with prefix arg, force first state."
2556 (interactive "P")
2557 (org-insert-heading)
2558 (save-excursion
2559 (org-back-to-heading)
2560 (outline-previous-heading)
2561 (looking-at org-todo-line-regexp))
2562 (if (or arg
2563 (not (match-beginning 2))
2564 (equal (match-string 2) org-done-string))
2565 (insert (car org-todo-keywords) " ")
2566 (insert (match-string 2) " ")))
2567
2568 (defun org-promote-subtree ()
2569 "Promote the entire subtree.
2570 See also `org-promote'."
2571 (interactive)
2572 (save-excursion
2573 (org-map-tree 'org-promote)))
2574
2575 (defun org-demote-subtree ()
2576 "Demote the entire subtree. See `org-demote'.
2577 See also `org-promote'."
2578 (interactive)
2579 (save-excursion
2580 (org-map-tree 'org-demote)))
2581
2582 (defun org-do-promote ()
2583 "Promote the current heading higher up the tree.
2584 If the region is active in `transient-mark-mode', promote all headings
2585 in the region."
2586 (interactive)
2587 (save-excursion
2588 (if (org-region-active-p)
2589 (org-map-region 'org-promote (region-beginning) (region-end))
2590 (org-promote)))
2591 (org-fix-position-after-promote))
2592
2593 (defun org-do-demote ()
2594 "Demote the current heading lower down the tree.
2595 If the region is active in `transient-mark-mode', demote all headings
2596 in the region."
2597 (interactive)
2598 (save-excursion
2599 (if (org-region-active-p)
2600 (org-map-region 'org-demote (region-beginning) (region-end))
2601 (org-demote)))
2602 (org-fix-position-after-promote))
2603
2604 (defun org-fix-position-after-promote ()
2605 "Make sure that after pro/demotion cursor position is right."
2606 (and (equal (char-after) ?\ )
2607 (equal (char-before) ?*)
2608 (forward-char 1)))
2609
2610 (defun org-promote ()
2611 "Promote the current heading higher up the tree.
2612 If the region is active in `transient-mark-mode', promote all headings
2613 in the region."
2614 (org-back-to-heading t)
2615 (let* ((level (save-match-data (funcall outline-level)))
2616 (up-head (make-string (1- level) ?*)))
2617 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2618 (replace-match up-head nil t)
2619 ;; Fixup tag positioning
2620 (and org-auto-align-tags (org-set-tags nil t))
2621 (if org-adapt-indentation
2622 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2623
2624 (defun org-demote ()
2625 "Demote the current heading lower down the tree.
2626 If the region is active in `transient-mark-mode', demote all headings
2627 in the region."
2628 (org-back-to-heading t)
2629 (let* ((level (save-match-data (funcall outline-level)))
2630 (down-head (make-string (1+ level) ?*)))
2631 (replace-match down-head nil t)
2632 ;; Fixup tag positioning
2633 (and org-auto-align-tags (org-set-tags nil t))
2634 (if org-adapt-indentation
2635 (org-fixup-indentation "^ " " " "^\\S-"))))
2636
2637 (defun org-map-tree (fun)
2638 "Call FUN for every heading underneath the current one."
2639 (org-back-to-heading)
2640 (let ((level (outline-level)))
2641 (save-excursion
2642 (funcall fun)
2643 (while (and (progn
2644 (outline-next-heading)
2645 (> (funcall outline-level) level))
2646 (not (eobp)))
2647 (funcall fun)))))
2648
2649 (defun org-map-region (fun beg end)
2650 "Call FUN for every heading between BEG and END."
2651 (let ((org-ignore-region t))
2652 (save-excursion
2653 (setq end (copy-marker end))
2654 (goto-char beg)
2655 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2656 (< (point) end))
2657 (funcall fun))
2658 (while (and (progn
2659 (outline-next-heading)
2660 (< (point) end))
2661 (not (eobp)))
2662 (funcall fun)))))
2663
2664 (defun org-fixup-indentation (from to prohibit)
2665 "Change the indentation in the current entry by re-replacing FROM with TO.
2666 However, if the regexp PROHIBIT matches at all, don't do anything.
2667 This is being used to change indentation along with the length of the
2668 heading marker. But if there are any lines which are not indented, nothing
2669 is changed at all."
2670 (save-excursion
2671 (let ((end (save-excursion (outline-next-heading)
2672 (point-marker))))
2673 (unless (save-excursion (re-search-forward prohibit end t))
2674 (while (re-search-forward from end t)
2675 (replace-match to)
2676 (beginning-of-line 2)))
2677 (move-marker end nil))))
2678
2679 ;;; Vertical tree motion, cutting and pasting of subtrees
2680
2681 (defun org-move-subtree-up (&optional arg)
2682 "Move the current subtree up past ARG headlines of the same level."
2683 (interactive "p")
2684 (org-move-subtree-down (- (prefix-numeric-value arg))))
2685
2686 (defun org-move-subtree-down (&optional arg)
2687 "Move the current subtree down past ARG headlines of the same level."
2688 (interactive "p")
2689 (setq arg (prefix-numeric-value arg))
2690 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2691 'outline-get-last-sibling))
2692 (ins-point (make-marker))
2693 (cnt (abs arg))
2694 beg end txt folded)
2695 ;; Select the tree
2696 (org-back-to-heading)
2697 (setq beg (point))
2698 (save-match-data
2699 (save-excursion (outline-end-of-heading)
2700 (setq folded (org-invisible-p)))
2701 (outline-end-of-subtree))
2702 (outline-next-heading)
2703 (setq end (point))
2704 ;; Find insertion point, with error handling
2705 (goto-char beg)
2706 (while (> cnt 0)
2707 (or (and (funcall movfunc) (looking-at outline-regexp))
2708 (progn (goto-char beg)
2709 (error "Cannot move past superior level or buffer limit")))
2710 (setq cnt (1- cnt)))
2711 (if (> arg 0)
2712 ;; Moving forward - still need to move over subtree
2713 (progn (outline-end-of-subtree)
2714 (outline-next-heading)
2715 (if (not (or (looking-at (concat "^" outline-regexp))
2716 (bolp)))
2717 (newline))))
2718 (move-marker ins-point (point))
2719 (setq txt (buffer-substring beg end))
2720 (delete-region beg end)
2721 (insert txt)
2722 (goto-char ins-point)
2723 (if folded (hide-subtree))
2724 (move-marker ins-point nil)))
2725
2726 (defvar org-subtree-clip ""
2727 "Clipboard for cut and paste of subtrees.
2728 This is actually only a copy of the kill, because we use the normal kill
2729 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2730
2731 (defvar org-subtree-clip-folded nil
2732 "Was the last copied subtree folded?
2733 This is used to fold the tree back after pasting.")
2734
2735 (defun org-cut-subtree ()
2736 "Cut the current subtree into the clipboard.
2737 This is a short-hand for marking the subtree and then cutting it."
2738 (interactive)
2739 (org-copy-subtree 'cut))
2740
2741 (defun org-copy-subtree (&optional cut)
2742 "Cut the current subtree into the clipboard.
2743 This is a short-hand for marking the subtree and then copying it.
2744 If CUT is non nil, actually cut the subtree."
2745 (interactive)
2746 (let (beg end folded)
2747 (org-back-to-heading)
2748 (setq beg (point))
2749 (save-match-data
2750 (save-excursion (outline-end-of-heading)
2751 (setq folded (org-invisible-p)))
2752 (outline-end-of-subtree))
2753 (if (equal (char-after) ?\n) (forward-char 1))
2754 (setq end (point))
2755 (goto-char beg)
2756 (when (> end beg)
2757 (setq org-subtree-clip-folded folded)
2758 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2759 (setq org-subtree-clip (current-kill 0))
2760 (message "%s: Subtree with %d characters"
2761 (if cut "Cut" "Copied")
2762 (length org-subtree-clip)))))
2763
2764 (defun org-paste-subtree (&optional level tree)
2765 "Paste the clipboard as a subtree, with modification of headline level.
2766 The entire subtree is promoted or demoted in order to match a new headline
2767 level. By default, the new level is derived from the visible headings
2768 before and after the insertion point, and taken to be the inferior headline
2769 level of the two. So if the previous visible heading is level 3 and the
2770 next is level 4 (or vice versa), level 4 will be used for insertion.
2771 This makes sure that the subtree remains an independent subtree and does
2772 not swallow low level entries.
2773
2774 You can also force a different level, either by using a numeric prefix
2775 argument, or by inserting the heading marker by hand. For example, if the
2776 cursor is after \"*****\", then the tree will be shifted to level 5.
2777
2778 If you want to insert the tree as is, just use \\[yank].
2779
2780 If optional TREE is given, use this text instead of the kill ring."
2781 (interactive "P")
2782 (unless (org-kill-is-subtree-p tree)
2783 (error
2784 (substitute-command-keys
2785 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2786 (let* ((txt (or tree (current-kill 0)))
2787 (^re (concat "^\\(" outline-regexp "\\)"))
2788 (re (concat "\\(" outline-regexp "\\)"))
2789 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2790
2791 (old-level (if (string-match ^re txt)
2792 (- (match-end 0) (match-beginning 0))
2793 -1))
2794 (force-level (cond (level (prefix-numeric-value level))
2795 ((string-match
2796 ^re_ (buffer-substring (point-at-bol) (point)))
2797 (- (match-end 0) (match-beginning 0)))
2798 (t nil)))
2799 (previous-level (save-excursion
2800 (condition-case nil
2801 (progn
2802 (outline-previous-visible-heading 1)
2803 (if (looking-at re)
2804 (- (match-end 0) (match-beginning 0))
2805 1))
2806 (error 1))))
2807 (next-level (save-excursion
2808 (condition-case nil
2809 (progn
2810 (outline-next-visible-heading 1)
2811 (if (looking-at re)
2812 (- (match-end 0) (match-beginning 0))
2813 1))
2814 (error 1))))
2815 (new-level (or force-level (max previous-level next-level)))
2816 (shift (if (or (= old-level -1)
2817 (= new-level -1)
2818 (= old-level new-level))
2819 0
2820 (- new-level old-level)))
2821 (shift1 shift)
2822 (delta (if (> shift 0) -1 1))
2823 (func (if (> shift 0) 'org-demote 'org-promote))
2824 beg end)
2825 ;; Remove the forces level indicator
2826 (if force-level
2827 (delete-region (point-at-bol) (point)))
2828 ;; Make sure we start at the beginning of an empty line
2829 (if (not (bolp)) (insert "\n"))
2830 (if (not (looking-at "[ \t]*$"))
2831 (progn (insert "\n") (backward-char 1)))
2832 ;; Paste
2833 (setq beg (point))
2834 (insert txt)
2835 (setq end (point))
2836 (goto-char beg)
2837 ;; Shift if necessary
2838 (if (= shift 0)
2839 (message "Pasted at level %d, without shift" new-level)
2840 (save-restriction
2841 (narrow-to-region beg end)
2842 (while (not (= shift 0))
2843 (org-map-region func (point-min) (point-max))
2844 (setq shift (+ delta shift)))
2845 (goto-char (point-min))
2846 (message "Pasted at level %d, with shift by %d levels"
2847 new-level shift1)))
2848 (if (and (eq org-subtree-clip (current-kill 0))
2849 org-subtree-clip-folded)
2850 ;; The tree was folded before it was killed/copied
2851 (hide-subtree))))
2852
2853 (defun org-kill-is-subtree-p (&optional txt)
2854 "Check if the current kill is an outline subtree, or a set of trees.
2855 Returns nil if kill does not start with a headline, or if the first
2856 headline level is not the largest headline level in the tree.
2857 So this will actually accept several entries of equal levels as well,
2858 which is OK for `org-paste-subtree'.
2859 If optional TXT is given, check this string instead of the current kill."
2860 (let* ((kill (or txt (current-kill 0) ""))
2861 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2862 (- (match-end 0) (match-beginning 0))))
2863 (re (concat "^" outline-regexp))
2864 (start 1))
2865 (if (not start-level)
2866 nil ;; does not even start with a heading
2867 (catch 'exit
2868 (while (setq start (string-match re kill (1+ start)))
2869 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2870 (throw 'exit nil)))
2871 t))))
2872
2873 ;;; Plain list items
2874
2875 (defun org-at-item-p ()
2876 "Is point in a line starting a hand-formatted item?"
2877 (let ((llt org-plain-list-ordered-item-terminator))
2878 (save-excursion
2879 (goto-char (point-at-bol))
2880 (looking-at
2881 (cond
2882 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2883 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2884 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2885 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2886
2887 (defun org-get-indentation ()
2888 "Get the indentation of the current line, ionterpreting tabs."
2889 (save-excursion
2890 (beginning-of-line 1)
2891 (skip-chars-forward " \t")
2892 (current-column)))
2893
2894 (defun org-beginning-of-item ()
2895 "Go to the beginning of the current hand-formatted item.
2896 If the cursor is not in an item, throw an error."
2897 (let ((pos (point))
2898 (limit (save-excursion (org-back-to-heading)
2899 (beginning-of-line 2) (point)))
2900 ind ind1)
2901 (if (org-at-item-p)
2902 (beginning-of-line 1)
2903 (beginning-of-line 1)
2904 (skip-chars-forward " \t")
2905 (setq ind (current-column))
2906 (if (catch 'exit
2907 (while t
2908 (beginning-of-line 0)
2909 (if (< (point) limit) (throw 'exit nil))
2910 (unless (looking-at " \t]*$")
2911 (skip-chars-forward " \t")
2912 (setq ind1 (current-column))
2913 (if (< ind1 ind)
2914 (throw 'exit (org-at-item-p))))))
2915 nil
2916 (goto-char pos)
2917 (error "Not in an item")))))
2918
2919 (defun org-end-of-item ()
2920 "Go to the beginning of the current hand-formatted item.
2921 If the cursor is not in an item, throw an error."
2922 (let ((pos (point))
2923 (limit (save-excursion (outline-next-heading) (point)))
2924 (ind (save-excursion
2925 (org-beginning-of-item)
2926 (skip-chars-forward " \t")
2927 (current-column)))
2928 ind1)
2929 (if (catch 'exit
2930 (while t
2931 (beginning-of-line 2)
2932 (if (>= (point) limit) (throw 'exit t))
2933 (unless (looking-at "[ \t]*$")
2934 (skip-chars-forward " \t")
2935 (setq ind1 (current-column))
2936 (if (<= ind1 ind) (throw 'exit t)))))
2937 (beginning-of-line 1)
2938 (goto-char pos)
2939 (error "Not in an item"))))
2940
2941 (defun org-move-item-down (arg)
2942 "Move the plain list item at point down, i.e. swap with following item.
2943 Subitems (items with larger indentation are considered part of the item,
2944 so this really moves item trees."
2945 (interactive "p")
2946 (let (beg end ind ind1 (pos (point)) txt)
2947 (org-beginning-of-item)
2948 (setq beg (point))
2949 (setq ind (org-get-indentation))
2950 (org-end-of-item)
2951 (setq end (point))
2952 (setq ind1 (org-get-indentation))
2953 (if (and (org-at-item-p) (= ind ind1))
2954 (progn
2955 (org-end-of-item)
2956 (setq txt (buffer-substring beg end))
2957 (save-excursion
2958 (delete-region beg end))
2959 (setq pos (point))
2960 (insert txt)
2961 (goto-char pos)
2962 (org-maybe-renumber-ordered-list))
2963 (goto-char pos)
2964 (error "Cannot move this item further down"))))
2965
2966 (defun org-move-item-up (arg)
2967 "Move the plain list item at point up, i.e. swap with previous item.
2968 Subitems (items with larger indentation are considered part of the item,
2969 so this really moves item trees."
2970 (interactive "p")
2971 (let (beg end ind ind1 (pos (point)) txt)
2972 (org-beginning-of-item)
2973 (setq beg (point))
2974 (setq ind (org-get-indentation))
2975 (org-end-of-item)
2976 (setq end (point))
2977 (goto-char beg)
2978 (catch 'exit
2979 (while t
2980 (beginning-of-line 0)
2981 (if (looking-at "[ \t]*$")
2982 nil
2983 (if (<= (setq ind1 (org-get-indentation)) ind)
2984 (throw 'exit t)))))
2985 (condition-case nil
2986 (org-beginning-of-item)
2987 (error (goto-char beg)
2988 (error "Cannot move this item further up")))
2989 (setq ind1 (org-get-indentation))
2990 (if (and (org-at-item-p) (= ind ind1))
2991 (progn
2992 (setq txt (buffer-substring beg end))
2993 (save-excursion
2994 (delete-region beg end))
2995 (setq pos (point))
2996 (insert txt)
2997 (goto-char pos)
2998 (org-maybe-renumber-ordered-list))
2999 (goto-char pos)
3000 (error "Cannot move this item further up"))))
3001
3002 (defun org-maybe-renumber-ordered-list ()
3003 "Renumber the ordered list at point if setup allows it.
3004 This tests the user option `org-auto-renumber-ordered-lists' before
3005 doing the renumbering."
3006 (and org-auto-renumber-ordered-lists
3007 (org-at-item-p)
3008 (match-beginning 3)
3009 (org-renumber-ordered-list 1)))
3010
3011 (defun org-get-string-indentation (s)
3012 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3013 (let ((n -1) (i 0) (w tab-width) c)
3014 (catch 'exit
3015 (while (< (setq n (1+ n)) (length s))
3016 (setq c (aref s n))
3017 (cond ((= c ?\ ) (setq i (1+ i)))
3018 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3019 (t (throw 'exit t)))))
3020 i))
3021
3022 (defun org-renumber-ordered-list (arg)
3023 "Renumber an ordered plain list.
3024 Cursor neext to be in the first line of an item, the line that starts
3025 with something like \"1.\" or \"2)\"."
3026 (interactive "p")
3027 (unless (and (org-at-item-p)
3028 (match-beginning 3))
3029 (error "This is not an ordered list"))
3030 (let ((line (org-current-line))
3031 (col (current-column))
3032 (ind (org-get-string-indentation
3033 (buffer-substring (point-at-bol) (match-beginning 3))))
3034 ;; (term (substring (match-string 3) -1))
3035 ind1 (n (1- arg)))
3036 ;; find where this list begins
3037 (catch 'exit
3038 (while t
3039 (catch 'next
3040 (beginning-of-line 0)
3041 (if (looking-at "[ \t]*$") (throw 'next t))
3042 (skip-chars-forward " \t") (setq ind1 (current-column))
3043 (if (or (< ind1 ind)
3044 (and (= ind1 ind)
3045 (not (org-at-item-p))))
3046 (throw 'exit t)))))
3047 ;; Walk forward and replace these numbers
3048 (catch 'exit
3049 (while t
3050 (catch 'next
3051 (beginning-of-line 2)
3052 (if (eobp) (throw 'exit nil))
3053 (if (looking-at "[ \t]*$") (throw 'next nil))
3054 (skip-chars-forward " \t") (setq ind1 (current-column))
3055 (if (> ind1 ind) (throw 'next t))
3056 (if (< ind1 ind) (throw 'exit t))
3057 (if (not (org-at-item-p)) (throw 'exit nil))
3058 (if (not (match-beginning 3))
3059 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3060 (delete-region (match-beginning 3) (1- (match-end 3)))
3061 (goto-char (match-beginning 3))
3062 (insert (format "%d" (setq n (1+ n)))))))
3063 (goto-line line)
3064 (move-to-column col)))
3065
3066 (defvar org-last-indent-begin-marker (make-marker))
3067 (defvar org-last-indent-end-marker (make-marker))
3068
3069
3070 (defun org-outdent-item (arg)
3071 "Outdent a local list item."
3072 (interactive "p")
3073 (org-indent-item (- arg)))
3074
3075 (defun org-indent-item (arg)
3076 "Indent a local list item."
3077 (interactive "p")
3078 (unless (org-at-item-p)
3079 (error "Not on an item"))
3080 (let (beg end ind ind1)
3081 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3082 (setq beg org-last-indent-begin-marker
3083 end org-last-indent-end-marker)
3084 (org-beginning-of-item)
3085 (setq beg (move-marker org-last-indent-begin-marker (point)))
3086 (org-end-of-item)
3087 (setq end (move-marker org-last-indent-end-marker (point))))
3088 (goto-char beg)
3089 (skip-chars-forward " \t") (setq ind (current-column))
3090 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3091 (while (< (point) end)
3092 (beginning-of-line 1)
3093 (skip-chars-forward " \t") (setq ind1 (current-column))
3094 (delete-region (point-at-bol) (point))
3095 (indent-to-column (+ ind1 arg))
3096 (beginning-of-line 2))
3097 (goto-char beg)))
3098
3099 ;;; Archiving
3100
3101 (defun org-archive-subtree ()
3102 "Move the current subtree to the archive.
3103 The archive can be a certain top-level heading in the current file, or in
3104 a different file. The tree will be moved to that location, the subtree
3105 heading be marked DONE, and the current time will be added."
3106 (interactive)
3107 ;; Save all relevant TODO keyword-relatex variables
3108 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3109 (tr-org-todo-keywords org-todo-keywords)
3110 (tr-org-todo-interpretation org-todo-interpretation)
3111 (tr-org-done-string org-done-string)
3112 (tr-org-todo-regexp org-todo-regexp)
3113 (tr-org-todo-line-regexp org-todo-line-regexp)
3114 (this-buffer (current-buffer))
3115 file heading buffer level newfile-p)
3116 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3117 (progn
3118 (setq file (format (match-string 1 org-archive-location)
3119 (file-name-nondirectory (buffer-file-name)))
3120 heading (match-string 2 org-archive-location)))
3121 (error "Invalid `org-archive-location'"))
3122 (if (> (length file) 0)
3123 (setq newfile-p (not (file-exists-p file))
3124 buffer (find-file-noselect file))
3125 (setq buffer (current-buffer)))
3126 (unless buffer
3127 (error "Cannot access file \"%s\"" file))
3128 (if (and (> (length heading) 0)
3129 (string-match "^\\*+" heading))
3130 (setq level (match-end 0))
3131 (setq heading nil level 0))
3132 (save-excursion
3133 ;; We first only copy, in case something goes wrong
3134 ;; we need to protect this-command, to avoid kill-region sets it,
3135 ;; which would lead to duplication of subtrees
3136 (let (this-command) (org-copy-subtree))
3137 (set-buffer buffer)
3138 ;; Enforce org-mode for the archive buffer
3139 (if (not (eq major-mode 'org-mode))
3140 ;; Force the mode for future visits.
3141 (let ((org-insert-mode-line-in-empty-file t))
3142 (call-interactively 'org-mode)))
3143 (when newfile-p
3144 (goto-char (point-max))
3145 (insert (format "\nArchived entries from file %s\n\n"
3146 (buffer-file-name this-buffer))))
3147 ;; Force the TODO keywords of the original buffer
3148 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3149 (org-todo-keywords tr-org-todo-keywords)
3150 (org-todo-interpretation tr-org-todo-interpretation)
3151 (org-done-string tr-org-done-string)
3152 (org-todo-regexp tr-org-todo-regexp)
3153 (org-todo-line-regexp tr-org-todo-line-regexp))
3154 (goto-char (point-min))
3155 (if heading
3156 (progn
3157 (if (re-search-forward
3158 (concat "\\(^\\|\r\\)"
3159 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3160 nil t)
3161 (goto-char (match-end 0))
3162 ;; Heading not found, just insert it at the end
3163 (goto-char (point-max))
3164 (or (bolp) (insert "\n"))
3165 (insert "\n" heading "\n")
3166 (end-of-line 0))
3167 ;; Make the heading visible, and the following as well
3168 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3169 (if (re-search-forward
3170 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3171 nil t)
3172 (progn (goto-char (match-beginning 0)) (insert "\n")
3173 (beginning-of-line 0))
3174 (goto-char (point-max)) (insert "\n")))
3175 (goto-char (point-max)) (insert "\n"))
3176 ;; Paste
3177 (org-paste-subtree (1+ level))
3178 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3179 (if org-archive-mark-done
3180 (org-todo (length org-todo-keywords)))
3181 ;; Move cursor to right after the TODO keyword
3182 (when org-archive-stamp-time
3183 (beginning-of-line 1)
3184 (looking-at org-todo-line-regexp)
3185 (goto-char (or (match-end 2) (match-beginning 3)))
3186 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3187 (current-time))
3188 ")"))
3189 ;; Save the buffer, if it is not the same buffer.
3190 (if (not (eq this-buffer buffer)) (save-buffer))))
3191 ;; Here we are back in the original buffer. Everything seems to have
3192 ;; worked. So now cut the tree and finish up.
3193 (let (this-command) (org-cut-subtree))
3194 (if (looking-at "[ \t]*$") (kill-line))
3195 (message "Subtree archived %s"
3196 (if (eq this-buffer buffer)
3197 (concat "under heading: " heading)
3198 (concat "in file: " (abbreviate-file-name file))))))
3199
3200 ;;; Completion
3201
3202 (defun org-complete (&optional arg)
3203 "Perform completion on word at point.
3204 At the beginning of a headline, this completes TODO keywords as given in
3205 `org-todo-keywords'.
3206 If the current word is preceded by a backslash, completes the TeX symbols
3207 that are supported for HTML support.
3208 If the current word is preceded by \"#+\", completes special words for
3209 setting file options.
3210 At all other locations, this simply calls `ispell-complete-word'."
3211 (interactive "P")
3212 (catch 'exit
3213 (let* ((end (point))
3214 (beg1 (save-excursion
3215 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3216 (skip-chars-backward "a-zA-Z_")
3217 (point)))
3218 (beg (save-excursion
3219 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3220 (skip-chars-backward "a-zA-Z0-9_:$")
3221 (point)))
3222 (camel (equal (char-before beg) ?*))
3223 (tag (equal (char-before beg1) ?:))
3224 (texp (equal (char-before beg) ?\\))
3225 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3226 beg)
3227 "#+"))
3228 (completion-ignore-case opt)
3229 (type nil)
3230 (tbl nil)
3231 (table (cond
3232 (opt
3233 (setq type :opt)
3234 (mapcar (lambda (x)
3235 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3236 (cons (match-string 2 x) (match-string 1 x)))
3237 (org-split-string (org-get-current-options) "\n")))
3238 (texp
3239 (setq type :tex)
3240 org-html-entities)
3241 ((string-match "\\`\\*+[ \t]*\\'"
3242 (buffer-substring (point-at-bol) beg))
3243 (setq type :todo)
3244 (mapcar 'list org-todo-keywords))
3245 (camel
3246 (setq type :camel)
3247 (save-excursion
3248 (goto-char (point-min))
3249 (while (re-search-forward org-todo-line-regexp nil t)
3250 (push (list (org-make-org-heading-camel (match-string 3)))
3251 tbl)))
3252 tbl)
3253 (tag (setq type :tag beg beg1)
3254 (org-get-buffer-tags))
3255 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3256 (pattern (buffer-substring-no-properties beg end))
3257 (completion (try-completion pattern table)))
3258 (cond ((eq completion t)
3259 (if (equal type :opt)
3260 (insert (substring (cdr (assoc (upcase pattern) table))
3261 (length pattern)))))
3262 ((null completion)
3263 (message "Can't find completion for \"%s\"" pattern)
3264 (ding))
3265 ((not (string= pattern completion))
3266 (delete-region beg end)
3267 (if (string-match " +$" completion)
3268 (setq completion (replace-match "" t t completion)))
3269 (insert completion)
3270 (if (get-buffer-window "*Completions*")
3271 (delete-window (get-buffer-window "*Completions*")))
3272 (if (assoc completion table)
3273 (if (eq type :todo) (insert " ")
3274 (if (eq type :tag) (insert ":"))))
3275 (if (and (equal type :opt) (assoc completion table))
3276 (message "%s" (substitute-command-keys
3277 "Press \\[org-complete] again to insert example settings"))))
3278 (t
3279 (message "Making completion list...")
3280 (let ((list (sort (all-completions pattern table) 'string<)))
3281 (with-output-to-temp-buffer "*Completions*"
3282 (display-completion-list list)))
3283 (message "Making completion list...%s" "done"))))))
3284
3285 ;;; Comments, TODO and DEADLINE
3286
3287 (defun org-toggle-comment ()
3288 "Change the COMMENT state of an entry."
3289 (interactive)
3290 (save-excursion
3291 (org-back-to-heading)
3292 (if (looking-at (concat outline-regexp
3293 "\\( +\\<" org-comment-string "\\>\\)"))
3294 (replace-match "" t t nil 1)
3295 (if (looking-at outline-regexp)
3296 (progn
3297 (goto-char (match-end 0))
3298 (insert " " org-comment-string))))))
3299
3300 (defvar org-last-todo-state-is-todo nil
3301 "This is non-nil when the last TODO state change led to a TODO state.
3302 If the last change removed the TODO tag or switched to DONE, then
3303 this is nil.")
3304
3305 (defun org-todo (&optional arg)
3306 "Change the TODO state of an item.
3307 The state of an item is given by a keyword at the start of the heading,
3308 like
3309 *** TODO Write paper
3310 *** DONE Call mom
3311
3312 The different keywords are specified in the variable `org-todo-keywords'. By
3313 default the available states are \"TODO\" and \"DONE\".
3314 So for this example: when the item starts with TODO, it is changed to DONE.
3315 When it starts with DONE, the DONE is removed. And when neither TODO nor
3316 DONE are present, add TODO at the beginning of the heading.
3317
3318 With prefix arg, use completion to determined the new state. With numeric
3319 prefix arg, switch to that state."
3320 (interactive "P")
3321 (save-excursion
3322 (org-back-to-heading)
3323 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3324 (or (looking-at (concat " +" org-todo-regexp " *"))
3325 (looking-at " *"))
3326 (let* ((this (match-string 1))
3327 (completion-ignore-case t)
3328 (member (member this org-todo-keywords))
3329 (tail (cdr member))
3330 (state (cond
3331 ((equal arg '(4))
3332 ;; Read a state with completion
3333 (completing-read "State: " (mapcar (lambda(x) (list x))
3334 org-todo-keywords)
3335 nil t))
3336 ((eq arg 'right)
3337 (if this
3338 (if tail (car tail) nil)
3339 (car org-todo-keywords)))
3340 ((eq arg 'left)
3341 (if (equal member org-todo-keywords)
3342 nil
3343 (if this
3344 (nth (- (length org-todo-keywords) (length tail) 2)
3345 org-todo-keywords)
3346 org-done-string)))
3347 (arg
3348 ;; user requests a specific state
3349 (nth (1- (prefix-numeric-value arg))
3350 org-todo-keywords))
3351 ((null member) (car org-todo-keywords))
3352 ((null tail) nil) ;; -> first entry
3353 ((eq org-todo-interpretation 'sequence)
3354 (car tail))
3355 ((memq org-todo-interpretation '(type priority))
3356 (if (eq this-command last-command)
3357 (car tail)
3358 (if (> (length tail) 0) org-done-string nil)))
3359 (t nil)))
3360 (next (if state (concat " " state " ") " ")))
3361 (replace-match next t t)
3362 (setq org-last-todo-state-is-todo
3363 (not (equal state org-done-string)))
3364 (when org-log-done
3365 (if (equal state org-done-string)
3366 (org-log-done)
3367 (if (not this)
3368 (org-log-done t))))
3369 ;; Fixup tag positioning
3370 (and org-auto-align-tags (org-set-tags nil t))
3371 (run-hooks 'org-after-todo-state-change-hook)))
3372 ;; Fixup cursor location if close to the keyword
3373 (if (and (outline-on-heading-p)
3374 (not (bolp))
3375 (save-excursion (beginning-of-line 1)
3376 (looking-at org-todo-line-regexp))
3377 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3378 (progn
3379 (goto-char (or (match-end 2) (match-end 1)))
3380 (just-one-space))))
3381
3382 (defun org-log-done (&optional undone)
3383 "Add a time stamp logging that a TODO entry has been closed.
3384 When UNDONE is non-nil, remove such a time stamg again."
3385 (interactive)
3386 (let (beg end col)
3387 (save-excursion
3388 (org-back-to-heading t)
3389 (setq beg (point))
3390 (looking-at (concat outline-regexp " *"))
3391 (goto-char (match-end 0))
3392 (setq col (current-column))
3393 (outline-next-heading)
3394 (setq end (point))
3395 (goto-char beg)
3396 (when (re-search-forward (concat
3397 "[\r\n]\\([ \t]*"
3398 (regexp-quote org-closed-string)
3399 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3400 (delete-region (match-beginning 1) (match-end 1)))
3401 (unless undone
3402 (org-back-to-heading t)
3403 (skip-chars-forward "^\n\r")
3404 (goto-char (min (1+ (point)) (point-max)))
3405 (when (not (member (char-before) '(?\r ?\n)))
3406 (insert "\n"))
3407 (indent-to col)
3408 (insert org-closed-string " "
3409 (format-time-string
3410 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3411 (current-time))
3412 "\n")))))
3413
3414 (defun org-show-todo-tree (arg)
3415 "Make a compact tree which shows all headlines marked with TODO.
3416 The tree will show the lines where the regexp matches, and all higher
3417 headlines above the match.
3418 With \\[universal-argument] prefix, also show the DONE entries.
3419 With a numeric prefix N, construct a sparse tree for the Nth element
3420 of `org-todo-keywords'."
3421 (interactive "P")
3422 (let ((case-fold-search nil)
3423 (kwd-re
3424 (cond ((null arg) org-not-done-regexp)
3425 ((equal arg '(4)) org-todo-regexp)
3426 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3427 (regexp-quote (nth (1- (prefix-numeric-value arg))
3428 org-todo-keywords)))
3429 (t (error "Invalid prefix argument: %s" arg)))))
3430 (message "%d TODO entries found"
3431 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3432
3433 (defun org-deadline ()
3434 "Insert the DEADLINE: string to make a deadline.
3435 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3436 to modify it to the correct date."
3437 (interactive)
3438 (insert
3439 org-deadline-string " "
3440 (format-time-string (car org-time-stamp-formats)
3441 (org-read-date nil 'to-time)))
3442 (message "%s" (substitute-command-keys
3443 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3444
3445 (defun org-schedule ()
3446 "Insert the SCHEDULED: string to schedule a TODO item.
3447 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3448 to modify it to the correct date."
3449 (interactive)
3450 (insert
3451 org-scheduled-string " "
3452 (format-time-string (car org-time-stamp-formats)
3453 (org-read-date nil 'to-time)))
3454 (message "%s" (substitute-command-keys
3455 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3456
3457
3458 (defun org-occur (regexp &optional callback)
3459 "Make a compact tree which shows all matches of REGEXP.
3460 The tree will show the lines where the regexp matches, and all higher
3461 headlines above the match. It will also show the heading after the match,
3462 to make sure editing the matching entry is easy.
3463 if CALLBACK is non-nil, it is a function which is called to confirm
3464 that the match should indeed be shown."
3465 (interactive "sRegexp: ")
3466 (org-remove-occur-highlights nil nil t)
3467 (setq regexp (org-check-occur-regexp regexp))
3468 (let ((cnt 0))
3469 (save-excursion
3470 (goto-char (point-min))
3471 (hide-sublevels 1)
3472 (while (re-search-forward regexp nil t)
3473 (when (or (not callback)
3474 (save-match-data (funcall callback)))
3475 (setq cnt (1+ cnt))
3476 (org-highlight-new-match (match-beginning 0) (match-end 0))
3477 (org-show-hierarchy-above))))
3478 (make-local-hook 'before-change-functions) ; needed for XEmacs
3479 (add-hook 'before-change-functions 'org-remove-occur-highlights
3480 nil 'local)
3481 (run-hooks 'org-occur-hook)
3482 (if (interactive-p)
3483 (message "%d match(es) for regexp %s" cnt regexp))
3484 cnt))
3485
3486 (defun org-show-hierarchy-above ()
3487 "Make sure point and the headings hierarchy above is visible."
3488 (catch 'exit
3489 (if (org-on-heading-p t)
3490 (org-flag-heading nil) ; only show the heading
3491 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3492 (save-excursion
3493 (and org-show-following-heading
3494 (outline-next-heading)
3495 (org-flag-heading nil))) ; show the next heading
3496 (when org-show-hierarchy-above
3497 (save-excursion ; show all higher headings
3498 (while (and (condition-case nil
3499 (progn (org-up-heading-all 1) t)
3500 (error nil))
3501 (not (bobp)))
3502 (org-flag-heading nil))))))
3503
3504 ;; Overlay compatibility functions
3505 (defun org-make-overlay (beg end &optional buffer)
3506 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3507 (defun org-delete-overlay (ovl)
3508 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3509 (defun org-detatch-overlay (ovl)
3510 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3511 (defun org-move-overlay (ovl beg end &optional buffer)
3512 (if org-xemacs-p
3513 (set-extent-endpoints ovl beg end buffer)
3514 (move-overlay ovl beg end buffer)))
3515 (defun org-overlay-put (ovl prop value)
3516 (if org-xemacs-p
3517 (set-extent-property ovl prop value)
3518 (overlay-put ovl prop value)))
3519
3520 (defvar org-occur-highlights nil)
3521 (defun org-highlight-new-match (beg end)
3522 "Highlight from BEG to END and mark the highlight is an occur headline."
3523 (let ((ov (org-make-overlay beg end)))
3524 (org-overlay-put ov 'face 'secondary-selection)
3525 (push ov org-occur-highlights)))
3526
3527 (defun org-remove-occur-highlights (&optional beg end noremove)
3528 "Remove the occur highlights from the buffer.
3529 BEG and END are ignored. If NOREMOVE is nil, remove this function
3530 from the before-change-functions in the current buffer."
3531 (interactive)
3532 (mapc 'org-delete-overlay org-occur-highlights)
3533 (setq org-occur-highlights nil)
3534 (unless noremove
3535 (remove-hook 'before-change-functions
3536 'org-remove-occur-highlights 'local)))
3537
3538 ;;; Priorities
3539
3540 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3541 "Regular expression matching the priority indicator.")
3542
3543 (defvar org-remove-priority-next-time nil)
3544
3545 (defun org-priority-up ()
3546 "Increase the priority of the current item."
3547 (interactive)
3548 (org-priority 'up))
3549
3550 (defun org-priority-down ()
3551 "Decrease the priority of the current item."
3552 (interactive)
3553 (org-priority 'down))
3554
3555 (defun org-priority (&optional action)
3556 "Change the priority of an item by ARG.
3557 ACTION can be set, up, or down."
3558 (interactive)
3559 (setq action (or action 'set))
3560 (let (current new news have remove)
3561 (save-excursion
3562 (org-back-to-heading)
3563 (if (looking-at org-priority-regexp)
3564 (setq current (string-to-char (match-string 2))
3565 have t)
3566 (setq current org-default-priority))
3567 (cond
3568 ((eq action 'set)
3569 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3570 (setq new (read-char-exclusive))
3571 (cond ((equal new ?\ ) (setq remove t))
3572 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3573 (error "Priority must be between `%c' and `%c'"
3574 ?A org-lowest-priority))))
3575 ((eq action 'up)
3576 (setq new (1- current)))
3577 ((eq action 'down)
3578 (setq new (1+ current)))
3579 (t (error "Invalid action")))
3580 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3581 (setq news (format "%c" new))
3582 (if have
3583 (if remove
3584 (replace-match "" t t nil 1)
3585 (replace-match news t t nil 2))
3586 (if remove
3587 (error "No priority cookie found in line")
3588 (looking-at org-todo-line-regexp)
3589 (if (match-end 2)
3590 (progn
3591 (goto-char (match-end 2))
3592 (insert " [#" news "]"))
3593 (goto-char (match-beginning 3))
3594 (insert "[#" news "] ")))))
3595 (if remove
3596 (message "Priority removed")
3597 (message "Priority of current item set to %s" news))))
3598
3599
3600 (defun org-get-priority (s)
3601 "Find priority cookie and return priority."
3602 (save-match-data
3603 (if (not (string-match org-priority-regexp s))
3604 (* 1000 (- org-lowest-priority org-default-priority))
3605 (* 1000 (- org-lowest-priority
3606 (string-to-char (match-string 2 s)))))))
3607
3608 ;;; Timestamps
3609
3610 (defvar org-last-changed-timestamp nil)
3611
3612 (defun org-time-stamp (arg)
3613 "Prompt for a date/time and insert a time stamp.
3614 If the user specifies a time like HH:MM, or if this command is called
3615 with a prefix argument, the time stamp will contain date and time.
3616 Otherwise, only the date will be included. All parts of a date not
3617 specified by the user will be filled in from the current date/time.
3618 So if you press just return without typing anything, the time stamp
3619 will represent the current date/time. If there is already a timestamp
3620 at the cursor, it will be modified."
3621 (interactive "P")
3622 (let ((fmt (if arg (cdr org-time-stamp-formats)
3623 (car org-time-stamp-formats)))
3624 (org-time-was-given nil)
3625 time)
3626 (cond
3627 ((and (org-at-timestamp-p)
3628 (eq last-command 'org-time-stamp)
3629 (eq this-command 'org-time-stamp))
3630 (insert "--")
3631 (setq time (let ((this-command this-command))
3632 (org-read-date arg 'totime)))
3633 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3634 (insert (format-time-string fmt time)))
3635 ((org-at-timestamp-p)
3636 (setq time (let ((this-command this-command))
3637 (org-read-date arg 'totime)))
3638 (and (org-at-timestamp-p) (replace-match
3639 (setq org-last-changed-timestamp
3640 (format-time-string fmt time))
3641 t t))
3642 (message "Timestamp updated"))
3643 (t
3644 (setq time (let ((this-command this-command))
3645 (org-read-date arg 'totime)))
3646 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3647 (insert (format-time-string fmt time))))))
3648
3649 (defun org-time-stamp-inactive (&optional arg)
3650 "Insert an inactive time stamp.
3651 An inactive time stamp is enclosed in square brackets instead of angle
3652 brackets. It is inactive in the sense that it does not trigger agenda entries,
3653 does not link to the calendar and cannot be changed with the S-cursor keys.
3654 So these are more for recording a certain time/date."
3655 ;; FIXME: Would it be better not to ask for a date/time here?
3656 (interactive "P")
3657 (let ((fmt (if arg (cdr org-time-stamp-formats)
3658 (car org-time-stamp-formats)))
3659 (org-time-was-given nil)
3660 time)
3661 (setq time (org-read-date arg 'totime))
3662 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3663 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3664 (insert (format-time-string fmt time))))
3665
3666 (defvar org-date-ovl (org-make-overlay 1 1))
3667 (org-overlay-put org-date-ovl 'face 'org-warning)
3668 (org-detatch-overlay org-date-ovl)
3669
3670 ;;; FIXME: Make the function take "Fri" as "next friday"
3671 ;;; because these are mostly being used to record the current time.
3672 (defun org-read-date (&optional with-time to-time)
3673 "Read a date and make things smooth for the user.
3674 The prompt will suggest to enter an ISO date, but you can also enter anything
3675 which will at least partially be understood by `parse-time-string'.
3676 Unrecognized parts of the date will default to the current day, month ,year,
3677 hour and minute. For example,
3678 3-2-5 --> 2003-02-05
3679 feb 15 --> currentyear-02-15
3680 sep 12 9 --> 2009-09-12
3681 12:45 --> today 12:45
3682 22 sept 0:34 --> currentyear-09-22 0:34
3683 12 --> currentyear-currentmonth-12
3684 etc.
3685 The function understands only English month and weekday abbreviations,
3686 but this can be configured with the variables `parse-time-months' and
3687 `parse-time-weekdays'.
3688
3689 While prompting, a calendar is popped up - you can also select the
3690 date with the mouse (button 1). The calendar shows a period of three
3691 month. To scroll it to other months, use the keys `>' and `<'.
3692 If you don't like the calendar, turn it off with
3693 \(setq org-popup-calendar-for-date-prompt nil).
3694
3695 With optional argument TO-TIME, the date will immediately be converted
3696 to an internal time.
3697 With an optional argument WITH-TIME, the prompt will suggest to also
3698 insert a time. Note that when WITH-TIME is not set, you can still
3699 enter a time, and this function will inform the calling routine about
3700 this change. The calling routine may then choose to change the format
3701 used to insert the time stamp into the buffer to include the time."
3702 (let* ((default-time
3703 ;; Default time is either today, or, when entering a range,
3704 ;; the range start.
3705 (if (save-excursion
3706 (re-search-backward
3707 (concat org-ts-regexp "--\\=")
3708 (- (point) 20) t))
3709 (apply
3710 'encode-time
3711 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3712 (parse-time-string (match-string 1))))
3713 (current-time)))
3714 (calendar-move-hook nil)
3715 (view-diary-entries-initially nil)
3716 (timestr (format-time-string
3717 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3718 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3719 ans ans1 ans2
3720 second minute hour day month year tl)
3721
3722 (if org-popup-calendar-for-date-prompt
3723 ;; Also show a calendar for date selection
3724 ;; Copied (with modifications) from planner.el by John Wiegley
3725 (save-excursion
3726 (save-window-excursion
3727 (calendar)
3728 (calendar-forward-day (- (time-to-days default-time)
3729 (calendar-absolute-from-gregorian
3730 (calendar-current-date))))
3731 (org-eval-in-calendar nil)
3732 (let* ((old-map (current-local-map))
3733 (map (copy-keymap calendar-mode-map))
3734 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3735 (define-key map (kbd "RET") 'org-calendar-select)
3736 (define-key map (if org-xemacs-p [button1] [mouse-1])
3737 'org-calendar-select-mouse)
3738 (define-key map (if org-xemacs-p [button2] [mouse-2])
3739 'org-calendar-select-mouse)
3740 (define-key minibuffer-local-map [(meta shift left)]
3741 (lambda () (interactive)
3742 (org-eval-in-calendar '(calendar-backward-month 1))))
3743 (define-key minibuffer-local-map [(meta shift right)]
3744 (lambda () (interactive)
3745 (org-eval-in-calendar '(calendar-forward-month 1))))
3746 (define-key minibuffer-local-map [(shift up)]
3747 (lambda () (interactive)
3748 (org-eval-in-calendar '(calendar-backward-week 1))))
3749 (define-key minibuffer-local-map [(shift down)]
3750 (lambda () (interactive)
3751 (org-eval-in-calendar '(calendar-forward-week 1))))
3752 (define-key minibuffer-local-map [(shift left)]
3753 (lambda () (interactive)
3754 (org-eval-in-calendar '(calendar-backward-day 1))))
3755 (define-key minibuffer-local-map [(shift right)]
3756 (lambda () (interactive)
3757 (org-eval-in-calendar '(calendar-forward-day 1))))
3758 (define-key minibuffer-local-map ">"
3759 (lambda () (interactive)
3760 (org-eval-in-calendar '(scroll-calendar-left 1))))
3761 (define-key minibuffer-local-map "<"
3762 (lambda () (interactive)
3763 (org-eval-in-calendar '(scroll-calendar-right 1))))
3764 (unwind-protect
3765 (progn
3766 (use-local-map map)
3767 (setq ans (read-string prompt "" nil nil))
3768 (setq ans (or ans1 ans2 ans)))
3769 (use-local-map old-map)))))
3770 ;; Naked prompt only
3771 (setq ans (read-string prompt "" nil timestr)))
3772 (org-detatch-overlay org-date-ovl)
3773
3774 (if (string-match
3775 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3776 (progn
3777 (setq year (if (match-end 2)
3778 (string-to-number (match-string 2 ans))
3779 (string-to-number (format-time-string "%Y")))
3780 month (string-to-number (match-string 3 ans))
3781 day (string-to-number (match-string 4 ans)))
3782 (if (< year 100) (setq year (+ 2000 year)))
3783 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3784 t t ans))))
3785 (setq tl (parse-time-string ans)
3786 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3787 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3788 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3789 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3790 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3791 second (or (nth 0 tl) 0))
3792 (if (and (boundp 'org-time-was-given)
3793 (nth 2 tl))
3794 (setq org-time-was-given t))
3795 (if (< year 100) (setq year (+ 2000 year)))
3796 (if to-time
3797 (encode-time second minute hour day month year)
3798 (if (or (nth 1 tl) (nth 2 tl))
3799 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3800 (format "%04d-%02d-%02d" year month day)))))
3801
3802 (defun org-eval-in-calendar (form)
3803 "Eval FORM in the calendar window and return to current window.
3804 Also, store the cursor date in variable ans2."
3805 (let ((sw (selected-window)))
3806 (select-window (get-buffer-window "*Calendar*"))
3807 (eval form)
3808 (when (calendar-cursor-to-date)
3809 (let* ((date (calendar-cursor-to-date))
3810 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3811 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3812 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3813 (select-window sw)))
3814
3815 (defun org-calendar-select ()
3816 "Return to `org-read-date' with the date currently selected.
3817 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3818 (interactive)
3819 (when (calendar-cursor-to-date)
3820 (let* ((date (calendar-cursor-to-date))
3821 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3822 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3823 (if (active-minibuffer-window) (exit-minibuffer))))
3824
3825 (defun org-calendar-select-mouse (ev)
3826 "Return to `org-read-date' with the date currently selected.
3827 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3828 (interactive "e")
3829 (mouse-set-point ev)
3830 (when (calendar-cursor-to-date)
3831 (let* ((date (calendar-cursor-to-date))
3832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3833 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3834 (if (active-minibuffer-window) (exit-minibuffer))))
3835
3836 (defun org-check-deadlines (ndays)
3837 "Check if there are any deadlines due or past due.
3838 A deadline is considered due if it happens within `org-deadline-warning-days'
3839 days from today's date. If the deadline appears in an entry marked DONE,
3840 it is not shown. The prefix arg NDAYS can be used to test that many
3841 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3842 (interactive "P")
3843 (let* ((org-warn-days
3844 (cond
3845 ((equal ndays '(4)) 100000)
3846 (ndays (prefix-numeric-value ndays))
3847 (t org-deadline-warning-days)))
3848 (case-fold-search nil)
3849 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3850 (callback
3851 (lambda ()
3852 (and (let ((d1 (time-to-days (current-time)))
3853 (d2 (time-to-days
3854 (org-time-string-to-time (match-string 1)))))
3855 (< (- d2 d1) org-warn-days))
3856 (not (org-entry-is-done-p))))))
3857 (message "%d deadlines past-due or due within %d days"
3858 (org-occur regexp callback)
3859 org-warn-days)))
3860
3861 (defun org-evaluate-time-range (&optional to-buffer)
3862 "Evaluate a time range by computing the difference between start and end.
3863 Normally the result is just printed in the echo area, but with prefix arg
3864 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3865 If the time range is actually in a table, the result is inserted into the
3866 next column.
3867 For time difference computation, a year is assumed to be exactly 365
3868 days in order to avoid rounding problems."
3869 (interactive "P")
3870 (save-excursion
3871 (unless (org-at-date-range-p)
3872 (goto-char (point-at-bol))
3873 (re-search-forward org-tr-regexp (point-at-eol) t))
3874 (if (not (org-at-date-range-p))
3875 (error "Not at a time-stamp range, and none found in current line")))
3876 (let* ((ts1 (match-string 1))
3877 (ts2 (match-string 2))
3878 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3879 (match-end (match-end 0))
3880 (time1 (org-time-string-to-time ts1))
3881 (time2 (org-time-string-to-time ts2))
3882 (t1 (time-to-seconds time1))
3883 (t2 (time-to-seconds time2))
3884 (diff (abs (- t2 t1)))
3885 (negative (< (- t2 t1) 0))
3886 ;; (ys (floor (* 365 24 60 60)))
3887 (ds (* 24 60 60))
3888 (hs (* 60 60))
3889 (fy "%dy %dd %02d:%02d")
3890 (fy1 "%dy %dd")
3891 (fd "%dd %02d:%02d")
3892 (fd1 "%dd")
3893 (fh "%02d:%02d")
3894 y d h m align)
3895 ;; FIXME: Should I re-introduce years, make year refer to same date?
3896 ;; This would be the only useful way to have years, actually.
3897 (if havetime
3898 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3899 y 0
3900 d (floor (/ diff ds)) diff (mod diff ds)
3901 h (floor (/ diff hs)) diff (mod diff hs)
3902 m (floor (/ diff 60)))
3903 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3904 y 0
3905 d (floor (+ (/ diff ds) 0.5))
3906 h 0 m 0))
3907 (if (not to-buffer)
3908 (message (org-make-tdiff-string y d h m))
3909 (when (org-at-table-p)
3910 (goto-char match-end)
3911 (setq align t)
3912 (and (looking-at " *|") (goto-char (match-end 0))))
3913 (if (looking-at
3914 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3915 (replace-match ""))
3916 (if negative (insert " -"))
3917 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3918 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3919 (insert " " (format fh h m))))
3920 (if align (org-table-align))
3921 (message "Time difference inserted"))))
3922
3923 (defun org-make-tdiff-string (y d h m)
3924 (let ((fmt "")
3925 (l nil))
3926 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3927 l (push y l)))
3928 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3929 l (push d l)))
3930 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3931 l (push h l)))
3932 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3933 l (push m l)))
3934 (apply 'format fmt (nreverse l))))
3935
3936 (defun org-time-string-to-time (s)
3937 (apply 'encode-time (org-parse-time-string s)))
3938
3939 (defun org-parse-time-string (s &optional nodefault)
3940 "Parse the standard Org-mode time string.
3941 This should be a lot faster than the normal `parse-time-string'.
3942 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3943 hour and minute fields will be nil if not given."
3944 (if (string-match org-ts-regexp1 s)
3945 (list 0
3946 (if (or (match-beginning 8) (not nodefault))
3947 (string-to-number (or (match-string 8 s) "0")))
3948 (if (or (match-beginning 7) (not nodefault))
3949 (string-to-number (or (match-string 7 s) "0")))
3950 (string-to-number (match-string 4 s))
3951 (string-to-number (match-string 3 s))
3952 (string-to-number (match-string 2 s))
3953 nil nil nil)
3954 (make-list 9 0)))
3955
3956 (defun org-timestamp-up (&optional arg)
3957 "Increase the date item at the cursor by one.
3958 If the cursor is on the year, change the year. If it is on the month or
3959 the day, change that.
3960 With prefix ARG, change by that many units."
3961 (interactive "p")
3962 (org-timestamp-change (prefix-numeric-value arg)))
3963
3964 (defun org-timestamp-down (&optional arg)
3965 "Decrease the date item at the cursor by one.
3966 If the cursor is on the year, change the year. If it is on the month or
3967 the day, change that.
3968 With prefix ARG, change by that many units."
3969 (interactive "p")
3970 (org-timestamp-change (- (prefix-numeric-value arg))))
3971
3972 (defun org-timestamp-up-day (&optional arg)
3973 "Increase the date in the time stamp by one day.
3974 With prefix ARG, change that many days."
3975 (interactive "p")
3976 (if (and (not (org-at-timestamp-p))
3977 (org-on-heading-p))
3978 (org-todo 'up)
3979 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3980
3981 (defun org-timestamp-down-day (&optional arg)
3982 "Decrease the date in the time stamp by one day.
3983 With prefix ARG, change that many days."
3984 (interactive "p")
3985 (if (and (not (org-at-timestamp-p))
3986 (org-on-heading-p))
3987 (org-todo 'down)
3988 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3989
3990 (defsubst org-pos-in-match-range (pos n)
3991 (and (match-beginning n)
3992 (<= (match-beginning n) pos)
3993 (>= (match-end n) pos)))
3994
3995 (defun org-at-timestamp-p ()
3996 "Determine if the cursor is in or at a timestamp."
3997 (interactive)
3998 (let* ((tsr org-ts-regexp2)
3999 (pos (point))
4000 (ans (or (looking-at tsr)
4001 (save-excursion
4002 (skip-chars-backward "^<\n\r\t")
4003 (if (> (point) 1) (backward-char 1))
4004 (and (looking-at tsr)
4005 (> (- (match-end 0) pos) -1))))))
4006 (and (boundp 'org-ts-what)
4007 (setq org-ts-what
4008 (cond
4009 ((org-pos-in-match-range pos 2) 'year)
4010 ((org-pos-in-match-range pos 3) 'month)
4011 ((org-pos-in-match-range pos 7) 'hour)
4012 ((org-pos-in-match-range pos 8) 'minute)
4013 ((or (org-pos-in-match-range pos 4)
4014 (org-pos-in-match-range pos 5)) 'day)
4015 (t 'day))))
4016 ans))
4017
4018 (defun org-timestamp-change (n &optional what)
4019 "Change the date in the time stamp at point.
4020 The date will be changed by N times WHAT. WHAT can be `day', `month',
4021 `year', `minute', `second'. If WHAT is not given, the cursor position
4022 in the timestamp determines what will be changed."
4023 (let ((fmt (car org-time-stamp-formats))
4024 org-ts-what
4025 (pos (point))
4026 ts time time0)
4027 (if (not (org-at-timestamp-p))
4028 (error "Not at a timestamp"))
4029 (setq org-ts-what (or what org-ts-what))
4030 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4031 (- (match-end 0) (match-beginning 0))))
4032 1)
4033 (cdr org-time-stamp-formats)
4034 (car org-time-stamp-formats)))
4035 (setq ts (match-string 0))
4036 (replace-match "")
4037 (setq time0 (org-parse-time-string ts))
4038 (setq time
4039 (apply 'encode-time
4040 (append
4041 (list (or (car time0) 0))
4042 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4043 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4044 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4045 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4046 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4047 (nthcdr 6 time0))))
4048 (if (eq what 'calendar)
4049 (let ((cal-date
4050 (save-excursion
4051 (save-match-data
4052 (set-buffer "*Calendar*")
4053 (calendar-cursor-to-date)))))
4054 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4055 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4056 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4057 (setcar time0 (or (car time0) 0))
4058 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4059 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4060 (setq time (apply 'encode-time time0))))
4061 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4062 (goto-char pos)
4063 ;; Try to recenter the calendar window, if any
4064 (if (and org-calendar-follow-timestamp-change
4065 (get-buffer-window "*Calendar*" t)
4066 (memq org-ts-what '(day month year)))
4067 (org-recenter-calendar (time-to-days time)))))
4068
4069 (defun org-recenter-calendar (date)
4070 "If the calendar is visible, recenter it to DATE."
4071 (let* ((win (selected-window))
4072 (cwin (get-buffer-window "*Calendar*" t))
4073 (calendar-move-hook nil))
4074 (when cwin
4075 (select-window cwin)
4076 (calendar-goto-date (if (listp date) date
4077 (calendar-gregorian-from-absolute date)))
4078 (select-window win))))
4079
4080 (defun org-goto-calendar (&optional arg)
4081 "Go to the Emacs calendar at the current date.
4082 If there is a time stamp in the current line, go to that date.
4083 A prefix ARG can be used force the current date."
4084 (interactive "P")
4085 (let ((tsr org-ts-regexp) diff
4086 (calendar-move-hook nil)
4087 (view-diary-entries-initially nil))
4088 (if (or (org-at-timestamp-p)
4089 (save-excursion
4090 (beginning-of-line 1)
4091 (looking-at (concat ".*" tsr))))
4092 (let ((d1 (time-to-days (current-time)))
4093 (d2 (time-to-days
4094 (org-time-string-to-time (match-string 1)))))
4095 (setq diff (- d2 d1))))
4096 (calendar)
4097 (calendar-goto-today)
4098 (if (and diff (not arg)) (calendar-forward-day diff))))
4099
4100 (defun org-date-from-calendar ()
4101 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4102 If there is already a time stamp at the cursor position, update it."
4103 (interactive)
4104 (org-timestamp-change 0 'calendar))
4105
4106 ;;; Agenda, and Diary Integration
4107
4108 ;;; Define the mode
4109
4110 (defvar org-agenda-mode-map (make-sparse-keymap)
4111 "Keymap for `org-agenda-mode'.")
4112
4113 (defvar org-agenda-menu)
4114 (defvar org-agenda-follow-mode nil)
4115 (defvar org-agenda-show-log nil)
4116 (defvar org-agenda-buffer-name "*Org Agenda*")
4117 (defvar org-agenda-redo-command nil)
4118 (defvar org-agenda-mode-hook nil)
4119 (defvar org-agenda-type nil)
4120 (defvar org-agenda-force-single-file nil)
4121
4122 ;;;###autoload
4123 (defun org-agenda-mode ()
4124 "Mode for time-sorted view on action items in Org-mode files.
4125
4126 The following commands are available:
4127
4128 \\{org-agenda-mode-map}"
4129 (interactive)
4130 (kill-all-local-variables)
4131 (setq major-mode 'org-agenda-mode)
4132 (setq mode-name "Org-Agenda")
4133 (use-local-map org-agenda-mode-map)
4134 (easy-menu-add org-agenda-menu)
4135 (if org-startup-truncated (setq truncate-lines t))
4136 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4137 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4138 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4139 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4140 (unless org-agenda-keep-modes
4141 (setq org-agenda-follow-mode nil
4142 org-agenda-show-log nil))
4143 (easy-menu-change
4144 '("Agenda") "Agenda Files"
4145 (append
4146 (list
4147 (vector
4148 (if (get 'org-agenda-files 'org-restrict)
4149 "Restricted to single file"
4150 "Edit File List")
4151 '(customize-variable 'org-agenda-files)
4152 (not (get 'org-agenda-files 'org-restrict)))
4153 "--")
4154 (mapcar 'org-file-menu-entry (org-agenda-files))))
4155 (org-agenda-set-mode-name)
4156 (apply
4157 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4158 (list 'org-agenda-mode-hook)))
4159
4160 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4161 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4162 (define-key org-agenda-mode-map " " 'org-agenda-show)
4163 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4164 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4165 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4166 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4167 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4168 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4169 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4170 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4171 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4172 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4173 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4174 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4175
4176 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4177 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4178 (while l (define-key org-agenda-mode-map
4179 (int-to-string (pop l)) 'digit-argument)))
4180
4181 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4182 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4183 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4184 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4185 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4186 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4187 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4188 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4189 (define-key org-agenda-mode-map "n" 'next-line)
4190 (define-key org-agenda-mode-map "p" 'previous-line)
4191 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4192 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4193 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4194 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4195 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4196 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4197 (eval-after-load "calendar"
4198 '(define-key calendar-mode-map org-calendar-to-agenda-key
4199 'org-calendar-goto-agenda))
4200 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4201 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4202 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4203 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4204 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4205 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4206 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4207 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4208 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4209 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4210 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4211 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4212 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4213 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4214 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4215 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4216 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4217 "Local keymap for agenda entries from Org-mode.")
4218
4219 (define-key org-agenda-keymap
4220 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4221 (define-key org-agenda-keymap
4222 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4223
4224 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4225 '("Agenda"
4226 ("Agenda Files")
4227 "--"
4228 ["Show" org-agenda-show t]
4229 ["Go To (other window)" org-agenda-goto t]
4230 ["Go To (one window)" org-agenda-switch-to t]
4231 ["Follow Mode" org-agenda-follow-mode
4232 :style toggle :selected org-agenda-follow-mode :active t]
4233 "--"
4234 ["Cycle TODO" org-agenda-todo t]
4235 ["Set Tags" org-agenda-set-tags t]
4236 ("Reschedule"
4237 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4238 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4239 "--"
4240 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4241 ("Priority"
4242 ["Set Priority" org-agenda-priority t]
4243 ["Increase Priority" org-agenda-priority-up t]
4244 ["Decrease Priority" org-agenda-priority-down t]
4245 ["Show Priority" org-agenda-show-priority t])
4246 "--"
4247 ;; ["New agenda command" org-agenda t]
4248 ["Rebuild buffer" org-agenda-redo t]
4249 "--"
4250 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4251 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4252 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4253 "--"
4254 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4255 :style radio :selected (equal org-agenda-ndays 1)]
4256 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4257 :style radio :selected (equal org-agenda-ndays 7)]
4258 "--"
4259 ["Show Logbook entries" org-agenda-log-mode
4260 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4261 ["Include Diary" org-agenda-toggle-diary
4262 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4263 ["Use Time Grid" org-agenda-toggle-time-grid
4264 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4265 "--"
4266 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4267 ("Calendar Commands"
4268 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4269 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4270 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4271 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4272 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4273 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4274 "--"
4275 ["Quit" org-agenda-quit t]
4276 ["Exit and Release Buffers" org-agenda-exit t]
4277 ))
4278
4279 ;;;###autoload
4280 (defun org-agenda (arg)
4281 "Dispatch agenda commands to collect entries to the agenda buffer.
4282 Prompts for a character to select a command. Any prefix arg will be passed
4283 on to the selected command. The default selections are:
4284
4285 a Call `org-agenda' to display the agenda for the current day or week.
4286 t Call `org-todo-list' to display the global todo list.
4287 T Call `org-todo-list' to display the global todo list, select only
4288 entries with a specific TODO keyword (the user get a prompt).
4289 m Call `org-tags-view' to display headlines with tags matching
4290 a condition (the user is prompted for the condition).
4291 M like `m', but select only TODO entries, no ordinary headlines.
4292
4293 More commands can be added by configuring the variable
4294 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4295 searches can be pre-defined in this way.
4296
4297 If the current buffer is in Org-mode and visiting a file, you can also
4298 first press `1' to indicate that the agenda should be temporarily (until the
4299 next use of \\[org-agenda]) restricted to the current file."
4300 (interactive "P")
4301 (catch 'exit
4302 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4303 (custom org-agenda-custom-commands)
4304 c entry key type string)
4305 (put 'org-agenda-files 'org-restrict nil)
4306 (save-window-excursion
4307 (delete-other-windows)
4308 (switch-to-buffer-other-window " *Agenda Commands*")
4309 (erase-buffer)
4310 (insert
4311 "Press key for an agenda command:
4312 --------------------------------
4313 a Agenda for current week or day
4314 t List of all TODO entries T Entries with special TODO kwd
4315 m Match a TAGS query M Like m, but only TODO entries.
4316 C Configure your own agenda commands")
4317 (while (setq entry (pop custom))
4318 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4319 (insert (format "\n%-4s%-14s: %s"
4320 key
4321 (cond
4322 ((eq type 'tags) "Tags query")
4323 ((eq type 'todo) "TODO keyword")
4324 ((eq type 'tags-tree) "Tags tree")
4325 ((eq type 'todo-tree) "TODO kwd tree")
4326 ((eq type 'occur-tree) "Occur tree")
4327 (t "???"))
4328 (org-string-props string 'face 'org-link))))
4329 (goto-char (point-min))
4330 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4331 (message "Press key for agenda command%s"
4332 (if restrict-ok ", or [1] to restrict to current file" ""))
4333 (setq c (read-char-exclusive))
4334 (message "")
4335 (when (equal c ?1)
4336 (if restrict-ok
4337 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4338 (error "Cannot restrict agenda to current buffer"))
4339 (message "Press key for agenda command%s"
4340 (if restrict-ok " (restricted to current file)" ""))
4341 (setq c (read-char-exclusive))
4342 (message "")))
4343 (require 'calendar) ; FIXME: can we avoid this for some commands?
4344 ;; For example the todo list should not need it (but does...)
4345 (cond
4346 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4347 ((equal c ?a) (call-interactively 'org-agenda-list))
4348 ((equal c ?t) (call-interactively 'org-todo-list))
4349 ((equal c ?T)
4350 (setq current-prefix-arg (or arg '(4)))
4351 (call-interactively 'org-todo-list))
4352 ((equal c ?m) (call-interactively 'org-tags-view))
4353 ((equal c ?M)
4354 (setq current-prefix-arg (or arg '(4)))
4355 (call-interactively 'org-tags-view))
4356 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4357 (setq type (nth 1 entry) string (nth 2 entry))
4358 (cond
4359 ((eq type 'tags)
4360 (org-tags-view current-prefix-arg string))
4361 ((eq type 'todo)
4362 (org-todo-list string))
4363 ((eq type 'tags-tree)
4364 (org-check-for-org-mode)
4365 (org-tags-sparse-tree current-prefix-arg string))
4366 ((eq type 'todo-tree)
4367 (org-check-for-org-mode)
4368 (org-occur (concat "^" outline-regexp "[ \t]*"
4369 (regexp-quote string) "\\>")))
4370 ((eq type 'occur-tree)
4371 (org-check-for-org-mode)
4372 (org-occur string))
4373 (t (error "Invalid custom agenda command type %s" type))))
4374 (t (error "Invalid key"))))))
4375
4376 (defun org-check-for-org-mode ()
4377 "Make sure current buffer is in org-mode. Error if not."
4378 (or (eq major-mode 'org-mode)
4379 (error "Cannot execute org-mode agenda command on buffer in %s."
4380 major-mode)))
4381
4382 (defun org-fit-agenda-window ()
4383 "Fit the window to the buffer size."
4384 (and org-fit-agenda-window
4385 (fboundp 'fit-window-to-buffer)
4386 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4387 (/ (frame-height) 2))))
4388
4389 (defun org-agenda-files ()
4390 "Get the list of agenda files."
4391 (or (get 'org-agenda-files 'org-restrict)
4392 org-agenda-files))
4393
4394 (defvar org-agenda-markers nil
4395 "List of all currently active markers created by `org-agenda'.")
4396 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4397 "Creation time of the last agenda marker.")
4398
4399 (defun org-agenda-new-marker (&optional pos)
4400 "Return a new agenda marker.
4401 Org-mode keeps a list of these markers and resets them when they are
4402 no longer in use."
4403 (let ((m (copy-marker (or pos (point)))))
4404 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4405 (push m org-agenda-markers)
4406 m))
4407
4408 (defun org-agenda-maybe-reset-markers (&optional force)
4409 "Reset markers created by `org-agenda'. But only if they are old enough."
4410 (if (or force
4411 (> (- (time-to-seconds (current-time))
4412 org-agenda-last-marker-time)
4413 5))
4414 (while org-agenda-markers
4415 (move-marker (pop org-agenda-markers) nil))))
4416
4417 (defvar org-agenda-new-buffers nil
4418 "Buffers created to visit agenda files.")
4419
4420 (defun org-get-agenda-file-buffer (file)
4421 "Get a buffer visiting FILE. If the buffer needs to be created, add
4422 it to the list of buffers which might be released later."
4423 (let ((buf (find-buffer-visiting file)))
4424 (if buf
4425 buf ; just return it
4426 ;; Make a new buffer and remember it
4427 (setq buf (find-file-noselect file))
4428 (if buf (push buf org-agenda-new-buffers))
4429 buf)))
4430
4431 (defun org-release-buffers (blist)
4432 "Release all buffers in list, asking the user for confirmation when needed.
4433 When a buffer is unmodified, it is just killed. When modified, it is saved
4434 \(if the user agrees) and then killed."
4435 (let (buf file)
4436 (while (setq buf (pop blist))
4437 (setq file (buffer-file-name buf))
4438 (when (and (buffer-modified-p buf)
4439 file
4440 (y-or-n-p (format "Save file %s? " file)))
4441 (with-current-buffer buf (save-buffer)))
4442 (kill-buffer buf))))
4443
4444 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4445
4446 (defun org-timeline (&optional include-all keep-modes)
4447 "Show a time-sorted view of the entries in the current org file.
4448 Only entries with a time stamp of today or later will be listed. With
4449 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4450 under the current date.
4451 If the buffer contains an active region, only check the region for
4452 dates."
4453 (interactive "P")
4454 (require 'calendar)
4455 (org-agenda-maybe-reset-markers 'force)
4456 (org-compile-prefix-format org-timeline-prefix-format)
4457 (let* ((dopast t)
4458 (dotodo include-all)
4459 (doclosed org-agenda-show-log)
4460 (org-agenda-keep-modes keep-modes)
4461 (entry (buffer-file-name))
4462 (org-agenda-files (list (buffer-file-name)))
4463 (date (calendar-current-date))
4464 (win (selected-window))
4465 (pos1 (point))
4466 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4467 (end (if (org-region-active-p) (region-end) (point-max)))
4468 (day-numbers (org-get-all-dates beg end 'no-ranges
4469 t doclosed)) ; always include today
4470 (today (time-to-days (current-time)))
4471 (org-respect-restriction t)
4472 (past t)
4473 args
4474 s e rtn d)
4475 (setq org-agenda-redo-command
4476 (list 'progn
4477 (list 'switch-to-buffer-other-window (current-buffer))
4478 (list 'org-timeline (list 'quote include-all) t)))
4479 (if (not dopast)
4480 ;; Remove past dates from the list of dates.
4481 (setq day-numbers (delq nil (mapcar (lambda(x)
4482 (if (>= x today) x nil))
4483 day-numbers))))
4484 (switch-to-buffer-other-window
4485 (get-buffer-create org-agenda-buffer-name))
4486 (setq buffer-read-only nil)
4487 (erase-buffer)
4488 (org-agenda-mode) (setq buffer-read-only nil)
4489 (set (make-local-variable 'org-agenda-type) 'timeline)
4490 (if doclosed (push :closed args))
4491 (push :timestamp args)
4492 (if dotodo (push :todo args))
4493 (while (setq d (pop day-numbers))
4494 (if (and (>= d today)
4495 dopast
4496 past)
4497 (progn
4498 (setq past nil)
4499 (insert (make-string 79 ?-) "\n")))
4500 (setq date (calendar-gregorian-from-absolute d))
4501 (setq s (point))
4502 (setq rtn (apply 'org-agenda-get-day-entries
4503 entry date args))
4504 (if (or rtn (equal d today))
4505 (progn
4506 (insert (calendar-day-name date) " "
4507 (number-to-string (extract-calendar-day date)) " "
4508 (calendar-month-name (extract-calendar-month date)) " "
4509 (number-to-string (extract-calendar-year date)) "\n")
4510 (put-text-property s (1- (point)) 'face
4511 'org-link)
4512 (if (equal d today)
4513 (put-text-property s (1- (point)) 'org-today t))
4514 (insert (org-finalize-agenda-entries rtn) "\n")
4515 (put-text-property s (1- (point)) 'day d))))
4516 (goto-char (point-min))
4517 (setq buffer-read-only t)
4518 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4519 (point-min)))
4520 (when (not org-select-timeline-window)
4521 (select-window win)
4522 (goto-char pos1))))
4523
4524 ;;;###autoload
4525 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4526 "Produce a weekly view from all files in variable `org-agenda-files'.
4527 The view will be for the current week, but from the overview buffer you
4528 will be able to go to other weeks.
4529 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4530 also be shown, under the current date.
4531 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4532 on the days are also shown. See the variable `org-log-done' for how
4533 to turn on logging.
4534 START-DAY defaults to TODAY, or to the most recent match for the weekday
4535 given in `org-agenda-start-on-weekday'.
4536 NDAYS defaults to `org-agenda-ndays'."
4537 (interactive "P")
4538 (org-agenda-maybe-reset-markers 'force)
4539 (org-compile-prefix-format org-agenda-prefix-format)
4540 (require 'calendar)
4541 (let* ((org-agenda-start-on-weekday
4542 (if (or (equal ndays 1)
4543 (and (null ndays) (equal 1 org-agenda-ndays)))
4544 nil org-agenda-start-on-weekday))
4545 (org-agenda-keep-modes keep-modes)
4546 (files (copy-sequence (org-agenda-files)))
4547 (win (selected-window))
4548 (today (time-to-days (current-time)))
4549 (sd (or start-day today))
4550 (start (if (or (null org-agenda-start-on-weekday)
4551 (< org-agenda-ndays 7))
4552 sd
4553 (let* ((nt (calendar-day-of-week
4554 (calendar-gregorian-from-absolute sd)))
4555 (n1 org-agenda-start-on-weekday)
4556 (d (- nt n1)))
4557 (- sd (+ (if (< d 0) 7 0) d)))))
4558 (day-numbers (list start))
4559 (inhibit-redisplay t)
4560 s e rtn rtnall file date d start-pos end-pos todayp nd)
4561 (setq org-agenda-redo-command
4562 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4563 ;; Make the list of days
4564 (setq ndays (or ndays org-agenda-ndays)
4565 nd ndays)
4566 (while (> ndays 1)
4567 (push (1+ (car day-numbers)) day-numbers)
4568 (setq ndays (1- ndays)))
4569 (setq day-numbers (nreverse day-numbers))
4570 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4571 (progn
4572 (delete-other-windows)
4573 (switch-to-buffer-other-window
4574 (get-buffer-create org-agenda-buffer-name))))
4575 (setq buffer-read-only nil)
4576 (erase-buffer)
4577 (org-agenda-mode) (setq buffer-read-only nil)
4578 (set (make-local-variable 'org-agenda-type) 'agenda)
4579 (set (make-local-variable 'starting-day) (car day-numbers))
4580 (set (make-local-variable 'include-all-loc) include-all)
4581 (when (and (or include-all org-agenda-include-all-todo)
4582 (member today day-numbers))
4583 (setq files (org-agenda-files)
4584 rtnall nil)
4585 (while (setq file (pop files))
4586 (catch 'nextfile
4587 (org-check-agenda-file file)
4588 (setq date (calendar-gregorian-from-absolute today)
4589 rtn (org-agenda-get-day-entries
4590 file date :todo))
4591 (setq rtnall (append rtnall rtn))))
4592 (when rtnall
4593 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4594 (add-text-properties (point-min) (1- (point))
4595 (list 'face 'org-link))
4596 (insert (org-finalize-agenda-entries rtnall) "\n")))
4597 (while (setq d (pop day-numbers))
4598 (setq date (calendar-gregorian-from-absolute d)
4599 s (point))
4600 (if (or (setq todayp (= d today))
4601 (and (not start-pos) (= d sd)))
4602 (setq start-pos (point))
4603 (if (and start-pos (not end-pos))
4604 (setq end-pos (point))))
4605 (setq files (org-agenda-files)
4606 rtnall nil)
4607 (while (setq file (pop files))
4608 (catch 'nextfile
4609 (org-check-agenda-file file)
4610 (if org-agenda-show-log
4611 (setq rtn (org-agenda-get-day-entries
4612 file date
4613 :deadline :scheduled :timestamp :closed))
4614 (setq rtn (org-agenda-get-day-entries
4615 file date
4616 :deadline :scheduled :timestamp)))
4617 (setq rtnall (append rtnall rtn))))
4618 (if org-agenda-include-diary
4619 (progn
4620 (require 'diary-lib)
4621 (setq rtn (org-get-entries-from-diary date))
4622 (setq rtnall (append rtnall rtn))))
4623 (if (or rtnall org-agenda-show-all-dates)
4624 (progn
4625 (insert (format "%-9s %2d %s %4d\n"
4626 (calendar-day-name date)
4627 (extract-calendar-day date)
4628 (calendar-month-name (extract-calendar-month date))
4629 (extract-calendar-year date)))
4630 (put-text-property s (1- (point)) 'face
4631 'org-link)
4632 (if rtnall (insert
4633 (org-finalize-agenda-entries
4634 (org-agenda-add-time-grid-maybe
4635 rtnall nd todayp))
4636 "\n"))
4637 (put-text-property s (1- (point)) 'day d))))
4638 (goto-char (point-min))
4639 (setq buffer-read-only t)
4640 (org-fit-agenda-window)
4641 (unless (and (pos-visible-in-window-p (point-min))
4642 (pos-visible-in-window-p (point-max)))
4643 (goto-char (1- (point-max)))
4644 (recenter -1)
4645 (if (not (pos-visible-in-window-p (or start-pos 1)))
4646 (progn
4647 (goto-char (or start-pos 1))
4648 (recenter 1))))
4649 (goto-char (or start-pos 1))
4650 (if (not org-select-agenda-window) (select-window win))
4651 (message "")))
4652
4653 (defvar org-select-this-todo-keyword nil)
4654
4655 ;;;###autoload
4656 (defun org-todo-list (arg &optional keep-modes)
4657 "Show all TODO entries from all agenda file in a single list.
4658 The prefix arg can be used to select a specific TODO keyword and limit
4659 the list to these. When using \\[universal-argument], you will be prompted
4660 for a keyword. A numeric prefix directly selects the Nth keyword in
4661 `org-todo-keywords'."
4662 (interactive "P")
4663 (org-agenda-maybe-reset-markers 'force)
4664 (org-compile-prefix-format org-agenda-prefix-format)
4665 (let* ((org-agenda-keep-modes keep-modes)
4666 (today (time-to-days (current-time)))
4667 (date (calendar-gregorian-from-absolute today))
4668 (win (selected-window))
4669 (kwds org-todo-keywords)
4670 (completion-ignore-case t)
4671 (org-select-this-todo-keyword
4672 (if (stringp arg) arg
4673 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4674 rtn rtnall files file pos)
4675 (when (equal arg '(4))
4676 (setq org-select-this-todo-keyword
4677 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4678 nil t)))
4679 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4680 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4681 (progn
4682 (delete-other-windows)
4683 (switch-to-buffer-other-window
4684 (get-buffer-create org-agenda-buffer-name))))
4685 (setq buffer-read-only nil)
4686 (erase-buffer)
4687 (org-agenda-mode) (setq buffer-read-only nil)
4688 (set (make-local-variable 'org-agenda-type) 'todo)
4689 (set (make-local-variable 'last-arg) arg)
4690 (set (make-local-variable 'org-todo-keywords) kwds)
4691 (set (make-local-variable 'org-agenda-redo-command)
4692 '(org-todo-list (or current-prefix-arg last-arg) t))
4693 (setq files (org-agenda-files)
4694 rtnall nil)
4695 (while (setq file (pop files))
4696 (catch 'nextfile
4697 (org-check-agenda-file file)
4698 (setq rtn (org-agenda-get-day-entries file date :todo))
4699 (setq rtnall (append rtnall rtn))))
4700 (insert "Global list of TODO items of type: ")
4701 (add-text-properties (point-min) (1- (point))
4702 (list 'face 'org-link))
4703 (setq pos (point))
4704 (insert (or org-select-this-todo-keyword "ALL") "\n")
4705 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4706 (setq pos (point))
4707 (insert
4708 "Available with `N r': (0)ALL "
4709 (let ((n 0))
4710 (mapconcat (lambda (x)
4711 (format "(%d)%s" (setq n (1+ n)) x))
4712 org-todo-keywords " "))
4713 "\n")
4714 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4715 (when rtnall
4716 (insert (org-finalize-agenda-entries rtnall) "\n"))
4717 (goto-char (point-min))
4718 (setq buffer-read-only t)
4719 (org-fit-agenda-window)
4720 (if (not org-select-agenda-window) (select-window win))))
4721
4722 (defun org-check-agenda-file (file)
4723 "Make sure FILE exists. If not, ask user what to do."
4724 ;; FIXME: this does not correctly change the menus
4725 ;; Could probably be fixed by explicitly going to the buffer where
4726 ;; the call originated.
4727 (when (not (file-exists-p file))
4728 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4729 file)
4730 (let ((r (downcase (read-char-exclusive))))
4731 (cond
4732 ((equal r ?r)
4733 (org-remove-file file)
4734 (throw 'nextfile t))
4735 (t (error "Abort"))))))
4736
4737 (defun org-agenda-check-type (error &rest types)
4738 "Check if agenda buffer is of allowed type.
4739 If ERROR is non-nil, throw an error, otherwise just return nil."
4740 (if (memq org-agenda-type types)
4741 t
4742 (if error
4743 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4744 nil)))
4745
4746 (defun org-agenda-quit ()
4747 "Exit agenda by removing the window or the buffer."
4748 (interactive)
4749 (let ((buf (current-buffer)))
4750 (if (not (one-window-p)) (delete-window))
4751 (kill-buffer buf)
4752 (org-agenda-maybe-reset-markers 'force)))
4753
4754 (defun org-agenda-exit ()
4755 "Exit agenda by removing the window or the buffer.
4756 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4757 Org-mode buffers visited directly by the user will not be touched."
4758 (interactive)
4759 (org-release-buffers org-agenda-new-buffers)
4760 (setq org-agenda-new-buffers nil)
4761 (org-agenda-quit))
4762
4763 (defun org-agenda-redo ()
4764 "Rebuild Agenda.
4765 When this is the global TODO list, a prefix argument will be interpreted."
4766 (interactive)
4767 (message "Rebuilding agenda buffer...")
4768 (eval org-agenda-redo-command)
4769 (message "Rebuilding agenda buffer...done"))
4770
4771 (defun org-agenda-goto-today ()
4772 "Go to today."
4773 (interactive)
4774 (org-agenda-check-type t 'timeline 'agenda)
4775 (if (boundp 'starting-day)
4776 (let ((cmd (car org-agenda-redo-command))
4777 (iall (nth 1 org-agenda-redo-command))
4778 (nday (nth 3 org-agenda-redo-command))
4779 (keep (nth 4 org-agenda-redo-command)))
4780 (eval (list cmd iall nil nday keep)))
4781 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4782 (point-min)))))
4783
4784 (defun org-agenda-later (arg)
4785 "Go forward in time by `org-agenda-ndays' days.
4786 With prefix ARG, go forward that many times `org-agenda-ndays'."
4787 (interactive "p")
4788 (org-agenda-check-type t 'agenda)
4789 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4790 (+ starting-day (* arg org-agenda-ndays)) nil t))
4791
4792 (defun org-agenda-earlier (arg)
4793 "Go back in time by `org-agenda-ndays' days.
4794 With prefix ARG, go back that many times `org-agenda-ndays'."
4795 (interactive "p")
4796 (org-agenda-check-type t 'agenda)
4797 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4798 (- starting-day (* arg org-agenda-ndays)) nil t))
4799
4800 (defun org-agenda-week-view ()
4801 "Switch to weekly view for agenda."
4802 (interactive)
4803 (org-agenda-check-type t 'agenda)
4804 (setq org-agenda-ndays 7)
4805 (org-agenda-list include-all-loc
4806 (or (get-text-property (point) 'day)
4807 starting-day)
4808 nil t)
4809 (org-agenda-set-mode-name)
4810 (message "Switched to week view"))
4811
4812 (defun org-agenda-day-view ()
4813 "Switch to weekly view for agenda."
4814 (interactive)
4815 (org-agenda-check-type t 'agenda)
4816 (setq org-agenda-ndays 1)
4817 (org-agenda-list include-all-loc
4818 (or (get-text-property (point) 'day)
4819 starting-day)
4820 nil t)
4821 (org-agenda-set-mode-name)
4822 (message "Switched to day view"))
4823
4824 (defun org-agenda-next-date-line (&optional arg)
4825 "Jump to the next line indicating a date in agenda buffer."
4826 (interactive "p")
4827 (org-agenda-check-type t 'agenda 'timeline)
4828 (beginning-of-line 1)
4829 (if (looking-at "^\\S-") (forward-char 1))
4830 (if (not (re-search-forward "^\\S-" nil t arg))
4831 (progn
4832 (backward-char 1)
4833 (error "No next date after this line in this buffer")))
4834 (goto-char (match-beginning 0)))
4835
4836 (defun org-agenda-previous-date-line (&optional arg)
4837 "Jump to the next line indicating a date in agenda buffer."
4838 (interactive "p")
4839 (org-agenda-check-type t 'agenda 'timeline)
4840 (beginning-of-line 1)
4841 (if (not (re-search-backward "^\\S-" nil t arg))
4842 (error "No previous date before this line in this buffer")))
4843
4844 ;; Initialize the highlight
4845 (defvar org-hl (org-make-overlay 1 1))
4846 (org-overlay-put org-hl 'face 'highlight)
4847
4848 (defun org-highlight (begin end &optional buffer)
4849 "Highlight a region with overlay."
4850 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4851 org-hl begin end (or buffer (current-buffer))))
4852
4853 (defun org-unhighlight ()
4854 "Detach overlay INDEX."
4855 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4856
4857
4858 (defun org-agenda-follow-mode ()
4859 "Toggle follow mode in an agenda buffer."
4860 (interactive)
4861 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4862 (org-agenda-set-mode-name)
4863 (message "Follow mode is %s"
4864 (if org-agenda-follow-mode "on" "off")))
4865
4866 (defun org-agenda-log-mode ()
4867 "Toggle follow mode in an agenda buffer."
4868 (interactive)
4869 (org-agenda-check-type t 'agenda 'timeline)
4870 (setq org-agenda-show-log (not org-agenda-show-log))
4871 (org-agenda-set-mode-name)
4872 (org-agenda-redo)
4873 (message "Log mode is %s"
4874 (if org-agenda-show-log "on" "off")))
4875
4876 (defun org-agenda-toggle-diary ()
4877 "Toggle follow mode in an agenda buffer."
4878 (interactive)
4879 (org-agenda-check-type t 'agenda)
4880 (setq org-agenda-include-diary (not org-agenda-include-diary))
4881 (org-agenda-redo)
4882 (org-agenda-set-mode-name)
4883 (message "Diary inclusion turned %s"
4884 (if org-agenda-include-diary "on" "off")))
4885
4886 (defun org-agenda-toggle-time-grid ()
4887 "Toggle follow mode in an agenda buffer."
4888 (interactive)
4889 (org-agenda-check-type t 'agenda)
4890 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4891 (org-agenda-redo)
4892 (org-agenda-set-mode-name)
4893 (message "Time-grid turned %s"
4894 (if org-agenda-use-time-grid "on" "off")))
4895
4896 (defun org-agenda-set-mode-name ()
4897 "Set the mode name to indicate all the small mode settings."
4898 (setq mode-name
4899 (concat "Org-Agenda"
4900 (if (equal org-agenda-ndays 1) " Day" "")
4901 (if (equal org-agenda-ndays 7) " Week" "")
4902 (if org-agenda-follow-mode " Follow" "")
4903 (if org-agenda-include-diary " Diary" "")
4904 (if org-agenda-use-time-grid " Grid" "")
4905 (if org-agenda-show-log " Log" "")))
4906 (force-mode-line-update))
4907
4908 (defun org-agenda-post-command-hook ()
4909 (and (eolp) (not (bolp)) (backward-char 1))
4910 (if (and org-agenda-follow-mode
4911 (get-text-property (point) 'org-marker))
4912 (org-agenda-show)))
4913
4914 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4915
4916 (defun org-get-entries-from-diary (date)
4917 "Get the (Emacs Calendar) diary entries for DATE."
4918 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4919 (diary-display-hook '(fancy-diary-display))
4920 (list-diary-entries-hook
4921 (cons 'org-diary-default-entry list-diary-entries-hook))
4922 (diary-file-name-prefix-function nil) ; turn this feature off
4923 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4924 entries
4925 (org-disable-agenda-to-diary t))
4926 (save-excursion
4927 (save-window-excursion
4928 (list-diary-entries date 1)))
4929 (if (not (get-buffer fancy-diary-buffer))
4930 (setq entries nil)
4931 (with-current-buffer fancy-diary-buffer
4932 (setq buffer-read-only nil)
4933 (if (= (point-max) 1)
4934 ;; No entries
4935 (setq entries nil)
4936 ;; Omit the date and other unnecessary stuff
4937 (org-agenda-cleanup-fancy-diary)
4938 ;; Add prefix to each line and extend the text properties
4939 (if (= (point-max) 1)
4940 (setq entries nil)
4941 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4942 (set-buffer-modified-p nil)
4943 (kill-buffer fancy-diary-buffer)))
4944 (when entries
4945 (setq entries (org-split-string entries "\n"))
4946 (setq entries
4947 (mapcar
4948 (lambda (x)
4949 (setq x (org-format-agenda-item "" x "Diary" 'time))
4950 ;; Extend the text properties to the beginning of the line
4951 (add-text-properties
4952 0 (length x)
4953 (text-properties-at (1- (length x)) x)
4954 x)
4955 x)
4956 entries)))))
4957
4958 (defun org-agenda-cleanup-fancy-diary ()
4959 "Remove unwanted stuff in buffer created by fancy-diary-display.
4960 This gets rid of the date, the underline under the date, and
4961 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4962 date. Itt also removes lines that contain only whitespace."
4963 (goto-char (point-min))
4964 (if (looking-at ".*?:[ \t]*")
4965 (progn
4966 (replace-match "")
4967 (re-search-forward "\n=+$" nil t)
4968 (replace-match "")
4969 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4970 (re-search-forward "\n=+$" nil t)
4971 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4972 (goto-char (point-min))
4973 (while (re-search-forward "^ +\n" nil t)
4974 (replace-match ""))
4975 (goto-char (point-min))
4976 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4977 (replace-match "")))
4978
4979 ;; Make sure entries from the diary have the right text properties.
4980 (eval-after-load "diary-lib"
4981 '(if (boundp 'diary-modify-entry-list-string-function)
4982 ;; We can rely on the hook, nothing to do
4983 nil
4984 ;; Hook not avaiable, must use advice to make this work
4985 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4986 "Make the position visible."
4987 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4988 (stringp string)
4989 (buffer-file-name))
4990 (setq string (org-modify-diary-entry-string string))))))
4991
4992 (defun org-modify-diary-entry-string (string)
4993 "Add text properties to string, allowing org-mode to act on it."
4994 (add-text-properties
4995 0 (length string)
4996 (list 'mouse-face 'highlight
4997 'keymap org-agenda-keymap
4998 'help-echo
4999 (format
5000 "mouse-2 or RET jump to diary file %s"
5001 (abbreviate-file-name (buffer-file-name)))
5002 'org-agenda-diary-link t
5003 'org-marker (org-agenda-new-marker (point-at-bol)))
5004 string)
5005 string)
5006
5007 (defun org-diary-default-entry ()
5008 "Add a dummy entry to the diary.
5009 Needed to avoid empty dates which mess up holiday display."
5010 ;; Catch the error if dealing with the new add-to-diary-alist
5011 (when org-disable-agenda-to-diary
5012 (condition-case nil
5013 (add-to-diary-list original-date "Org-mode dummy" "")
5014 (error
5015 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5016
5017 (defun org-cycle-agenda-files ()
5018 "Cycle through the files in `org-agenda-files'.
5019 If the current buffer visits an agenda file, find the next one in the list.
5020 If the current buffer does not, find the first agenda file."
5021 (interactive)
5022 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5023 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5024 file)
5025 (unless files (error "No agenda files"))
5026 (catch 'exit
5027 (while (setq file (pop files))
5028 (if (equal (file-truename file) tcf)
5029 (when (car files)
5030 (find-file (car files))
5031 (throw 'exit t))))
5032 (find-file (car org-agenda-files)))))
5033
5034 (defun org-agenda-file-to-end (&optional file)
5035 "Move/add the current file to the end of the agenda fiole list.
5036 I the file is not present in the list, it is appended ot the list. If it is
5037 present, it is moved there."
5038 (interactive)
5039 (org-agenda-file-to-front 'to-end file))
5040
5041 (defun org-agenda-file-to-front (&optional to-end file)
5042 "Move/add the current file to the top of the agenda file list.
5043 If the file is not present in the list, it is added to the front. If it is
5044 present, it is moved there. With optional argument TO-END, add/move to the
5045 end of the list."
5046 (interactive "P")
5047 (let ((file-alist (mapcar (lambda (x)
5048 (cons (file-truename x) x))
5049 org-agenda-files))
5050 (ctf (file-truename (buffer-file-name)))
5051 x had)
5052 (setq x (assoc ctf file-alist) had x)
5053
5054 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5055 (if to-end
5056 (setq file-alist (append (delq x file-alist) (list x)))
5057 (setq file-alist (cons x (delq x file-alist))))
5058 (setq org-agenda-files (mapcar 'cdr file-alist))
5059 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5060 (customize-save-variable 'org-agenda-files org-agenda-files))
5061 (org-install-agenda-files-menu)
5062 (message "File %s to %s of agenda file list"
5063 (if had "moved" "added") (if to-end "end" "front"))))
5064
5065 (defun org-remove-file (&optional file)
5066 "Remove current file from the list of files in variable `org-agenda-files'.
5067 These are the files which are being checked for agenda entries.
5068 Optional argument FILE means, use this file instead of the current."
5069 (interactive)
5070 (let* ((file (or file (buffer-file-name)))
5071 (true-file (file-truename file))
5072 (afile (abbreviate-file-name file))
5073 (files (delq nil (mapcar
5074 (lambda (x)
5075 (if (equal true-file
5076 (file-truename x))
5077 nil x))
5078 org-agenda-files))))
5079 (if (not (= (length files) (length org-agenda-files)))
5080 (progn
5081 (setq org-agenda-files files)
5082 (customize-save-variable 'org-agenda-files org-agenda-files)
5083 (org-install-agenda-files-menu)
5084 (message "Removed file: %s" afile))
5085 (message "File was not in list: %s" afile))))
5086
5087 (defun org-file-menu-entry (file)
5088 (vector file (list 'find-file file) t))
5089 ;; FIXME: Maybe we removed a buffer visited through the menu from
5090 ;; org-agenda-new-buffers, so that the buffer will not be removed
5091 ;; when exiting the agenda????
5092
5093 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5094 "Return a list of all relevant day numbers from BEG to END buffer positions.
5095 If NO-RANGES is non-nil, include only the start and end dates of a range,
5096 not every single day in the range. If FORCE-TODAY is non-nil, make
5097 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5098 inactive time stamps (those in square brackets) are included."
5099 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5100 dates date day day1 day2 ts1 ts2)
5101 (if force-today
5102 (setq dates (list (time-to-days (current-time)))))
5103 (save-excursion
5104 (goto-char beg)
5105 (while (re-search-forward re end t)
5106 (setq day (time-to-days (org-time-string-to-time
5107 (substring (match-string 1) 0 10))))
5108 (or (memq day dates) (push day dates)))
5109 (unless no-ranges
5110 (goto-char beg)
5111 (while (re-search-forward org-tr-regexp end t)
5112 (setq ts1 (substring (match-string 1) 0 10)
5113 ts2 (substring (match-string 2) 0 10)
5114 day1 (time-to-days (org-time-string-to-time ts1))
5115 day2 (time-to-days (org-time-string-to-time ts2)))
5116 (while (< (setq day1 (1+ day1)) day2)
5117 (or (memq day1 dates) (push day1 dates)))))
5118 (sort dates '<))))
5119
5120 ;;;###autoload
5121 (defun org-diary (&rest args)
5122 "Return diary information from org-files.
5123 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5124 It accesses org files and extracts information from those files to be
5125 listed in the diary. The function accepts arguments specifying what
5126 items should be listed. The following arguments are allowed:
5127
5128 :timestamp List the headlines of items containing a date stamp or
5129 date range matching the selected date. Deadlines will
5130 also be listed, on the expiration day.
5131
5132 :deadline List any deadlines past due, or due within
5133 `org-deadline-warning-days'. The listing occurs only
5134 in the diary for *today*, not at any other date. If
5135 an entry is marked DONE, it is no longer listed.
5136
5137 :scheduled List all items which are scheduled for the given date.
5138 The diary for *today* also contains items which were
5139 scheduled earlier and are not yet marked DONE.
5140
5141 :todo List all TODO items from the org-file. This may be a
5142 long list - so this is not turned on by default.
5143 Like deadlines, these entries only show up in the
5144 diary for *today*, not at any other date.
5145
5146 The call in the diary file should look like this:
5147
5148 &%%(org-diary) ~/path/to/some/orgfile.org
5149
5150 Use a separate line for each org file to check. Or, if you omit the file name,
5151 all files listed in `org-agenda-files' will be checked automatically:
5152
5153 &%%(org-diary)
5154
5155 If you don't give any arguments (as in the example above), the default
5156 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5157 also be written as
5158
5159 &%%(org-diary :deadline :timestamp :scheduled)
5160
5161 The function expects the lisp variables `entry' and `date' to be provided
5162 by the caller, because this is how the calendar works. Don't use this
5163 function from a program - use `org-agenda-get-day-entries' instead."
5164 (org-agenda-maybe-reset-markers)
5165 (org-compile-prefix-format org-agenda-prefix-format)
5166 (setq args (or args '(:deadline :scheduled :timestamp)))
5167 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5168 (list entry)
5169 org-agenda-files))
5170 file rtn results)
5171 ;; If this is called during org-agenda, don't return any entries to
5172 ;; the calendar. Org Agenda will list these entries itself.
5173 (if org-disable-agenda-to-diary (setq files nil))
5174 (while (setq file (pop files))
5175 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5176 (setq results (append results rtn)))
5177 (if results
5178 (concat (org-finalize-agenda-entries results) "\n"))))
5179 (defvar org-category-table nil)
5180 (defun org-get-category-table ()
5181 "Get the table of categories and positions in current buffer."
5182 (let (tbl)
5183 (save-excursion
5184 (goto-char (point-min))
5185 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5186 (push (cons (point) (org-trim (match-string 2))) tbl)))
5187 tbl))
5188 (defun org-get-category (&optional pos)
5189 "Get the category applying to position POS."
5190 (if (not org-category-table)
5191 (cond
5192 ((null org-category)
5193 (setq org-category
5194 (if (buffer-file-name)
5195 (file-name-sans-extension
5196 (file-name-nondirectory (buffer-file-name)))
5197 "???")))
5198 ((symbolp org-category) (symbol-name org-category))
5199 (t org-category))
5200 (let ((tbl org-category-table)
5201 (pos (or pos (point))))
5202 (while (and tbl (> (caar tbl) pos))
5203 (pop tbl))
5204 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5205 org-category-table))))))
5206
5207 (defun org-agenda-get-day-entries (file date &rest args)
5208 "Does the work for `org-diary' and `org-agenda'.
5209 FILE is the path to a file to be checked for entries. DATE is date like
5210 the one returned by `calendar-current-date'. ARGS are symbols indicating
5211 which kind of entries should be extracted. For details about these, see
5212 the documentation of `org-diary'."
5213 (setq args (or args '(:deadline :scheduled :timestamp)))
5214 (let* ((org-startup-with-deadline-check nil)
5215 (org-startup-folded nil)
5216 (buffer (if (file-exists-p file)
5217 (org-get-agenda-file-buffer file)
5218 (error "No such file %s" file)))
5219 arg results rtn)
5220 (if (not buffer)
5221 ;; If file does not exist, make sure an error message ends up in diary
5222 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5223 (with-current-buffer buffer
5224 (unless (eq major-mode 'org-mode)
5225 (error "Agenda file %s is not in `org-mode'" file))
5226 (setq org-category-table (org-get-category-table))
5227 (let ((case-fold-search nil))
5228 (save-excursion
5229 (save-restriction
5230 (if org-respect-restriction
5231 (if (org-region-active-p)
5232 ;; Respect a region to restrict search
5233 (narrow-to-region (region-beginning) (region-end)))
5234 ;; If we work for the calendar or many files,
5235 ;; get rid of any restriction
5236 (widen))
5237 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5238 (while (setq arg (pop args))
5239 (cond
5240 ((and (eq arg :todo)
5241 (equal date (calendar-current-date)))
5242 (setq rtn (org-agenda-get-todos))
5243 (setq results (append results rtn)))
5244 ((eq arg :timestamp)
5245 (setq rtn (org-agenda-get-blocks))
5246 (setq results (append results rtn))
5247 (setq rtn (org-agenda-get-timestamps))
5248 (setq results (append results rtn)))
5249 ((eq arg :scheduled)
5250 (setq rtn (org-agenda-get-scheduled))
5251 (setq results (append results rtn)))
5252 ((eq arg :closed)
5253 (setq rtn (org-agenda-get-closed))
5254 (setq results (append results rtn)))
5255 ((and (eq arg :deadline)
5256 (equal date (calendar-current-date)))
5257 (setq rtn (org-agenda-get-deadlines))
5258 (setq results (append results rtn))))))))
5259 results))))
5260
5261 (defun org-entry-is-done-p ()
5262 "Is the current entry marked DONE?"
5263 (save-excursion
5264 (and (re-search-backward "[\r\n]\\*" nil t)
5265 (looking-at org-nl-done-regexp))))
5266
5267 (defun org-at-date-range-p ()
5268 "Is the cursor inside a date range?"
5269 (interactive)
5270 (save-excursion
5271 (catch 'exit
5272 (let ((pos (point)))
5273 (skip-chars-backward "^<\r\n")
5274 (skip-chars-backward "<")
5275 (and (looking-at org-tr-regexp)
5276 (>= (match-end 0) pos)
5277 (throw 'exit t))
5278 (skip-chars-backward "^<\r\n")
5279 (skip-chars-backward "<")
5280 (and (looking-at org-tr-regexp)
5281 (>= (match-end 0) pos)
5282 (throw 'exit t)))
5283 nil)))
5284
5285 (defun org-agenda-get-todos ()
5286 "Return the TODO information for agenda display."
5287 (let* ((props (list 'face nil
5288 'done-face 'org-done
5289 'mouse-face 'highlight
5290 'keymap org-agenda-keymap
5291 'help-echo
5292 (format "mouse-2 or RET jump to org file %s"
5293 (abbreviate-file-name (buffer-file-name)))))
5294 (regexp (concat "[\n\r]\\*+ *\\("
5295 (if org-select-this-todo-keyword
5296 (concat "\\<\\(" org-select-this-todo-keyword
5297 "\\)\\>")
5298 org-not-done-regexp)
5299 "[^\n\r]*\\)"))
5300 marker priority category
5301 ee txt)
5302 (goto-char (point-min))
5303 (while (re-search-forward regexp nil t)
5304 (goto-char (match-beginning 1))
5305 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5306 category (org-get-category)
5307 txt (org-format-agenda-item "" (match-string 1) category)
5308 priority
5309 (+ (org-get-priority txt)
5310 (if org-todo-kwd-priority-p
5311 (- org-todo-kwd-max-priority -2
5312 (length
5313 (member (match-string 2) org-todo-keywords)))
5314 1)))
5315 (add-text-properties
5316 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5317 'priority priority 'category category)
5318 props)
5319 txt)
5320 (push txt ee)
5321 (goto-char (match-end 1)))
5322 (nreverse ee)))
5323
5324 (defconst org-agenda-no-heading-message
5325 "No heading for this item in buffer or region")
5326
5327 (defun org-agenda-get-timestamps ()
5328 "Return the date stamp information for agenda display."
5329 (let* ((props (list 'face nil
5330 'mouse-face 'highlight
5331 'keymap org-agenda-keymap
5332 'help-echo
5333 (format "mouse-2 or RET jump to org file %s"
5334 (abbreviate-file-name (buffer-file-name)))))
5335 (regexp (regexp-quote
5336 (substring
5337 (format-time-string
5338 (car org-time-stamp-formats)
5339 (apply 'encode-time ; DATE bound by calendar
5340 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5341 0 11)))
5342 marker hdmarker deadlinep scheduledp donep tmp priority category
5343 ee txt timestr)
5344 (goto-char (point-min))
5345 (while (re-search-forward regexp nil t)
5346 (if (not (save-match-data (org-at-date-range-p)))
5347 (progn
5348 (setq marker (org-agenda-new-marker (match-beginning 0))
5349 category (org-get-category (match-beginning 0))
5350 tmp (buffer-substring (max (point-min)
5351 (- (match-beginning 0)
5352 org-ds-keyword-length))
5353 (match-beginning 0))
5354 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5355 deadlinep (string-match org-deadline-regexp tmp)
5356 scheduledp (string-match org-scheduled-regexp tmp)
5357 donep (org-entry-is-done-p))
5358 (if (string-match ">" timestr)
5359 ;; substring should only run to end of time stamp
5360 (setq timestr (substring timestr 0 (match-end 0))))
5361 (save-excursion
5362 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5363 (progn
5364 (goto-char (match-end 1))
5365 (setq hdmarker (org-agenda-new-marker))
5366 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5367 (setq txt (org-format-agenda-item
5368 (format "%s%s"
5369 (if deadlinep "Deadline: " "")
5370 (if scheduledp "Scheduled: " ""))
5371 (match-string 1) category timestr)))
5372 (setq txt org-agenda-no-heading-message))
5373 (setq priority (org-get-priority txt))
5374 (add-text-properties
5375 0 (length txt) (append (list 'org-marker marker
5376 'org-hd-marker hdmarker) props)
5377 txt)
5378 (if deadlinep
5379 (add-text-properties
5380 0 (length txt)
5381 (list 'face
5382 (if donep 'org-done 'org-warning)
5383 'undone-face 'org-warning
5384 'done-face 'org-done
5385 'category category
5386 'priority (+ 100 priority))
5387 txt)
5388 (if scheduledp
5389 (add-text-properties
5390 0 (length txt)
5391 (list 'face 'org-scheduled-today
5392 'undone-face 'org-scheduled-today
5393 'done-face 'org-done
5394 'category category
5395 priority (+ 99 priority))
5396 txt)
5397 (add-text-properties
5398 0 (length txt)
5399 (list 'priority priority 'category category) txt)))
5400 (push txt ee))
5401 (outline-next-heading))))
5402 (nreverse ee)))
5403
5404 (defun org-agenda-get-closed ()
5405 "Return the loggedd TODO entries for agenda display."
5406 (let* ((props (list 'mouse-face 'highlight
5407 'keymap org-agenda-keymap
5408 'help-echo
5409 (format "mouse-2 or RET jump to org file %s"
5410 (abbreviate-file-name (buffer-file-name)))))
5411 (regexp (concat
5412 "\\<" org-closed-string " *\\["
5413 (regexp-quote
5414 (substring
5415 (format-time-string
5416 (car org-time-stamp-formats)
5417 (apply 'encode-time ; DATE bound by calendar
5418 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5419 1 11))))
5420 marker hdmarker priority category
5421 ee txt timestr)
5422 (goto-char (point-min))
5423 (while (re-search-forward regexp nil t)
5424 (if (not (save-match-data (org-at-date-range-p)))
5425 (progn
5426 (setq marker (org-agenda-new-marker (match-beginning 0))
5427 category (org-get-category (match-beginning 0))
5428 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5429 ;; donep (org-entry-is-done-p)
5430 )
5431 (if (string-match "\\]" timestr)
5432 ;; substring should only run to end of time stamp
5433 (setq timestr (substring timestr 0 (match-end 0))))
5434 (save-excursion
5435 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5436 (progn
5437 (goto-char (match-end 1))
5438 (setq hdmarker (org-agenda-new-marker))
5439 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5440 (setq txt (org-format-agenda-item
5441 "Closed: "
5442 (match-string 1) category timestr)))
5443 (setq txt org-agenda-no-heading-message))
5444 (setq priority 100000)
5445 (add-text-properties
5446 0 (length txt) (append (list 'org-marker marker
5447 'org-hd-marker hdmarker
5448 'face 'org-done
5449 'priority priority
5450 'category category
5451 'undone-face 'org-warning
5452 'done-face 'org-done) props)
5453 txt)
5454 (push txt ee))
5455 (outline-next-heading))))
5456 (nreverse ee)))
5457
5458 (defun org-agenda-get-deadlines ()
5459 "Return the deadline information for agenda display."
5460 (let* ((wdays org-deadline-warning-days)
5461 (props (list 'mouse-face 'highlight
5462 'keymap org-agenda-keymap
5463 'help-echo
5464 (format "mouse-2 or RET jump to org file %s"
5465 (abbreviate-file-name (buffer-file-name)))))
5466 (regexp org-deadline-time-regexp)
5467 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5468 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5469 d2 diff pos pos1 category
5470 ee txt head)
5471 (goto-char (point-min))
5472 (while (re-search-forward regexp nil t)
5473 (setq pos (1- (match-beginning 1))
5474 d2 (time-to-days
5475 (org-time-string-to-time (match-string 1)))
5476 diff (- d2 d1))
5477 ;; When to show a deadline in the calendar:
5478 ;; If the expiration is within wdays warning time.
5479 ;; Past-due deadlines are only shown on the current date
5480 (if (and (< diff wdays) todayp (not (= diff 0)))
5481 (save-excursion
5482 (setq category (org-get-category))
5483 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5484 (progn
5485 (goto-char (match-end 0))
5486 (setq pos1 (match-end 1))
5487 (setq head (buffer-substring-no-properties
5488 (point)
5489 (progn (skip-chars-forward "^\r\n")
5490 (point))))
5491 (if (string-match org-looking-at-done-regexp head)
5492 (setq txt nil)
5493 (setq txt (org-format-agenda-item
5494 (format "In %3d d.: " diff) head category))))
5495 (setq txt org-agenda-no-heading-message))
5496 (when txt
5497 (add-text-properties
5498 0 (length txt)
5499 (append
5500 (list 'org-marker (org-agenda-new-marker pos)
5501 'org-hd-marker (org-agenda-new-marker pos1)
5502 'priority (+ (- 10 diff) (org-get-priority txt))
5503 'category category
5504 'face (cond ((<= diff 0) 'org-warning)
5505 ((<= diff 5) 'org-scheduled-previously)
5506 (t nil))
5507 'undone-face (cond
5508 ((<= diff 0) 'org-warning)
5509 ((<= diff 5) 'org-scheduled-previously)
5510 (t nil))
5511 'done-face 'org-done)
5512 props)
5513 txt)
5514 (push txt ee)))))
5515 ee))
5516
5517 (defun org-agenda-get-scheduled ()
5518 "Return the scheduled information for agenda display."
5519 (let* ((props (list 'face 'org-scheduled-previously
5520 'undone-face 'org-scheduled-previously
5521 'done-face 'org-done
5522 'mouse-face 'highlight
5523 'keymap org-agenda-keymap
5524 'help-echo
5525 (format "mouse-2 or RET jump to org file %s"
5526 (abbreviate-file-name (buffer-file-name)))))
5527 (regexp org-scheduled-time-regexp)
5528 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5529 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5530 d2 diff pos pos1 category
5531 ee txt head)
5532 (goto-char (point-min))
5533 (while (re-search-forward regexp nil t)
5534 (setq pos (1- (match-beginning 1))
5535 d2 (time-to-days
5536 (org-time-string-to-time (match-string 1)))
5537 diff (- d2 d1))
5538 ;; When to show a scheduled item in the calendar:
5539 ;; If it is on or past the date.
5540 (if (and (< diff 0) todayp)
5541 (save-excursion
5542 (setq category (org-get-category))
5543 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5544 (progn
5545 (goto-char (match-end 0))
5546 (setq pos1 (match-end 1))
5547 (setq head (buffer-substring-no-properties
5548 (point)
5549 (progn (skip-chars-forward "^\r\n") (point))))
5550 (if (string-match org-looking-at-done-regexp head)
5551 (setq txt nil)
5552 (setq txt (org-format-agenda-item
5553 (format "Sched.%2dx: " (- 1 diff)) head
5554 category))))
5555 (setq txt org-agenda-no-heading-message))
5556 (when txt
5557 (add-text-properties
5558 0 (length txt)
5559 (append (list 'org-marker (org-agenda-new-marker pos)
5560 'org-hd-marker (org-agenda-new-marker pos1)
5561 'priority (+ (- 5 diff) (org-get-priority txt))
5562 'category category)
5563 props) txt)
5564 (push txt ee)))))
5565 ee))
5566
5567 (defun org-agenda-get-blocks ()
5568 "Return the date-range information for agenda display."
5569 (let* ((props (list 'face nil
5570 'mouse-face 'highlight
5571 'keymap org-agenda-keymap
5572 'help-echo
5573 (format "mouse-2 or RET jump to org file %s"
5574 (abbreviate-file-name (buffer-file-name)))))
5575 (regexp org-tr-regexp)
5576 (d0 (calendar-absolute-from-gregorian date))
5577 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5578 (goto-char (point-min))
5579 (while (re-search-forward regexp nil t)
5580 (setq timestr (match-string 0)
5581 s1 (match-string 1)
5582 s2 (match-string 2)
5583 d1 (time-to-days (org-time-string-to-time s1))
5584 d2 (time-to-days (org-time-string-to-time s2)))
5585 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5586 ;; Only allow days between the limits, because the normal
5587 ;; date stamps will catch the limits.
5588 (save-excursion
5589 (setq marker (org-agenda-new-marker (point)))
5590 (setq category (org-get-category))
5591 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5592 (progn
5593 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5594 (goto-char (match-end 1))
5595 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5596 (setq txt (org-format-agenda-item
5597 (format (if (= d1 d2) "" "(%d/%d): ")
5598 (1+ (- d0 d1)) (1+ (- d2 d1)))
5599 (match-string 1) category
5600 (if (= d0 d1) timestr))))
5601 (setq txt org-agenda-no-heading-message))
5602 (add-text-properties
5603 0 (length txt) (append (list 'org-marker marker
5604 'org-hd-marker hdmarker
5605 'priority (org-get-priority txt)
5606 'category category)
5607 props)
5608 txt)
5609 (push txt ee)))
5610 (outline-next-heading))
5611 ;; Sort the entries by expiration date.
5612 (nreverse ee)))
5613
5614 (defconst org-plain-time-of-day-regexp
5615 (concat
5616 "\\(\\<[012]?[0-9]"
5617 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5618 "\\(--?"
5619 "\\(\\<[012]?[0-9]"
5620 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5621 "\\)?")
5622 "Regular expression to match a plain time or time range.
5623 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5624 groups carry important information:
5625 0 the full match
5626 1 the first time, range or not
5627 8 the second time, if it is a range.")
5628
5629 (defconst org-stamp-time-of-day-regexp
5630 (concat
5631 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5632 "\\([012][0-9]:[0-5][0-9]\\)>"
5633 "\\(--?"
5634 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5635 "Regular expression to match a timestamp time or time range.
5636 After a match, the following groups carry important information:
5637 0 the full match
5638 1 date plus weekday, for backreferencing to make sure both times on same day
5639 2 the first time, range or not
5640 4 the second time, if it is a range.")
5641
5642 (defvar org-prefix-has-time nil
5643 "A flag, set by `org-compile-prefix-format'.
5644 The flag is set if the currently compiled format contains a `%t'.")
5645
5646 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5647 "Format TXT to be inserted into the agenda buffer.
5648 In particular, it adds the prefix and corresponding text properties. EXTRA
5649 must be a string and replaces the `%s' specifier in the prefix format.
5650 CATEGORY (string, symbol or nil) may be used to overule the default
5651 category taken from local variable or file name. It will replace the `%c'
5652 specifier in the format. DOTIME, when non-nil, indicates that a
5653 time-of-day should be extracted from TXT for sorting of this entry, and for
5654 the `%t' specifier in the format. When DOTIME is a string, this string is
5655 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5656 only the correctly processes TXT should be returned - this is used by
5657 `org-agenda-change-all-lines'."
5658 (save-match-data
5659 ;; Diary entries sometimes have extra whitespace at the beginning
5660 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5661 (let* ((category (or category
5662 org-category
5663 (if (buffer-file-name)
5664 (file-name-sans-extension
5665 (file-name-nondirectory (buffer-file-name)))
5666 "")))
5667 time ;; needed for the eval of the prefix format
5668 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5669 (time-of-day (and dotime (org-get-time-of-day ts)))
5670 stamp plain s0 s1 s2 rtn)
5671 (when (and dotime time-of-day org-prefix-has-time)
5672 ;; Extract starting and ending time and move them to prefix
5673 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5674 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5675 (setq s0 (match-string 0 ts)
5676 s1 (match-string (if plain 1 2) ts)
5677 s2 (match-string (if plain 8 4) ts))
5678
5679 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5680 ;; them, we might want to remove them there to avoid duplication.
5681 ;; The user can turn this off with a variable.
5682 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5683 (string-match (concat (regexp-quote s0) " *") txt)
5684 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5685 (= (match-beginning 0) 0)
5686 t))
5687 (setq txt (replace-match "" nil nil txt))))
5688 ;; Normalize the time(s) to 24 hour
5689 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5690 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5691
5692 ;; Create the final string
5693 (if noprefix
5694 (setq rtn txt)
5695 ;; Prepare the variables needed in the eval of the compiled format
5696 (setq time (cond (s2 (concat s1 "-" s2))
5697 (s1 (concat s1 "......"))
5698 (t ""))
5699 extra (or extra "")
5700 category (if (symbolp category) (symbol-name category) category))
5701 ;; Evaluate the compiled format
5702 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5703
5704 ;; And finally add the text properties
5705 (add-text-properties
5706 0 (length rtn) (list 'category (downcase category)
5707 'prefix-length (- (length rtn) (length txt))
5708 'time-of-day time-of-day
5709 'dotime dotime)
5710 rtn)
5711 rtn)))
5712
5713 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5714 (catch 'exit
5715 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5716 ((and todayp (member 'today (car org-agenda-time-grid))))
5717 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5718 ((member 'weekly (car org-agenda-time-grid)))
5719 (t (throw 'exit list)))
5720 (let* ((have (delq nil (mapcar
5721 (lambda (x) (get-text-property 1 'time-of-day x))
5722 list)))
5723 (string (nth 1 org-agenda-time-grid))
5724 (gridtimes (nth 2 org-agenda-time-grid))
5725 (req (car org-agenda-time-grid))
5726 (remove (member 'remove-match req))
5727 new time)
5728 (if (and (member 'require-timed req) (not have))
5729 ;; don't show empty grid
5730 (throw 'exit list))
5731 (while (setq time (pop gridtimes))
5732 (unless (and remove (member time have))
5733 (setq time (int-to-string time))
5734 (push (org-format-agenda-item
5735 nil string "" ;; FIXME: put a category for the grid?
5736 (concat (substring time 0 -2) ":" (substring time -2)))
5737 new)
5738 (put-text-property
5739 1 (length (car new)) 'face 'org-time-grid (car new))))
5740 (if (member 'time-up org-agenda-sorting-strategy)
5741 (append new list)
5742 (append list new)))))
5743
5744 (defun org-compile-prefix-format (format)
5745 "Compile the prefix format into a Lisp form that can be evaluated.
5746 The resulting form is returned and stored in the variable
5747 `org-prefix-format-compiled'."
5748 (setq org-prefix-has-time nil)
5749 (let ((start 0) varform vars var (s format) c f opt)
5750 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5751 s start)
5752 (setq var (cdr (assoc (match-string 4 s)
5753 '(("c" . category) ("t" . time) ("s" . extra))))
5754 c (or (match-string 3 s) "")
5755 opt (match-beginning 1)
5756 start (1+ (match-beginning 0)))
5757 (if (equal var 'time) (setq org-prefix-has-time t))
5758 (setq f (concat "%" (match-string 2 s) "s"))
5759 (if opt
5760 (setq varform
5761 `(if (equal "" ,var)
5762 ""
5763 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5764 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5765 (setq s (replace-match "%s" t nil s))
5766 (push varform vars))
5767 (setq vars (nreverse vars))
5768 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5769
5770 (defun org-get-time-of-day (s &optional string)
5771 "Check string S for a time of day.
5772 If found, return it as a military time number between 0 and 2400.
5773 If not found, return nil.
5774 The optional STRING argument forces conversion into a 5 character wide string
5775 HH:MM."
5776 (save-match-data
5777 (when
5778 (or
5779 (string-match
5780 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5781 (string-match
5782 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5783 (let* ((t0 (+ (* 100
5784 (+ (string-to-number (match-string 1 s))
5785 (if (and (match-beginning 4)
5786 (equal (downcase (match-string 4 s)) "pm"))
5787 12 0)))
5788 (if (match-beginning 3)
5789 (string-to-number (match-string 3 s))
5790 0)))
5791 (t1 (concat " " (int-to-string t0))))
5792 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5793
5794 (defun org-finalize-agenda-entries (list)
5795 "Sort and concatenate the agenda items."
5796 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5797
5798 (defsubst org-cmp-priority (a b)
5799 "Compare the priorities of string a and b."
5800 (let ((pa (or (get-text-property 1 'priority a) 0))
5801 (pb (or (get-text-property 1 'priority b) 0)))
5802 (cond ((> pa pb) +1)
5803 ((< pa pb) -1)
5804 (t nil))))
5805
5806 (defsubst org-cmp-category (a b)
5807 "Compare the string values of categories of strings a and b."
5808 (let ((ca (or (get-text-property 1 'category a) ""))
5809 (cb (or (get-text-property 1 'category b) "")))
5810 (cond ((string-lessp ca cb) -1)
5811 ((string-lessp cb ca) +1)
5812 (t nil))))
5813
5814 (defsubst org-cmp-time (a b)
5815 "Compare the time-of-day values of strings a and b."
5816 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5817 (ta (or (get-text-property 1 'time-of-day a) def))
5818 (tb (or (get-text-property 1 'time-of-day b) def)))
5819 (cond ((< ta tb) -1)
5820 ((< tb ta) +1)
5821 (t nil))))
5822
5823 (defun org-entries-lessp (a b)
5824 "Predicate for sorting agenda entries."
5825 ;; The following variables will be used when the form is evaluated.
5826 (let* ((time-up (org-cmp-time a b))
5827 (time-down (if time-up (- time-up) nil))
5828 (priority-up (org-cmp-priority a b))
5829 (priority-down (if priority-up (- priority-up) nil))
5830 (category-up (org-cmp-category a b))
5831 (category-down (if category-up (- category-up) nil))
5832 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5833 (cdr (assoc
5834 (eval (cons 'or org-agenda-sorting-strategy))
5835 '((-1 . t) (1 . nil) (nil . nil))))))
5836
5837 (defun org-agenda-show-priority ()
5838 "Show the priority of the current item.
5839 This priority is composed of the main priority given with the [#A] cookies,
5840 and by additional input from the age of a schedules or deadline entry."
5841 (interactive)
5842 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5843 (message "Priority is %d" (if pri pri -1000))))
5844
5845 (defun org-agenda-goto (&optional highlight)
5846 "Go to the Org-mode file which contains the item at point."
5847 (interactive)
5848 (let* ((marker (or (get-text-property (point) 'org-marker)
5849 (org-agenda-error)))
5850 (buffer (marker-buffer marker))
5851 (pos (marker-position marker)))
5852 (switch-to-buffer-other-window buffer)
5853 (widen)
5854 (goto-char pos)
5855 (when (eq major-mode 'org-mode)
5856 (org-show-hidden-entry)
5857 (save-excursion
5858 (and (outline-next-heading)
5859 (org-flag-heading nil)))) ; show the next heading
5860 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5861
5862 (defun org-agenda-switch-to ()
5863 "Go to the Org-mode file which contains the item at point."
5864 (interactive)
5865 (let* ((marker (or (get-text-property (point) 'org-marker)
5866 (org-agenda-error)))
5867 (buffer (marker-buffer marker))
5868 (pos (marker-position marker)))
5869 (switch-to-buffer buffer)
5870 (delete-other-windows)
5871 (widen)
5872 (goto-char pos)
5873 (when (eq major-mode 'org-mode)
5874 (org-show-hidden-entry)
5875 (save-excursion
5876 (and (outline-next-heading)
5877 (org-flag-heading nil)))))) ; show the next heading
5878
5879 (defun org-agenda-goto-mouse (ev)
5880 "Go to the Org-mode file which contains the item at the mouse click."
5881 (interactive "e")
5882 (mouse-set-point ev)
5883 (org-agenda-goto))
5884
5885 (defun org-agenda-show ()
5886 "Display the Org-mode file which contains the item at point."
5887 (interactive)
5888 (let ((win (selected-window)))
5889 (org-agenda-goto t)
5890 (select-window win)))
5891
5892 (defun org-agenda-recenter (arg)
5893 "Display the Org-mode file which contains the item at point and recenter."
5894 (interactive "P")
5895 (let ((win (selected-window)))
5896 (org-agenda-goto t)
5897 (recenter arg)
5898 (select-window win)))
5899
5900 (defun org-agenda-show-mouse (ev)
5901 "Display the Org-mode file which contains the item at the mouse click."
5902 (interactive "e")
5903 (mouse-set-point ev)
5904 (org-agenda-show))
5905
5906 (defun org-agenda-check-no-diary ()
5907 "Check if the entry is a diary link and abort if yes."
5908 (if (get-text-property (point) 'org-agenda-diary-link)
5909 (org-agenda-error)))
5910
5911 (defun org-agenda-error ()
5912 (error "Command not allowed in this line"))
5913
5914 (defvar org-last-heading-marker (make-marker)
5915 "Marker pointing to the headline that last changed its TODO state
5916 by a remote command from the agenda.")
5917
5918 (defun org-agenda-todo (&optional arg)
5919 "Cycle TODO state of line at point, also in Org-mode file.
5920 This changes the line at point, all other lines in the agenda referring to
5921 the same tree node, and the headline of the tree node in the Org-mode file."
5922 (interactive "P")
5923 (org-agenda-check-no-diary)
5924 (let* ((col (current-column))
5925 (marker (or (get-text-property (point) 'org-marker)
5926 (org-agenda-error)))
5927 (buffer (marker-buffer marker))
5928 (pos (marker-position marker))
5929 (hdmarker (get-text-property (point) 'org-hd-marker))
5930 (buffer-read-only nil)
5931 newhead)
5932 (with-current-buffer buffer
5933 (widen)
5934 (goto-char pos)
5935 (org-show-hidden-entry)
5936 (save-excursion
5937 (and (outline-next-heading)
5938 (org-flag-heading nil))) ; show the next heading
5939 (org-todo arg)
5940 (forward-char 1)
5941 (setq newhead (org-get-heading))
5942 (save-excursion
5943 (org-back-to-heading)
5944 (move-marker org-last-heading-marker (point))))
5945 (beginning-of-line 1)
5946 (save-excursion
5947 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5948 (move-to-column col)))
5949
5950 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5951 "Change all lines in the agenda buffer which match hdmarker.
5952 The new content of the line will be NEWHEAD (as modified by
5953 `org-format-agenda-item'). HDMARKER is checked with
5954 `equal' against all `org-hd-marker' text properties in the file.
5955 If FIXFACE is non-nil, the face of each item is modified acording to
5956 the new TODO state."
5957 (let* (props m pl undone-face done-face finish new dotime cat)
5958 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5959 (save-excursion
5960 (goto-char (point-max))
5961 (beginning-of-line 1)
5962 (while (not finish)
5963 (setq finish (bobp))
5964 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5965 (equal m hdmarker))
5966 (setq props (text-properties-at (point))
5967 dotime (get-text-property (point) 'dotime)
5968 cat (get-text-property (point) 'category)
5969 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
5970 pl (get-text-property (point) 'prefix-length)
5971 undone-face (get-text-property (point) 'undone-face)
5972 done-face (get-text-property (point) 'done-face))
5973 (move-to-column pl)
5974 (if (looking-at ".*")
5975 (progn
5976 (replace-match new t t)
5977 (beginning-of-line 1)
5978 (add-text-properties (point-at-bol) (point-at-eol) props)
5979 (if fixface
5980 (add-text-properties
5981 (point-at-bol) (point-at-eol)
5982 (list 'face
5983 (if org-last-todo-state-is-todo
5984 undone-face done-face))))
5985 (beginning-of-line 1))
5986 (error "Line update did not work")))
5987 (beginning-of-line 0)))))
5988
5989 (defun org-agenda-priority-up ()
5990 "Increase the priority of line at point, also in Org-mode file."
5991 (interactive)
5992 (org-agenda-priority 'up))
5993
5994 (defun org-agenda-priority-down ()
5995 "Decrease the priority of line at point, also in Org-mode file."
5996 (interactive)
5997 (org-agenda-priority 'down))
5998
5999 (defun org-agenda-priority (&optional force-direction)
6000 "Set the priority of line at point, also in Org-mode file.
6001 This changes the line at point, all other lines in the agenda referring to
6002 the same tree node, and the headline of the tree node in the Org-mode file."
6003 (interactive)
6004 (org-agenda-check-no-diary)
6005 (let* ((marker (or (get-text-property (point) 'org-marker)
6006 (org-agenda-error)))
6007 (buffer (marker-buffer marker))
6008 (pos (marker-position marker))
6009 (hdmarker (get-text-property (point) 'org-hd-marker))
6010 (buffer-read-only nil)
6011 newhead)
6012 (with-current-buffer buffer
6013 (widen)
6014 (goto-char pos)
6015 (org-show-hidden-entry)
6016 (save-excursion
6017 (and (outline-next-heading)
6018 (org-flag-heading nil))) ; show the next heading
6019 (funcall 'org-priority force-direction)
6020 (end-of-line 1)
6021 (setq newhead (org-get-heading)))
6022 (org-agenda-change-all-lines newhead hdmarker)
6023 (beginning-of-line 1)))
6024
6025 (defun org-agenda-set-tags ()
6026 "Set tags for the current headline."
6027 (interactive)
6028 (org-agenda-check-no-diary)
6029 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6030 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6031 (org-agenda-error)))
6032 (buffer (marker-buffer hdmarker))
6033 (pos (marker-position hdmarker))
6034 (buffer-read-only nil)
6035 newhead)
6036 (with-current-buffer buffer
6037 (widen)
6038 (goto-char pos)
6039 (org-show-hidden-entry)
6040 (save-excursion
6041 (and (outline-next-heading)
6042 (org-flag-heading nil))) ; show the next heading
6043 (call-interactively 'org-set-tags)
6044 (end-of-line 1)
6045 (setq newhead (org-get-heading)))
6046 (org-agenda-change-all-lines newhead hdmarker)
6047 (beginning-of-line 1)))
6048
6049 (defun org-agenda-date-later (arg &optional what)
6050 "Change the date of this item to one day later."
6051 (interactive "p")
6052 (org-agenda-check-type t 'agenda 'timeline)
6053 (org-agenda-check-no-diary)
6054 (let* ((marker (or (get-text-property (point) 'org-marker)
6055 (org-agenda-error)))
6056 (buffer (marker-buffer marker))
6057 (pos (marker-position marker)))
6058 (with-current-buffer buffer
6059 (widen)
6060 (goto-char pos)
6061 (if (not (org-at-timestamp-p))
6062 (error "Cannot find time stamp"))
6063 (org-timestamp-change arg (or what 'day))
6064 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6065
6066 (defun org-agenda-date-earlier (arg &optional what)
6067 "Change the date of this item to one day earlier."
6068 (interactive "p")
6069 (org-agenda-date-later (- arg) what))
6070
6071 (defun org-agenda-date-prompt (arg)
6072 "Change the date of this item. Date is prompted for, with default today.
6073 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6074 be used to request time specification in the time stamp."
6075 (interactive "P")
6076 (org-agenda-check-type t 'agenda 'timeline)
6077 (org-agenda-check-no-diary)
6078 (let* ((marker (or (get-text-property (point) 'org-marker)
6079 (org-agenda-error)))
6080 (buffer (marker-buffer marker))
6081 (pos (marker-position marker)))
6082 (with-current-buffer buffer
6083 (widen)
6084 (goto-char pos)
6085 (if (not (org-at-timestamp-p))
6086 (error "Cannot find time stamp"))
6087 (org-time-stamp arg)
6088 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6089
6090 (defun org-get-heading ()
6091 "Return the heading of the current entry, without the stars."
6092 (save-excursion
6093 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6094 ;;FIXME???????? (and (bolp) (end-of-line 1))
6095 (if (and (re-search-backward "[\r\n]\\*" nil t)
6096 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6097 (match-string 1)
6098 "")))
6099
6100 (defun org-agenda-diary-entry ()
6101 "Make a diary entry, like the `i' command from the calendar.
6102 All the standard commands work: block, weekly etc"
6103 (interactive)
6104 (org-agenda-check-type t 'agenda 'timeline)
6105 (require 'diary-lib)
6106 (let* ((char (progn
6107 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6108 (read-char-exclusive)))
6109 (cmd (cdr (assoc char
6110 '((?d . insert-diary-entry)
6111 (?w . insert-weekly-diary-entry)
6112 (?m . insert-monthly-diary-entry)
6113 (?y . insert-yearly-diary-entry)
6114 (?a . insert-anniversary-diary-entry)
6115 (?b . insert-block-diary-entry)
6116 (?c . insert-cyclic-diary-entry)))))
6117 (oldf (symbol-function 'calendar-cursor-to-date))
6118 (point (point))
6119 (mark (or (mark t) (point))))
6120 (unless cmd
6121 (error "No command associated with <%c>" char))
6122 (unless (and (get-text-property point 'day)
6123 (or (not (equal ?b char))
6124 (get-text-property mark 'day)))
6125 (error "Don't know which date to use for diary entry"))
6126 ;; We implement this by hacking the `calendar-cursor-to-date' function
6127 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6128 (let ((calendar-mark-ring
6129 (list (calendar-gregorian-from-absolute
6130 (or (get-text-property mark 'day)
6131 (get-text-property point 'day))))))
6132 (unwind-protect
6133 (progn
6134 (fset 'calendar-cursor-to-date
6135 (lambda (&optional error)
6136 (calendar-gregorian-from-absolute
6137 (get-text-property point 'day))))
6138 (call-interactively cmd))
6139 (fset 'calendar-cursor-to-date oldf)))))
6140
6141
6142 (defun org-agenda-execute-calendar-command (cmd)
6143 "Execute a calendar command from the agenda, with the date associated to
6144 the cursor position."
6145 (org-agenda-check-type t 'agenda 'timeline)
6146 (require 'diary-lib)
6147 (unless (get-text-property (point) 'day)
6148 (error "Don't know which date to use for calendar command"))
6149 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6150 (point (point))
6151 (date (calendar-gregorian-from-absolute
6152 (get-text-property point 'day)))
6153 (displayed-day (extract-calendar-day date))
6154 (displayed-month (extract-calendar-month date))
6155 (displayed-year (extract-calendar-year date)))
6156 (unwind-protect
6157 (progn
6158 (fset 'calendar-cursor-to-date
6159 (lambda (&optional error)
6160 (calendar-gregorian-from-absolute
6161 (get-text-property point 'day))))
6162 (call-interactively cmd))
6163 (fset 'calendar-cursor-to-date oldf))))
6164
6165 (defun org-agenda-phases-of-moon ()
6166 "Display the phases of the moon for the 3 months around the cursor date."
6167 (interactive)
6168 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6169
6170 (defun org-agenda-holidays ()
6171 "Display the holidays for the 3 months around the cursor date."
6172 (interactive)
6173 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6174
6175 (defun org-agenda-sunrise-sunset (arg)
6176 "Display sunrise and sunset for the cursor date.
6177 Latitude and longitude can be specified with the variables
6178 `calendar-latitude' and `calendar-longitude'. When called with prefix
6179 argument, latitude and longitude will be prompted for."
6180 (interactive "P")
6181 (let ((calendar-longitude (if arg nil calendar-longitude))
6182 (calendar-latitude (if arg nil calendar-latitude))
6183 (calendar-location-name
6184 (if arg "the given coordinates" calendar-location-name)))
6185 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6186
6187 (defun org-agenda-goto-calendar ()
6188 "Open the Emacs calendar with the date at the cursor."
6189 (interactive)
6190 (org-agenda-check-type t 'agenda 'timeline)
6191 (let* ((day (or (get-text-property (point) 'day)
6192 (error "Don't know which date to open in calendar")))
6193 (date (calendar-gregorian-from-absolute day))
6194 (calendar-move-hook nil)
6195 (view-diary-entries-initially nil))
6196 (calendar)
6197 (calendar-goto-date date)))
6198
6199 (defun org-calendar-goto-agenda ()
6200 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6201 This is a command that has to be installed in `calendar-mode-map'."
6202 (interactive)
6203 (org-agenda-list nil (calendar-absolute-from-gregorian
6204 (calendar-cursor-to-date))
6205 nil t))
6206
6207 (defun org-agenda-convert-date ()
6208 (interactive)
6209 (org-agenda-check-type t 'agenda 'timeline)
6210 (let ((day (get-text-property (point) 'day))
6211 date s)
6212 (unless day
6213 (error "Don't know which date to convert"))
6214 (setq date (calendar-gregorian-from-absolute day))
6215 (setq s (concat
6216 "Gregorian: " (calendar-date-string date) "\n"
6217 "ISO: " (calendar-iso-date-string date) "\n"
6218 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6219 "Julian: " (calendar-julian-date-string date) "\n"
6220 "Astron. JD: " (calendar-astro-date-string date)
6221 " (Julian date number at noon UTC)\n"
6222 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6223 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6224 "French: " (calendar-french-date-string date) "\n"
6225 "Mayan: " (calendar-mayan-date-string date) "\n"
6226 "Coptic: " (calendar-coptic-date-string date) "\n"
6227 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6228 "Persian: " (calendar-persian-date-string date) "\n"
6229 "Chinese: " (calendar-chinese-date-string date) "\n"))
6230 (with-output-to-temp-buffer "*Dates*"
6231 (princ s))
6232 (if (fboundp 'fit-window-to-buffer)
6233 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6234
6235 ;;; Tags
6236
6237 (defun org-scan-tags (action matcher &optional todo-only)
6238 "Scan headline tags with inheritance and produce output ACTION.
6239 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6240 evaluated, testing if a given set of tags qualifies a headline for
6241 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6242 d are included in the output."
6243 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6244 (mapconcat 'regexp-quote
6245 (nreverse (cdr (reverse org-todo-keywords)))
6246 "\\|")
6247 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6248 (props (list 'face nil
6249 'done-face 'org-done
6250 'undone-face nil
6251 'mouse-face 'highlight
6252 'keymap org-agenda-keymap
6253 'help-echo
6254 (format "mouse-2 or RET jump to org file %s"
6255 (abbreviate-file-name (buffer-file-name)))))
6256 lspos
6257 tags tags-list tags-alist (llast 0) rtn level category i txt
6258 todo marker)
6259
6260 (save-excursion
6261 (goto-char (point-min))
6262 (when (eq action 'sparse-tree) (hide-sublevels 1))
6263 (while (re-search-forward re nil t)
6264 (setq todo (if (match-end 1) (match-string 2))
6265 tags (if (match-end 4) (match-string 4)))
6266 (goto-char (setq lspos (1+ (match-beginning 0))))
6267 (setq level (outline-level)
6268 category (org-get-category))
6269 (setq i llast llast level)
6270 ;; remove tag lists from same and sublevels
6271 (while (>= i level)
6272 (when (setq entry (assoc i tags-alist))
6273 (setq tags-alist (delete entry tags-alist)))
6274 (setq i (1- i)))
6275 ;; add the nex tags
6276 (when tags
6277 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6278 tags-alist
6279 (cons (cons level tags) tags-alist)))
6280 ;; compile tags for current headline
6281 (setq tags-list
6282 (if org-use-tag-inheritance
6283 (apply 'append (mapcar 'cdr tags-alist))
6284 tags))
6285 (when (and (or (not todo-only) todo)
6286 (eval matcher))
6287 ;; list this headline
6288 (if (eq action 'sparse-tree)
6289 (progn
6290 (org-show-hierarchy-above))
6291 (setq txt (org-format-agenda-item
6292 ""
6293 (concat
6294 (if org-tags-match-list-sublevels
6295 (make-string (1- level) ?.) "")
6296 (org-get-heading))
6297 category))
6298 (goto-char lspos)
6299 (setq marker (org-agenda-new-marker))
6300 (add-text-properties
6301 0 (length txt)
6302 (append (list 'org-marker marker 'org-hd-marker marker
6303 'category category)
6304 props)
6305 txt)
6306 (push txt rtn))
6307 ;; if we are to skip sublevels, jump to end of subtree
6308 (point)
6309 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6310 (nreverse rtn)))
6311
6312 (defun org-tags-sparse-tree (&optional arg match)
6313 "Create a sparse tree according to tags search string MATCH.
6314 MATCH can contain positive and negative selection of tags, like
6315 \"+WORK+URGENT-WITHBOSS\"."
6316 (interactive "P")
6317 (let ((org-show-following-heading nil)
6318 (org-show-hierarchy-above nil))
6319 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6320
6321 (defun org-make-tags-matcher (match)
6322 "Create the TAGS matcher form for the tags-selecting string MATCH."
6323 (unless match
6324 ;; Get a new match request, with completion
6325 (setq org-last-tags-completion-table
6326 (or (org-get-buffer-tags)
6327 org-last-tags-completion-table))
6328 (setq match (completing-read
6329 "Tags: " 'org-tags-completion-function nil nil nil
6330 'org-tags-history)))
6331 ;; parse the string and create a lisp form
6332 (let ((match0 match) minus tag mm matcher orterms term orlist)
6333 (setq orterms (org-split-string match "|"))
6334 (while (setq term (pop orterms))
6335 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6336 (setq minus (and (match-end 1)
6337 (equal (match-string 1 term) "-"))
6338 tag (match-string 2 term)
6339 term (substring term (match-end 0))
6340 mm (list 'member (downcase tag) 'tags-list)
6341 mm (if minus (list 'not mm) mm))
6342 (push mm matcher))
6343 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6344 orlist)
6345 (setq matcher nil))
6346 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6347 ;; Return the string and lisp forms of the matcher
6348 (cons match0 matcher)))
6349
6350 ;;;###autoload
6351 (defun org-tags-view (&optional todo-only match keep-modes)
6352 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6353 The prefix arg TODO-ONLY limits the search to TODO entries."
6354 (interactive "P")
6355 (org-agenda-maybe-reset-markers 'force)
6356 (org-compile-prefix-format org-agenda-prefix-format)
6357 (let* ((org-agenda-keep-modes keep-modes)
6358 (org-tags-match-list-sublevels
6359 (if todo-only t org-tags-match-list-sublevels))
6360 (win (selected-window))
6361 (completion-ignore-case t)
6362 rtn rtnall files file pos matcher
6363 buffer)
6364 (setq matcher (org-make-tags-matcher match)
6365 match (car matcher) matcher (cdr matcher))
6366 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6367 (progn
6368 (delete-other-windows)
6369 (switch-to-buffer-other-window
6370 (get-buffer-create org-agenda-buffer-name))))
6371 (setq buffer-read-only nil)
6372 (erase-buffer)
6373 (org-agenda-mode) (setq buffer-read-only nil)
6374 (set (make-local-variable 'org-agenda-type) 'tags)
6375 (set (make-local-variable 'org-agenda-redo-command)
6376 (list 'org-tags-view (list 'quote todo-only)
6377 (list 'if 'current-prefix-arg nil match) t))
6378 (setq files (org-agenda-files)
6379 rtnall nil)
6380 (while (setq file (pop files))
6381 (catch 'nextfile
6382 (org-check-agenda-file file)
6383 (setq buffer (if (file-exists-p file)
6384 (org-get-agenda-file-buffer file)
6385 (error "No such file %s" file)))
6386 (if (not buffer)
6387 ;; If file does not exist, merror message to agenda
6388 (setq rtn (list
6389 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6390 rtnall (append rtnall rtn))
6391 (with-current-buffer buffer
6392 (unless (eq major-mode 'org-mode)
6393 (error "Agenda file %s is not in `org-mode'" file))
6394 (save-excursion
6395 (save-restriction
6396 (if org-respect-restriction
6397 (if (org-region-active-p)
6398 ;; Respect a region to restrict search
6399 (narrow-to-region (region-beginning) (region-end)))
6400 ;; If we work for the calendar or many files,
6401 ;; get rid of any restriction
6402 (widen))
6403 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6404 (setq rtnall (append rtnall rtn))))))))
6405 (insert "Headlines with TAGS match: ")
6406 (add-text-properties (point-min) (1- (point))
6407 (list 'face 'org-link))
6408 (setq pos (point))
6409 (insert match "\n")
6410 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6411 (setq pos (point))
6412 (insert "Press `C-u r' to search again with new search string\n")
6413 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6414 (when rtnall
6415 (insert (mapconcat 'identity rtnall "\n")))
6416 (goto-char (point-min))
6417 (setq buffer-read-only t)
6418 (org-fit-agenda-window)
6419 (if (not org-select-agenda-window) (select-window win))))
6420
6421 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6422 (defun org-set-tags (&optional arg just-align)
6423 "Set the tags for the current headline.
6424 With prefix ARG, realign all tags in headings in the current buffer."
6425 (interactive)
6426 (let* (;(inherit (org-get-inherited-tags))
6427 (re (concat "^" outline-regexp))
6428 (col (current-column))
6429 (current (org-get-tags))
6430 tags hd empty)
6431 (if arg
6432 (save-excursion
6433 (goto-char (point-min))
6434 (while (re-search-forward re nil t)
6435 (org-set-tags nil t))
6436 (message "All tags realigned to column %d" org-tags-column))
6437 (if just-align
6438 (setq tags current)
6439 (setq org-last-tags-completion-table
6440 (or (org-get-buffer-tags)
6441 org-last-tags-completion-table))
6442 (setq tags
6443 (let ((org-add-colon-after-tag-completion t))
6444 (completing-read "Tags: " 'org-tags-completion-function
6445 nil nil current 'org-tags-history)))
6446 (while (string-match "[-+&]+" tags)
6447 (setq tags (replace-match ":" t t tags)))
6448 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6449 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6450 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6451 (if (equal current "")
6452 (progn
6453 (end-of-line 1)
6454 (or empty (insert " ")))
6455 (beginning-of-line 1)
6456 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6457 (setq hd (match-string 1))
6458 (delete-region (match-beginning 0) (match-end 0))
6459 (insert (org-trim hd) (if empty "" " ")))
6460 (unless (equal tags "")
6461 (move-to-column (max (current-column)
6462 (if (> org-tags-column 0)
6463 org-tags-column
6464 (- (- org-tags-column) (length tags))))
6465 t)
6466 (insert tags))
6467 (move-to-column col))))
6468
6469 (defun org-tags-completion-function (string predicate &optional flag)
6470 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6471 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6472 (setq s1 (match-string 1 string)
6473 s2 (match-string 2 string))
6474 (setq s1 "" s2 string))
6475 (cond
6476 ((eq flag nil)
6477 ;; try completion
6478 (setq rtn (try-completion s2 ctable))
6479 (if (stringp rtn)
6480 (concat s1 s2 (substring rtn (length s2))
6481 (if (and org-add-colon-after-tag-completion
6482 (assoc rtn ctable))
6483 ":" "")))
6484 )
6485 ((eq flag t)
6486 ;; all-completions
6487 (all-completions s2 ctable)
6488 )
6489 ((eq flag 'lambda)
6490 ;; exact match?
6491 (assoc s2 ctable)))
6492 ))
6493
6494 (defun org-get-tags ()
6495 "Get the TAGS string in the current headline."
6496 (unless (org-on-heading-p)
6497 (error "Not on a heading"))
6498 (save-excursion
6499 (beginning-of-line 1)
6500 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6501 (match-string 1)
6502 "")))
6503
6504 (defun org-get-buffer-tags ()
6505 "Get a table of all tags used in the buffer, for completion."
6506 (let (tags)
6507 (save-excursion
6508 (goto-char (point-min))
6509 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6510 (mapc (lambda (x) (add-to-list 'tags x))
6511 (org-split-string (match-string 1) ":"))))
6512 (mapcar 'list tags)))
6513
6514 ;;; Link Stuff
6515
6516 (defun org-find-file-at-mouse (ev)
6517 "Open file link or URL at mouse."
6518 (interactive "e")
6519 (mouse-set-point ev)
6520 (org-open-at-point 'in-emacs))
6521
6522 (defun org-open-at-mouse (ev)
6523 "Open file link or URL at mouse."
6524 (interactive "e")
6525 (mouse-set-point ev)
6526 (org-open-at-point))
6527
6528 (defun org-open-at-point (&optional in-emacs)
6529 "Open link at or after point.
6530 If there is no link at point, this function will search forward up to
6531 the end of the current subtree.
6532 Normally, files will be opened by an appropriate application. If the
6533 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6534 (interactive "P")
6535 (org-remove-occur-highlights nil nil t)
6536 (if (org-at-timestamp-p)
6537 (org-agenda-list nil (time-to-days (org-time-string-to-time
6538 (substring (match-string 1) 0 10)))
6539 1)
6540 (let (type path line search (pos (point)))
6541 (catch 'match
6542 (save-excursion
6543 (skip-chars-backward
6544 (concat (if org-allow-space-in-links "^" "^ ")
6545 org-non-link-chars))
6546 (when (looking-at org-link-regexp)
6547 (setq type (match-string 1)
6548 path (match-string 2))
6549 (throw 'match t)))
6550 (save-excursion
6551 (skip-chars-backward "^ \t\n\r")
6552 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6553 (setq type "tags"
6554 path (match-string 1))
6555 (while (string-match ":" path)
6556 (setq path (replace-match "+" t t path)))
6557 (throw 'match t)))
6558 (save-excursion
6559 (skip-chars-backward "a-zA-Z_")
6560 (when (looking-at org-camel-regexp)
6561 (setq type "camel" path (match-string 0))
6562 (if (equal (char-before) ?*)
6563 (setq path (concat "*" path))))
6564 (throw 'match t))
6565 (save-excursion
6566 (when (re-search-forward
6567 org-link-regexp
6568 (save-excursion
6569 (condition-case nil
6570 (progn (outline-end-of-subtree) (max pos (point)))
6571 (error (end-of-line 1) (point))))
6572 t)
6573 (setq type (match-string 1)
6574 path (match-string 2)))))
6575 (unless path
6576 (error "No link found"))
6577 ;; Remove any trailing spaces in path
6578 (if (string-match " +\\'" path)
6579 (setq path (replace-match "" t t path)))
6580
6581 (cond
6582
6583 ((string= type "tags")
6584 (org-tags-view path in-emacs))
6585 ((string= type "camel")
6586 (org-link-search
6587 path
6588 (cond ((equal in-emacs '(4)) 'occur)
6589 ((equal in-emacs '(16)) 'org-occur)
6590 (t nil))))
6591
6592 ((string= type "file")
6593 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6594 (setq line (string-to-number (match-string 1 path))
6595 path (substring path 0 (match-beginning 0)))
6596 (if (string-match "::\\(.+\\)\\'" path)
6597 (setq search (match-string 1 path)
6598 path (substring path 0 (match-beginning 0)))))
6599 (org-open-file path in-emacs line search))
6600
6601 ((string= type "news")
6602 (org-follow-gnus-link path))
6603
6604 ((string= type "bbdb")
6605 (org-follow-bbdb-link path))
6606
6607 ((string= type "gnus")
6608 (let (group article)
6609 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6610 (error "Error in Gnus link"))
6611 (setq group (match-string 1 path)
6612 article (match-string 3 path))
6613 (org-follow-gnus-link group article)))
6614
6615 ((string= type "vm")
6616 (let (folder article)
6617 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6618 (error "Error in VM link"))
6619 (setq folder (match-string 1 path)
6620 article (match-string 3 path))
6621 ;; in-emacs is the prefix arg, will be interpreted as read-only
6622 (org-follow-vm-link folder article in-emacs)))
6623
6624 ((string= type "wl")
6625 (let (folder article)
6626 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6627 (error "Error in Wanderlust link"))
6628 (setq folder (match-string 1 path)
6629 article (match-string 3 path))
6630 (org-follow-wl-link folder article)))
6631
6632 ((string= type "rmail")
6633 (let (folder article)
6634 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6635 (error "Error in RMAIL link"))
6636 (setq folder (match-string 1 path)
6637 article (match-string 3 path))
6638 (org-follow-rmail-link folder article)))
6639
6640 ((string= type "shell")
6641 (let ((cmd path))
6642 (while (string-match "@{" cmd)
6643 (setq cmd (replace-match "<" t t cmd)))
6644 (while (string-match "@}" cmd)
6645 (setq cmd (replace-match ">" t t cmd)))
6646 (if (or (not org-confirm-shell-links)
6647 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6648 (shell-command cmd)
6649 (error "Abort"))))
6650
6651 (t
6652 (browse-url-at-point))))))
6653
6654 (defun org-link-search (s &optional type)
6655 "Search for a link search option.
6656 When S is a CamelCaseWord, search for a target, or for a sentence containing
6657 the words. If S is surrounded by forward slashes, it is interpreted as a
6658 regular expression. In org-mode files, this will create an `org-occur'
6659 sparse tree. In ordinary files, `occur' will be used to list matched.
6660 If the current buffer is in `dired-mode', grep will be used to search
6661 in all files."
6662 (let ((case-fold-search t)
6663 (s0 s)
6664 (pos (point))
6665 (pre "") (post "")
6666 words re0 re1 re2 re3 re4 re5 reall)
6667 (cond ((string-match "^/\\(.*\\)/$" s)
6668 ;; A regular expression
6669 (cond
6670 ((eq major-mode 'org-mode)
6671 (org-occur (match-string 1 s)))
6672 ;;((eq major-mode 'dired-mode)
6673 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6674 (t (org-do-occur (match-string 1 s)))))
6675 ((string-match (concat "^" org-camel-regexp) s)
6676 ;; A camel
6677 (if (equal (string-to-char s) ?*)
6678 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6679 post "[ \t]*$"
6680 s (substring s 1)))
6681 (remove-text-properties
6682 0 (length s)
6683 '(face nil mouse-face nil keymap nil fontified nil) s)
6684 ;; Make a series of regular expressions to find a match
6685 (setq words (org-camel-to-words s)
6686 re0 (concat "<<" (regexp-quote s0) ">>")
6687 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6688 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6689 re1 (concat pre re2 post)
6690 re3 (concat pre re4 post)
6691 re5 (concat pre ".*" re4)
6692 re2 (concat pre re2)
6693 re4 (concat pre re4)
6694 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6695 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6696 re5 "\\)"
6697 ))
6698 (cond
6699 ((eq type 'org-occur) (org-occur reall))
6700 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6701 (t (goto-char (point-min))
6702 (if (or (re-search-forward re0 nil t)
6703 (re-search-forward re1 nil t)
6704 (re-search-forward re2 nil t)
6705 (re-search-forward re3 nil t)
6706 (re-search-forward re4 nil t)
6707 (re-search-forward re5 nil t))
6708 (goto-char (match-beginning 0))
6709 (goto-char pos)
6710 (error "No match")))))
6711 (t
6712 ;; Normal string-search
6713 (goto-char (point-min))
6714 (if (search-forward s nil t)
6715 (goto-char (match-beginning 0))
6716 (error "No match"))))))
6717
6718 (defun org-do-occur (regexp &optional cleanup)
6719 "Call the Emacs command `occur'.
6720 If CLEANUP is non-nil, remove the printout of the regular expression
6721 in the *Occur* buffer. This is useful if the regex is long and not useful
6722 to read."
6723 (occur regexp)
6724 (when cleanup
6725 (let ((cwin (selected-window)) win beg end)
6726 (when (setq win (get-buffer-window "*Occur*"))
6727 (select-window win))
6728 (goto-char (point-min))
6729 (when (re-search-forward "match[a-z]+" nil t)
6730 (setq beg (match-end 0))
6731 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6732 (setq end (1- (match-beginning 0)))))
6733 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6734 (goto-char (point-min))
6735 (select-window cwin))))
6736
6737 (defun org-camel-to-words (s)
6738 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6739 (let ((case-fold-search nil)
6740 words)
6741 (while (string-match "[a-z][A-Z]" s)
6742 (push (substring s 0 (1+ (match-beginning 0))) words)
6743 (setq s (substring s (1+ (match-beginning 0)))))
6744 (nreverse (cons s words))))
6745
6746 (defun org-follow-bbdb-link (name)
6747 "Follow a BBDB link to NAME."
6748 (require 'bbdb)
6749 (let ((inhibit-redisplay t))
6750 (catch 'exit
6751 ;; Exact match on name
6752 (bbdb-name (concat "\\`" name "\\'") nil)
6753 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6754 ;; Exact match on name
6755 (bbdb-company (concat "\\`" name "\\'") nil)
6756 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6757 ;; Partial match on name
6758 (bbdb-name name nil)
6759 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6760 ;; Partial match on company
6761 (bbdb-company name nil)
6762 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6763 ;; General match including network address and notes
6764 (bbdb name nil)
6765 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6766 (delete-window (get-buffer-window "*BBDB*"))
6767 (error "No matching BBDB record")))))
6768
6769 (defun org-follow-gnus-link (&optional group article)
6770 "Follow a Gnus link to GROUP and ARTICLE."
6771 (require 'gnus)
6772 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6773 (if group (gnus-fetch-group group))
6774 (if article
6775 (or (gnus-summary-goto-article article nil 'force)
6776 (if (fboundp 'gnus-summary-insert-cached-articles)
6777 (progn
6778 (gnus-summary-insert-cached-articles)
6779 (gnus-summary-goto-article article nil 'force))
6780 (message "Message could not be found.")))))
6781
6782 (defun org-follow-vm-link (&optional folder article readonly)
6783 "Follow a VM link to FOLDER and ARTICLE."
6784 (require 'vm)
6785 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6786 ;; ange-ftp or efs or tramp access
6787 (let ((user (or (match-string 1 folder) (user-login-name)))
6788 (host (match-string 2 folder))
6789 (file (match-string 3 folder)))
6790 (cond
6791 ((featurep 'tramp)
6792 ;; use tramp to access the file
6793 (if org-xemacs-p
6794 (setq folder (format "[%s@%s]%s" user host file))
6795 (setq folder (format "/%s@%s:%s" user host file))))
6796 (t
6797 ;; use ange-ftp or efs
6798 (require (if org-xemacs-p 'efs 'ange-ftp))
6799 (setq folder (format "/%s@%s:%s" user host file))))))
6800 (when folder
6801 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6802 (sit-for 0.1)
6803 (when article
6804 (vm-select-folder-buffer)
6805 (widen)
6806 (let ((case-fold-search t))
6807 (goto-char (point-min))
6808 (if (not (re-search-forward
6809 (concat "^" "message-id: *" (regexp-quote article))))
6810 (error "Could not find the specified message in this folder"))
6811 (vm-isearch-update)
6812 (vm-isearch-narrow)
6813 (vm-beginning-of-message)
6814 (vm-summarize)))))
6815
6816 (defun org-follow-wl-link (folder article)
6817 "Follow a Wanderlust link to FOLDER and ARTICLE."
6818 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6819 (if article (wl-summary-jump-to-msg-by-message-id article))
6820 (wl-summary-redisplay))
6821
6822 (defun org-follow-rmail-link (folder article)
6823 "Follow an RMAIL link to FOLDER and ARTICLE."
6824 (let (message-number)
6825 (save-excursion
6826 (save-window-excursion
6827 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6828 (setq message-number
6829 (save-restriction
6830 (widen)
6831 (goto-char (point-max))
6832 (if (re-search-backward
6833 (concat "^Message-ID:\\s-+" (regexp-quote
6834 (or article "")))
6835 nil t)
6836 (rmail-what-message))))))
6837 (if message-number
6838 (progn
6839 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6840 (rmail-show-message message-number)
6841 message-number)
6842 (error "Message not found"))))
6843
6844 (defun org-open-file (path &optional in-emacs line search)
6845 "Open the file at PATH.
6846 First, this expands any special file name abbreviations. Then the
6847 configuration variable `org-file-apps' is checked if it contains an
6848 entry for this file type, and if yes, the corresponding command is launched.
6849 If no application is found, Emacs simply visits the file.
6850 With optional argument IN-EMACS, Emacs will visit the file.
6851 Optional LINE specifies a line to go to, optional SEARCH a string to
6852 search for. If LINE or SEARCH is given, the file will always be
6853 openen in emacs.
6854 If the file does not exist, an error is thrown."
6855 (setq in-emacs (or in-emacs line search))
6856 (let* ((file (if (equal path "")
6857 (buffer-file-name)
6858 (convert-standard-filename (org-expand-file-name path))))
6859 (dfile (downcase file))
6860 ext cmd apps)
6861 (if (and (not (file-exists-p file))
6862 (not org-open-non-existing-files))
6863 (error "No such file: %s" file))
6864 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6865 (setq ext (match-string 1 dfile))
6866 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6867 (setq ext (match-string 1 dfile))))
6868 (setq apps (append org-file-apps (org-default-apps)))
6869 (if in-emacs
6870 (setq cmd 'emacs)
6871 (setq cmd (or (cdr (assoc ext apps))
6872 (cdr (assoc t apps)))))
6873 (cond
6874 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6875 (setq cmd (format cmd (concat "\"" file "\"")))
6876 (save-window-excursion
6877 (shell-command (concat cmd " & &"))))
6878 ((or (stringp cmd)
6879 (eq cmd 'emacs))
6880 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6881 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6882 (if line (goto-line line)
6883 (if search (org-link-search search))))
6884 ((consp cmd)
6885 (eval cmd))
6886 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6887
6888 (defun org-default-apps ()
6889 "Return the default applications for this operating system."
6890 (cond
6891 ((eq system-type 'darwin)
6892 org-file-apps-defaults-macosx)
6893 ((eq system-type 'windows-nt)
6894 org-file-apps-defaults-windowsnt)
6895 (t org-file-apps-defaults-gnu)))
6896
6897 (defun org-expand-file-name (path)
6898 "Replace special path abbreviations and expand the file name."
6899 (expand-file-name path))
6900
6901
6902 (defvar org-insert-link-history nil
6903 "Minibuffer history for links inserted with `org-insert-link'.")
6904
6905 (defvar org-stored-links nil
6906 "Contains the links stored with `org-store-link'.")
6907
6908 ;;;###autoload
6909 (defun org-store-link (arg)
6910 "\\<org-mode-map>Store an org-link to the current location.
6911 This link can later be inserted into an org-buffer with
6912 \\[org-insert-link].
6913 For some link types, a prefix arg is interpreted:
6914 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6915 For file links, arg negates `org-context-in-file-links'."
6916 (interactive "P")
6917 (let (link cpltxt)
6918 (cond
6919
6920 ((eq major-mode 'bbdb-mode)
6921 (setq cpltxt (concat
6922 "bbdb:"
6923 (or (bbdb-record-name (bbdb-current-record))
6924 (bbdb-record-company (bbdb-current-record))))
6925 link (org-make-link cpltxt)))
6926
6927 ((eq major-mode 'calendar-mode)
6928 (let ((cd (calendar-cursor-to-date)))
6929 (setq link
6930 (format-time-string
6931 (car org-time-stamp-formats)
6932 (apply 'encode-time
6933 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6934 nil nil nil))))))
6935
6936 ((or (eq major-mode 'vm-summary-mode)
6937 (eq major-mode 'vm-presentation-mode))
6938 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6939 (vm-follow-summary-cursor)
6940 (save-excursion
6941 (vm-select-folder-buffer)
6942 (let* ((message (car vm-message-pointer))
6943 (folder (buffer-file-name))
6944 (subject (vm-su-subject message))
6945 (author (vm-su-full-name message))
6946 (message-id (vm-su-message-id message)))
6947 (setq folder (abbreviate-file-name folder))
6948 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6949 folder)
6950 (setq folder (replace-match "" t t folder)))
6951 (setq cpltxt (concat author " on: " subject))
6952 (setq link (concat cpltxt "\n "
6953 (org-make-link
6954 "vm:" folder "#" message-id))))))
6955
6956 ((eq major-mode 'wl-summary-mode)
6957 (let* ((msgnum (wl-summary-message-number))
6958 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6959 msgnum 'message-id))
6960 (wl-message-entity (elmo-msgdb-overview-get-entity
6961 msgnum (wl-summary-buffer-msgdb)))
6962 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6963 (subject "???")) ; FIXME: How to get subject of email?
6964 (setq cpltxt (concat author " on: " subject))
6965 (setq link (concat cpltxt "\n "
6966 (org-make-link
6967 "wl:" wl-summary-buffer-folder-name
6968 "#" message-id)))))
6969
6970 ((eq major-mode 'rmail-mode)
6971 (save-excursion
6972 (save-restriction
6973 (rmail-narrow-to-non-pruned-header)
6974 (let ((folder (buffer-file-name))
6975 (message-id (mail-fetch-field "message-id"))
6976 (author (mail-fetch-field "from"))
6977 (subject (mail-fetch-field "subject")))
6978 (setq cpltxt (concat author " on: " subject))
6979 (setq link (concat cpltxt "\n "
6980 (org-make-link
6981 "rmail:" folder "#" message-id)))))))
6982
6983 ((eq major-mode 'gnus-group-mode)
6984 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
6985 (gnus-group-group-name)) ; version
6986 ((fboundp 'gnus-group-name)
6987 (gnus-group-name))
6988 (t "???"))))
6989 (setq cpltxt (concat
6990 (if (org-xor arg org-usenet-links-prefer-google)
6991 "http://groups.google.com/groups?group="
6992 "gnus:")
6993 group)
6994 link (org-make-link cpltxt))))
6995
6996 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
6997 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
6998 (gnus-summary-beginning-of-article)
6999 (let* ((group (car gnus-article-current))
7000 (article (cdr gnus-article-current))
7001 (header (gnus-summary-article-header article))
7002 (author (mail-header-from header))
7003 (message-id (mail-header-id header))
7004 (date (mail-header-date header))
7005 (subject (gnus-summary-subject-string)))
7006 (setq cpltxt (concat author " on: " subject))
7007 (if (org-xor arg org-usenet-links-prefer-google)
7008 (setq link
7009 (concat
7010 cpltxt "\n "
7011 (format "http://groups.google.com/groups?as_umsgid=%s"
7012 (org-fixup-message-id-for-http message-id))))
7013 (setq link (concat cpltxt "\n"
7014 (org-make-link
7015 "gnus:" group
7016 "#" (number-to-string article)))))))
7017
7018 ((eq major-mode 'w3-mode)
7019 (setq cpltxt (url-view-url t)
7020 link (org-make-link cpltxt)))
7021 ((eq major-mode 'w3m-mode)
7022 (setq cpltxt w3m-current-url
7023 link (org-make-link cpltxt)))
7024
7025 ((eq major-mode 'org-mode)
7026 ;; Just link to current headline
7027 (setq cpltxt (concat "file:"
7028 (abbreviate-file-name (buffer-file-name))))
7029 ;; Add a context search string
7030 (when (org-xor org-context-in-file-links arg)
7031 (if (save-excursion
7032 (skip-chars-backward "a-zA-Z<")
7033 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7034 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7035 (setq cpltxt
7036 (concat cpltxt "::"
7037 (org-make-org-heading-camel
7038 (cond
7039 ((org-on-heading-p) nil)
7040 ((org-region-active-p)
7041 (buffer-substring (region-beginning) (region-end)))
7042 (t (buffer-substring (point-at-bol) (point-at-eol))))
7043 )))))
7044 (setq link (org-make-link cpltxt)))
7045
7046 ((buffer-file-name)
7047 ;; Just link to this file here.
7048 (setq cpltxt (concat "file:"
7049 (abbreviate-file-name (buffer-file-name))))
7050 ;; Add a context string
7051 (when (org-xor org-context-in-file-links arg)
7052 (setq cpltxt
7053 (concat cpltxt "::"
7054 (org-make-org-heading-camel
7055 (if (org-region-active-p)
7056 (buffer-substring (region-beginning) (region-end))
7057 (buffer-substring (point-at-bol) (point-at-eol)))))))
7058 (setq link (org-make-link cpltxt)))
7059
7060 ((interactive-p)
7061 (error "Cannot link to a buffer which is not visiting a file"))
7062
7063 (t (setq link nil)))
7064
7065 (if (and (interactive-p) link)
7066 (progn
7067 (setq org-stored-links
7068 (cons (cons (or cpltxt link) link) org-stored-links))
7069 (message "Stored: %s" (or cpltxt link)))
7070 link)))
7071
7072 (defun org-make-org-heading-camel (&optional string)
7073 "Make a CamelCase string for S or the current headline."
7074 (interactive)
7075 (let ((s (or string (org-get-heading))))
7076 (unless string
7077 ;; We are using a headline, clean up garbage in there.
7078 (if (string-match org-todo-regexp s)
7079 (setq s (replace-match "" t t s)))
7080 (setq s (org-trim s))
7081 (if (string-match (concat "^\\(" org-quote-string "\\|"
7082 org-comment-string "\\)") s)
7083 (setq s (replace-match "" t t s)))
7084 (while (string-match org-ts-regexp s)
7085 (setq s (replace-match "" t t s))))
7086 (while (string-match "[^a-zA-Z_ \t]+" s)
7087 (setq s (replace-match " " t t s)))
7088 (or string (setq s (concat "*" s))) ; Add * for headlines
7089 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7090
7091 (defun org-make-link (&rest strings)
7092 "Concatenate STRINGS, format resulting string with `org-link-format'."
7093 (format org-link-format (apply 'concat strings)))
7094
7095 (defun org-xor (a b)
7096 "Exclusive or."
7097 (if a (not b) b))
7098
7099 (defun org-get-header (header)
7100 "Find a header field in the current buffer."
7101 (save-excursion
7102 (goto-char (point-min))
7103 (let ((case-fold-search t) s)
7104 (cond
7105 ((eq header 'from)
7106 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7107 (setq s (match-string 1)))
7108 (while (string-match "\"" s)
7109 (setq s (replace-match "" t t s)))
7110 (if (string-match "[<(].*" s)
7111 (setq s (replace-match "" t t s))))
7112 ((eq header 'message-id)
7113 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7114 (setq s (match-string 1))))
7115 ((eq header 'subject)
7116 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7117 (setq s (match-string 1)))))
7118 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7119 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7120 s)))
7121
7122
7123 (defun org-fixup-message-id-for-http (s)
7124 "Replace special characters in a message id, so it can be used in an http query."
7125 (while (string-match "<" s)
7126 (setq s (replace-match "%3C" t t s)))
7127 (while (string-match ">" s)
7128 (setq s (replace-match "%3E" t t s)))
7129 (while (string-match "@" s)
7130 (setq s (replace-match "%40" t t s)))
7131 s)
7132
7133 (defun org-insert-link (&optional complete-file)
7134 "Insert a link. At the prompt, enter the link.
7135
7136 Completion can be used to select a link previously stored with
7137 `org-store-link'. When the empty string is entered (i.e. if you just
7138 press RET at the prompt), the link defaults to the most recently
7139 stored link. As SPC triggers completion in the minibuffer, you need to
7140 use M-SPC or C-q SPC to force the insertion of a space character.
7141
7142 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7143 selected using completion. The path to the file will be relative to
7144 the current directory if the file is in the current directory or a
7145 subdirectory. Otherwise, the link will be the absolute path as
7146 completed in the minibuffer (i.e. normally ~/path/to/file).
7147
7148 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7149 is in the current directory or below."
7150 (interactive "P")
7151 (let ((link (if complete-file
7152 (read-file-name "File: ")
7153 (completing-read
7154 "Link: " org-stored-links nil nil nil
7155 org-insert-link-history
7156 (or (car (car org-stored-links))))))
7157 linktxt matched)
7158 (if (or (not link) (equal link ""))
7159 (error "No links available"))
7160 (if complete-file
7161 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7162 (cond
7163 ((equal complete-file '(16))
7164 (insert
7165 (org-make-link
7166 "file:" (abbreviate-file-name (expand-file-name link)))))
7167 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7168 (expand-file-name link))
7169 (insert
7170 (org-make-link
7171 "file:" (match-string 1 (expand-file-name link)))))
7172 (t (insert (org-make-link "file:" link)))))
7173 (setq linktxt (cdr (assoc link org-stored-links)))
7174 (if (not org-keep-stored-link-after-insertion)
7175 (setq org-stored-links (delq (assoc link org-stored-links)
7176 org-stored-links)))
7177 (if (not linktxt) (setq link (org-make-link link)))
7178 (setq link (or linktxt link))
7179 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7180 (let* ((path (match-string 1 link))
7181 (case-fold-search nil)
7182 (search (match-string 2 link)))
7183 (when (save-match-data
7184 (equal (file-truename (buffer-file-name))
7185 (file-truename path)))
7186 (if (save-match-data
7187 (string-match (concat "^" org-camel-regexp "$") search))
7188 (setq link (replace-match search t t link)
7189 matched t)
7190 (setq link (replace-match (concat "<file:::" search ">")
7191 t t link))))))
7192 (let ((lines (org-split-string link "\n")))
7193 (insert (car lines))
7194 (setq matched (or matched (string-match org-link-regexp (car lines))))
7195 (setq lines (cdr lines))
7196 (while lines
7197 (insert "\n")
7198 (if (save-excursion
7199 (beginning-of-line 0)
7200 (looking-at "[ \t]+\\S-"))
7201 (indent-relative))
7202 (setq matched (or matched
7203 (string-match org-link-regexp (car lines))))
7204 (insert (car lines))
7205 (setq lines (cdr lines))))
7206 (unless matched
7207 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7208
7209 ;;; Hooks for remember.el
7210 ;;;###autoload
7211 (defun org-remember-annotation ()
7212 "Return a link to the current location as an annotation for remember.el.
7213 If you are using Org-mode files as target for data storage with
7214 remember.el, then the annotations should include a link compatible with the
7215 conventions in Org-mode. This function returns such a link."
7216 (org-store-link nil))
7217
7218 (defconst org-remember-help
7219 "Select a destination location for the note.
7220 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7221 RET at beg-of-buf -> Append to file as level 2 headline
7222 RET on headline -> Store as sublevel entry to current headline
7223 <left>/<right> -> before/after current headline, same headings level")
7224
7225 ;;;###autoload
7226 (defun org-remember-handler ()
7227 "Store stuff from remember.el into an org file.
7228 First prompts for an org file. If the user just presses return, the value
7229 of `org-default-notes-file' is used.
7230 Then the command offers the headings tree of the selected file in order to
7231 file the text at a specific location.
7232 You can either immediately press RET to get the note appended to the
7233 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7234 find a better place. Then press RET or <left> or <right> in insert the note.
7235
7236 Key Cursor position Note gets inserted
7237 -----------------------------------------------------------------------------
7238 RET buffer-start as level 2 heading at end of file
7239 RET on headline as sublevel of the heading at cursor
7240 RET no heading at cursor position, level taken from context.
7241 Or use prefix arg to specify level manually.
7242 <left> on headline as same level, before current heading
7243 <right> on headline as same level, after current heading
7244
7245 So the fastest way to store the note is to press RET RET to append it to
7246 the default file. This way your current train of thought is not
7247 interrupted, in accordance with the principles of remember.el. But with
7248 little extra effort, you can push it directly to the correct location.
7249
7250 Before being stored away, the function ensures that the text has a
7251 headline, i.e. a first line that starts with a \"*\". If not, a headline
7252 is constructed from the current date and some additional data.
7253
7254 If the variable `org-adapt-indentation' is non-nil, the entire text is
7255 also indented so that it starts in the same column as the headline
7256 \(i.e. after the stars).
7257
7258 See also the variable `org-reverse-note-order'."
7259 (catch 'quit
7260 (let* ((txt (buffer-substring (point-min) (point-max)))
7261 (fastp current-prefix-arg)
7262 (file (if fastp org-default-notes-file (org-get-org-file)))
7263 (visiting (find-buffer-visiting file))
7264 (org-startup-with-deadline-check nil)
7265 (org-startup-folded nil)
7266 spos level indent reversed)
7267 ;; Modify text so that it becomes a nice subtree which can be inserted
7268 ;; into an org tree.
7269 (let* ((lines (split-string txt "\n"))
7270 (first (car lines))
7271 (lines (cdr lines)))
7272 (if (string-match "^\\*+" first)
7273 ;; Is already a headline
7274 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7275 -1) ?\ ))
7276 ;; We need to add a headline: Use time and first buffer line
7277 (setq lines (cons first lines)
7278 first (concat "* " (current-time-string)
7279 " (" (remember-buffer-desc) ")")
7280 indent " "))
7281 (if org-adapt-indentation
7282 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7283 (setq txt (concat first "\n"
7284 (mapconcat 'identity lines "\n"))))
7285 ;; Find the file
7286 (if (not visiting)
7287 (find-file-noselect file))
7288 (with-current-buffer (get-file-buffer file)
7289 (setq reversed (org-notes-order-reversed-p))
7290 (save-excursion
7291 (save-restriction
7292 (widen)
7293 ;; Ask the User for a location
7294 (setq spos (if fastp 1 (org-get-location
7295 (current-buffer)
7296 org-remember-help)))
7297 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7298 ; not handle this note
7299 (goto-char spos)
7300 (cond ((bobp)
7301 ;; Put it at the start or end, as level 2
7302 (save-restriction
7303 (widen)
7304 (goto-char (if reversed (point-min) (point-max)))
7305 (if (not (bolp)) (newline))
7306 (org-paste-subtree (or current-prefix-arg 2) txt)))
7307 ((and (org-on-heading-p nil) (not current-prefix-arg))
7308 ;; Put it below this entry, at the beg/end of the subtree
7309 (org-back-to-heading)
7310 (setq level (outline-level))
7311 (if reversed
7312 (outline-end-of-heading)
7313 (outline-end-of-subtree))
7314 (if (not (bolp)) (newline))
7315 (beginning-of-line 1)
7316 (org-paste-subtree (1+ level) txt))
7317 (t
7318 ;; Put it right there, with automatic level determined by
7319 ;; org-paste-subtree or from prefix arg
7320 (org-paste-subtree current-prefix-arg txt)))
7321 (when remember-save-after-remembering
7322 (save-buffer)
7323 (if (not visiting) (kill-buffer (current-buffer)))))))))
7324 t) ;; return t to indicate that we took care of this note.
7325
7326 (defun org-get-org-file ()
7327 "Read a filename, with default directory `org-directory'."
7328 (let ((default (or org-default-notes-file remember-data-file)))
7329 (read-file-name (format "File name [%s]: " default)
7330 (file-name-as-directory org-directory)
7331 default)))
7332
7333 (defun org-notes-order-reversed-p ()
7334 "Check if the current file should receive notes in reversed order."
7335 (cond
7336 ((not org-reverse-note-order) nil)
7337 ((eq t org-reverse-note-order) t)
7338 ((not (listp org-reverse-note-order)) nil)
7339 (t (catch 'exit
7340 (let ((all org-reverse-note-order)
7341 entry)
7342 (while (setq entry (pop all))
7343 (if (string-match (car entry) (buffer-file-name))
7344 (throw 'exit (cdr entry))))
7345 nil)))))
7346
7347 ;;; Tables
7348
7349 ;; Watch out: Here we are talking about two different kind of tables.
7350 ;; Most of the code is for the tables created with the Org-mode table editor.
7351 ;; Sometimes, we talk about tables created and edited with the table.el
7352 ;; Emacs package. We call the former org-type tables, and the latter
7353 ;; table.el-type tables.
7354
7355
7356 (defun org-before-change-function (beg end)
7357 "Every change indicates that a table might need an update."
7358 (setq org-table-may-need-update t))
7359
7360 (defconst org-table-line-regexp "^[ \t]*|"
7361 "Detects an org-type table line.")
7362 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7363 "Detects an org-type table line.")
7364 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7365 "Detects a table line marked for automatic recalculation.")
7366 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7367 "Detects a table line marked for automatic recalculation.")
7368 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7369 "Detects a table line marked for automatic recalculation.")
7370 (defconst org-table-hline-regexp "^[ \t]*|-"
7371 "Detects an org-type table hline.")
7372 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7373 "Detects a table-type table hline.")
7374 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7375 "Detects an org-type or table-type table.")
7376 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7377 "Searching from within a table (any type) this finds the first line
7378 outside the table.")
7379 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7380 "Searching from within a table (any type) this finds the first line
7381 outside the table.")
7382
7383 (defun org-table-create-with-table.el ()
7384 "Use the table.el package to insert a new table.
7385 If there is already a table at point, convert between Org-mode tables
7386 and table.el tables."
7387 (interactive)
7388 (require 'table)
7389 (cond
7390 ((org-at-table.el-p)
7391 (if (y-or-n-p "Convert table to Org-mode table? ")
7392 (org-table-convert)))
7393 ((org-at-table-p)
7394 (if (y-or-n-p "Convert table to table.el table? ")
7395 (org-table-convert)))
7396 (t (call-interactively 'table-insert))))
7397
7398 (defun org-table-create (&optional size)
7399 "Query for a size and insert a table skeleton.
7400 SIZE is a string Columns x Rows like for example \"3x2\"."
7401 (interactive "P")
7402 (unless size
7403 (setq size (read-string
7404 (concat "Table size Columns x Rows [e.g. "
7405 org-table-default-size "]: ")
7406 "" nil org-table-default-size)))
7407
7408 (let* ((pos (point))
7409 (indent (make-string (current-column) ?\ ))
7410 (split (org-split-string size " *x *"))
7411 (rows (string-to-number (nth 1 split)))
7412 (columns (string-to-number (car split)))
7413 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7414 "\n")))
7415 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7416 (point-at-bol) (point)))
7417 (beginning-of-line 1)
7418 (newline))
7419 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7420 (dotimes (i rows) (insert line))
7421 (goto-char pos)
7422 (if (> rows 1)
7423 ;; Insert a hline after the first row.
7424 (progn
7425 (end-of-line 1)
7426 (insert "\n|-")
7427 (goto-char pos)))
7428 (org-table-align)))
7429
7430 (defun org-table-convert-region (beg0 end0 nspace)
7431 "Convert region to a table.
7432 The region goes from BEG0 to END0, but these borders will be moved
7433 slightly, to make sure a beginning of line in the first line is included.
7434 When NSPACE is non-nil, it indicates the minimum number of spaces that
7435 separate columns (default: just one space)"
7436 (let* ((beg (min beg0 end0))
7437 (end (max beg0 end0))
7438 (tabsep t)
7439 re)
7440 (goto-char beg)
7441 (beginning-of-line 1)
7442 (setq beg (move-marker (make-marker) (point)))
7443 (goto-char end)
7444 (if (bolp) (backward-char 1) (end-of-line 1))
7445 (setq end (move-marker (make-marker) (point)))
7446 ;; Lets see if this is tab-separated material. If every nonempty line
7447 ;; contains a tab, we will assume that it is tab-separated material
7448 (if nspace
7449 (setq tabsep nil)
7450 (goto-char beg)
7451 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7452 (if nspace (setq tabsep nil))
7453 (if tabsep
7454 (setq re "^\\|\t")
7455 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7456 (max 1 (prefix-numeric-value nspace)))))
7457 (goto-char beg)
7458 (while (re-search-forward re end t)
7459 (replace-match "|" t t))
7460 (goto-char beg)
7461 (insert " ")
7462 (org-table-align)))
7463
7464 (defun org-table-import (file arg)
7465 "Import FILE as a table.
7466 The file is assumed to be tab-separated. Such files can be produced by most
7467 spreadsheet and database applications. If no tabs (at least one per line)
7468 are found, lines will be split on whitespace into fields."
7469 (interactive "f\nP")
7470 (or (bolp) (newline))
7471 (let ((beg (point))
7472 (pm (point-max)))
7473 (insert-file-contents file)
7474 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7475
7476 (defun org-table-export ()
7477 "Export table as a tab-separated file.
7478 Such a file can be imported into a spreadsheet program like Excel."
7479 (interactive)
7480 (let* ((beg (org-table-begin))
7481 (end (org-table-end))
7482 (table (buffer-substring beg end))
7483 (file (read-file-name "Export table to: "))
7484 buf)
7485 (unless (or (not (file-exists-p file))
7486 (y-or-n-p (format "Overwrite file %s? " file)))
7487 (error "Abort"))
7488 (with-current-buffer (find-file-noselect file)
7489 (setq buf (current-buffer))
7490 (erase-buffer)
7491 (fundamental-mode)
7492 (insert table)
7493 (goto-char (point-min))
7494 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7495 (replace-match "" t t)
7496 (end-of-line 1))
7497 (goto-char (point-min))
7498 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7499 (replace-match "" t t)
7500 (goto-char (min (1+ (point)) (point-max))))
7501 (goto-char (point-min))
7502 (while (re-search-forward "^-[-+]*$" nil t)
7503 (replace-match "")
7504 (if (looking-at "\n")
7505 (delete-char 1)))
7506 (goto-char (point-min))
7507 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7508 (replace-match "\t" t t))
7509 (save-buffer))
7510 (kill-buffer buf)))
7511
7512 (defvar org-table-aligned-begin-marker (make-marker)
7513 "Marker at the beginning of the table last aligned.
7514 Used to check if cursor still is in that table, to minimize realignment.")
7515 (defvar org-table-aligned-end-marker (make-marker)
7516 "Marker at the end of the table last aligned.
7517 Used to check if cursor still is in that table, to minimize realignment.")
7518 (defvar org-table-last-alignment nil
7519 "List of flags for flushright alignment, from the last re-alignment.
7520 This is being used to correctly align a single field after TAB or RET.")
7521 ;; FIXME: The following is currently not used.
7522 (defvar org-table-last-column-widths nil
7523 "List of max width of fields in each column.
7524 This is being used to correctly align a single field after TAB or RET.")
7525
7526 (defvar org-last-recalc-line nil)
7527
7528 (defun org-table-align ()
7529 "Align the table at point by aligning all vertical bars."
7530 (interactive)
7531 ;; (message "align") (sit-for 2)
7532 (let* (
7533 ;; Limits of table
7534 (beg (org-table-begin))
7535 (end (org-table-end))
7536 ;; Current cursor position
7537 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7538 (colpos (org-table-current-column))
7539 (winstart (window-start))
7540 text lines (new "") lengths l typenums ty fields maxfields i
7541 column
7542 (indent "") cnt frac
7543 rfmt hfmt
7544 (spaces (if (org-in-invisibility-spec-p '(org-table))
7545 org-table-spaces-around-invisible-separators
7546 org-table-spaces-around-separators))
7547 (sp1 (car spaces))
7548 (sp2 (cdr spaces))
7549 (rfmt1 (concat
7550 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7551 (hfmt1 (concat
7552 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7553 emptystrings)
7554 (untabify beg end)
7555 ;; (message "Aligning table...")
7556 ;; Get the rows
7557 (setq lines (org-split-string
7558 (buffer-substring-no-properties beg end) "\n"))
7559 ;; Store the indentation of the first line
7560 (if (string-match "^ *" (car lines))
7561 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7562 ;; Mark the hlines
7563 (setq lines (mapcar (lambda (l)
7564 (if (string-match "^ *|-" l)
7565 nil
7566 (if (string-match "[ \t]+$" l)
7567 (substring l 0 (match-beginning 0))
7568 l)))
7569 lines))
7570 ;; Get the data fields
7571 (setq fields (mapcar
7572 (lambda (l)
7573 (org-split-string l " *| *"))
7574 (delq nil (copy-sequence lines))))
7575 ;; How many fields in the longest line?
7576 (condition-case nil
7577 (setq maxfields (apply 'max (mapcar 'length fields)))
7578 (error
7579 (kill-region beg end)
7580 (org-table-create org-table-default-size)
7581 (error "Empty table - created default table")))
7582 ;; A list of empty string to fill any short rows on output
7583 (setq emptystrings (make-list maxfields ""))
7584 ;; Get the maximum length of a field and the most common datatype
7585 ;; for each column
7586 (setq i -1)
7587 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7588 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7589 ;; maximum length
7590 (push (apply 'max 1 (mapcar 'length column)) lengths)
7591 ;; compute the fraction stepwise, ignoring empty fields
7592 (setq cnt 0 frac 0.0)
7593 (mapcar
7594 (lambda (x)
7595 (if (equal x "")
7596 nil
7597 (setq frac ( / (+ (* frac cnt)
7598 (if (string-match org-table-number-regexp x) 1 0))
7599 (setq cnt (1+ cnt))))))
7600 column)
7601 (push (>= frac org-table-number-fraction) typenums))
7602 (setq lengths (nreverse lengths)
7603 typenums (nreverse typenums))
7604 (setq org-table-last-alignment typenums
7605 org-table-last-column-widths lengths)
7606 ;; Compute the formats needed for output of the table
7607 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7608 (while (setq l (pop lengths))
7609 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7610 (setq rfmt (concat rfmt (format rfmt1 ty l))
7611 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7612 (setq rfmt (concat rfmt "\n")
7613 hfmt (concat (substring hfmt 0 -1) "|\n"))
7614 ;; Produce the new table
7615 ;;(while lines
7616 ;; (setq l (pop lines))
7617 ;; (if l
7618 ;; (setq new (concat new (apply 'format rfmt
7619 ;; (append (pop fields) emptystrings))))
7620 ;; (setq new (concat new hfmt))))
7621 (setq new (mapconcat
7622 (lambda (l)
7623 (if l (apply 'format rfmt
7624 (append (pop fields) emptystrings))
7625 hfmt))
7626 lines ""))
7627 ;; Replace the old one
7628 (delete-region beg end)
7629 (move-marker end nil)
7630 (move-marker org-table-aligned-begin-marker (point))
7631 (insert new)
7632 (move-marker org-table-aligned-end-marker (point))
7633 ;; Try to move to the old location (approximately)
7634 (goto-line linepos)
7635 (set-window-start (selected-window) winstart 'noforce)
7636 (org-table-goto-column colpos)
7637 (setq org-table-may-need-update nil)
7638 (if (org-in-invisibility-spec-p '(org-table))
7639 (org-table-add-invisible-to-vertical-lines))
7640 ))
7641
7642 (defun org-table-begin (&optional table-type)
7643 "Find the beginning of the table and return its position.
7644 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7645 (save-excursion
7646 (if (not (re-search-backward
7647 (if table-type org-table-any-border-regexp
7648 org-table-border-regexp)
7649 nil t))
7650 (error "Can't find beginning of table")
7651 (goto-char (match-beginning 0))
7652 (beginning-of-line 2)
7653 (point))))
7654
7655 (defun org-table-end (&optional table-type)
7656 "Find the end of the table and return its position.
7657 With argument TABLE-TYPE, go to the end of a table.el-type table."
7658 (save-excursion
7659 (if (not (re-search-forward
7660 (if table-type org-table-any-border-regexp
7661 org-table-border-regexp)
7662 nil t))
7663 (goto-char (point-max))
7664 (goto-char (match-beginning 0)))
7665 (point-marker)))
7666
7667 (defun org-table-justify-field-maybe (&optional new)
7668 "Justify the current field, text to left, number to right.
7669 Optional argument NEW may specify text to replace the current field content."
7670 (cond
7671 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7672 ((org-at-table-hline-p)
7673 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7674 ;; (setq org-table-may-need-update t)
7675 )
7676 ((and (not new)
7677 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7678 (current-buffer)))
7679 (< (point) org-table-aligned-begin-marker)
7680 (>= (point) org-table-aligned-end-marker)))
7681 ;; This is not the same table, force a full re-align
7682 (setq org-table-may-need-update t))
7683 (t ;; realign the current field, based on previous full realign
7684 (let* ((pos (point)) s
7685 (col (org-table-current-column))
7686 (num (nth (1- col) org-table-last-alignment))
7687 l f n o e)
7688 (when (> col 0)
7689 (skip-chars-backward "^|\n")
7690 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7691 (progn
7692 (setq s (match-string 1)
7693 o (match-string 0)
7694 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7695 e (not (= (match-beginning 2) (match-end 2))))
7696 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7697 l (if e "|" (setq org-table-may-need-update t) ""))
7698 n (format f s t t))
7699 (if new
7700 (if (<= (length new) l)
7701 (setq n (format f new t t)) ;; FIXME: why t t?????
7702 (setq n (concat new "|") org-table-may-need-update t)))
7703 (or (equal n o)
7704 (let (org-table-may-need-update)
7705 (replace-match n))))
7706 (setq org-table-may-need-update t))
7707 (goto-char pos))))))
7708
7709 (defun org-table-next-field ()
7710 "Go to the next field in the current table, creating new lines as needed.
7711 Before doing so, re-align the table if necessary."
7712 (interactive)
7713 (org-table-maybe-eval-formula)
7714 (org-table-maybe-recalculate-line)
7715 (if (and org-table-automatic-realign
7716 org-table-may-need-update)
7717 (org-table-align))
7718 (let ((end (org-table-end)))
7719 (if (org-at-table-hline-p)
7720 (end-of-line 1))
7721 (condition-case nil
7722 (progn
7723 (re-search-forward "|" end)
7724 (if (looking-at "[ \t]*$")
7725 (re-search-forward "|" end))
7726 (if (and (looking-at "-")
7727 org-table-tab-jumps-over-hlines
7728 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7729 (goto-char (match-beginning 1)))
7730 (if (looking-at "-")
7731 (progn
7732 (beginning-of-line 0)
7733 (org-table-insert-row 'below))
7734 (if (looking-at " ") (forward-char 1))))
7735 (error
7736 (org-table-insert-row 'below)))))
7737
7738 (defun org-table-previous-field ()
7739 "Go to the previous field in the table.
7740 Before doing so, re-align the table if necessary."
7741 (interactive)
7742 (org-table-justify-field-maybe)
7743 (org-table-maybe-recalculate-line)
7744 (if (and org-table-automatic-realign
7745 org-table-may-need-update)
7746 (org-table-align))
7747 (if (org-at-table-hline-p)
7748 (end-of-line 1))
7749 (re-search-backward "|" (org-table-begin))
7750 (re-search-backward "|" (org-table-begin))
7751 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7752 (re-search-backward "|" (org-table-begin)))
7753 (if (looking-at "| ?")
7754 (goto-char (match-end 0))))
7755
7756 (defun org-table-next-row ()
7757 "Go to the next row (same column) in the current table.
7758 Before doing so, re-align the table if necessary."
7759 (interactive)
7760 (org-table-maybe-eval-formula)
7761 (org-table-maybe-recalculate-line)
7762 (if (or (looking-at "[ \t]*$")
7763 (save-excursion (skip-chars-backward " \t") (bolp)))
7764 (newline)
7765 (if (and org-table-automatic-realign
7766 org-table-may-need-update)
7767 (org-table-align))
7768 (let ((col (org-table-current-column)))
7769 (beginning-of-line 2)
7770 (if (or (not (org-at-table-p))
7771 (org-at-table-hline-p))
7772 (progn
7773 (beginning-of-line 0)
7774 (org-table-insert-row 'below)))
7775 (org-table-goto-column col)
7776 (skip-chars-backward "^|\n\r")
7777 (if (looking-at " ") (forward-char 1)))))
7778
7779 (defun org-table-copy-down (n)
7780 "Copy a field down in the current column.
7781 If the field at the cursor is empty, copy into it the content of the nearest
7782 non-empty field above. With argument N, use the Nth non-empty field.
7783 If the current field is not empty, it is copied down to the next row, and
7784 the cursor is moved with it. Therefore, repeating this command causes the
7785 column to be filled row-by-row.
7786 If the variable `org-table-copy-increment' is non-nil and the field is an
7787 integer, it will be incremented while copying."
7788 (interactive "p")
7789 (let* ((colpos (org-table-current-column))
7790 (field (org-table-get-field))
7791 (non-empty (string-match "[^ \t]" field))
7792 (beg (org-table-begin))
7793 txt)
7794 (org-table-check-inside-data-field)
7795 (if non-empty
7796 (progn
7797 (setq txt (org-trim field))
7798 (org-table-next-row)
7799 (org-table-blank-field))
7800 (save-excursion
7801 (setq txt
7802 (catch 'exit
7803 (while (progn (beginning-of-line 1)
7804 (re-search-backward org-table-dataline-regexp
7805 beg t))
7806 (org-table-goto-column colpos t)
7807 (if (and (looking-at
7808 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7809 (= (setq n (1- n)) 0))
7810 (throw 'exit (match-string 1))))))))
7811 (if txt
7812 (progn
7813 (if (and org-table-copy-increment
7814 (string-match "^[0-9]+$" txt))
7815 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7816 (insert txt)
7817 (org-table-maybe-recalculate-line)
7818 (org-table-align))
7819 (error "No non-empty field found"))))
7820
7821 (defun org-table-check-inside-data-field ()
7822 "Is point inside a table data field?
7823 I.e. not on a hline or before the first or after the last column?
7824 This actually throws an error, so it aborts the current command."
7825 (if (or (not (org-at-table-p))
7826 (= (org-table-current-column) 0)
7827 (org-at-table-hline-p)
7828 (looking-at "[ \t]*$"))
7829 (error "Not in table data field")))
7830
7831 (defvar org-table-clip nil
7832 "Clipboard for table regions.")
7833
7834 (defun org-table-blank-field ()
7835 "Blank the current table field or active region."
7836 (interactive)
7837 (org-table-check-inside-data-field)
7838 (if (and (interactive-p) (org-region-active-p))
7839 (let (org-table-clip)
7840 (org-table-cut-region (region-beginning) (region-end)))
7841 (skip-chars-backward "^|")
7842 (backward-char 1)
7843 (if (looking-at "|[^|\n]+")
7844 (let* ((pos (match-beginning 0))
7845 (match (match-string 0))
7846 (len (length match)))
7847 (replace-match (concat "|" (make-string (1- len) ?\ )))
7848 (goto-char (+ 2 pos))
7849 (substring match 1)))))
7850
7851 (defun org-table-get-field (&optional n replace)
7852 "Return the value of the field in column N of current row.
7853 N defaults to current field.
7854 If REPLACE is a string, replace field with this value. The return value
7855 is always the old value."
7856 (and n (org-table-goto-column n))
7857 (skip-chars-backward "^|\n")
7858 (backward-char 1)
7859 (if (looking-at "|[^|\r\n]*")
7860 (let* ((pos (match-beginning 0))
7861 (val (buffer-substring (1+ pos) (match-end 0))))
7862 (if replace
7863 (replace-match (concat "|" replace)))
7864 (goto-char (min (point-at-eol) (+ 2 pos)))
7865 val)
7866 (forward-char 1) ""))
7867
7868 (defun org-table-current-column ()
7869 "Find out which column we are in.
7870 When called interactively, column is also displayed in echo area."
7871 (interactive)
7872 (if (interactive-p) (org-table-check-inside-data-field))
7873 (save-excursion
7874 (let ((cnt 0) (pos (point)))
7875 (beginning-of-line 1)
7876 (while (search-forward "|" pos t)
7877 (setq cnt (1+ cnt)))
7878 (if (interactive-p) (message "This is table column %d" cnt))
7879 cnt)))
7880
7881 (defun org-table-goto-column (n &optional on-delim force)
7882 "Move the cursor to the Nth column in the current table line.
7883 With optional argument ON-DELIM, stop with point before the left delimiter
7884 of the field.
7885 If there are less than N fields, just go to after the last delimiter.
7886 However, when FORCE is non-nil, create new columns if necessary."
7887 (interactive "p")
7888 (let ((pos (point-at-eol)))
7889 (beginning-of-line 1)
7890 (when (> n 0)
7891 (while (and (> (setq n (1- n)) -1)
7892 (or (search-forward "|" pos t)
7893 (and force
7894 (progn (end-of-line 1)
7895 (skip-chars-backward "^|")
7896 (insert " | "))))))
7897 ; (backward-char 2) t)))))
7898 (when (and force (not (looking-at ".*|")))
7899 (save-excursion (end-of-line 1) (insert " | ")))
7900 (if on-delim
7901 (backward-char 1)
7902 (if (looking-at " ") (forward-char 1))))))
7903
7904 (defun org-at-table-p (&optional table-type)
7905 "Return t if the cursor is inside an org-type table.
7906 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7907 (if org-enable-table-editor
7908 (save-excursion
7909 (beginning-of-line 1)
7910 (looking-at (if table-type org-table-any-line-regexp
7911 org-table-line-regexp)))
7912 nil))
7913
7914 (defun org-at-table.el-p ()
7915 "Return t if and only if we are at a table.el table."
7916 (and (org-at-table-p 'any)
7917 (save-excursion
7918 (goto-char (org-table-begin 'any))
7919 (looking-at org-table1-hline-regexp))))
7920
7921 (defun org-table-recognize-table.el ()
7922 "If there is a table.el table nearby, recognize it and move into it."
7923 (if org-table-tab-recognizes-table.el
7924 (if (org-at-table.el-p)
7925 (progn
7926 (beginning-of-line 1)
7927 (if (looking-at org-table-dataline-regexp)
7928 nil
7929 (if (looking-at org-table1-hline-regexp)
7930 (progn
7931 (beginning-of-line 2)
7932 (if (looking-at org-table-any-border-regexp)
7933 (beginning-of-line -1)))))
7934 (if (re-search-forward "|" (org-table-end t) t)
7935 (progn
7936 (require 'table)
7937 (if (table--at-cell-p (point))
7938 t
7939 (message "recognizing table.el table...")
7940 (table-recognize-table)
7941 (message "recognizing table.el table...done")))
7942 (error "This should not happen..."))
7943 t)
7944 nil)
7945 nil))
7946
7947 (defun org-at-table-hline-p ()
7948 "Return t if the cursor is inside a hline in a table."
7949 (if org-enable-table-editor
7950 (save-excursion
7951 (beginning-of-line 1)
7952 (looking-at org-table-hline-regexp))
7953 nil))
7954
7955 (defun org-table-insert-column ()
7956 "Insert a new column into the table."
7957 (interactive)
7958 (if (not (org-at-table-p))
7959 (error "Not at a table"))
7960 (org-table-find-dataline)
7961 (let* ((col (max 1 (org-table-current-column)))
7962 (beg (org-table-begin))
7963 (end (org-table-end))
7964 ;; Current cursor position
7965 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7966 (colpos col))
7967 (goto-char beg)
7968 (while (< (point) end)
7969 (if (org-at-table-hline-p)
7970 nil
7971 (org-table-goto-column col t)
7972 (insert "| "))
7973 (beginning-of-line 2))
7974 (move-marker end nil)
7975 (goto-line linepos)
7976 (org-table-goto-column colpos)
7977 (org-table-align)
7978 (org-table-modify-formulas 'insert col)))
7979
7980 (defun org-table-find-dataline ()
7981 "Find a dataline in the current table, which is needed for column commands."
7982 (if (and (org-at-table-p)
7983 (not (org-at-table-hline-p)))
7984 t
7985 (let ((col (current-column))
7986 (end (org-table-end)))
7987 (move-to-column col)
7988 (while (and (< (point) end)
7989 (or (not (= (current-column) col))
7990 (org-at-table-hline-p)))
7991 (beginning-of-line 2)
7992 (move-to-column col))
7993 (if (and (org-at-table-p)
7994 (not (org-at-table-hline-p)))
7995 t
7996 (error
7997 "Please position cursor in a data line for column operations")))))
7998
7999 (defun org-table-delete-column ()
8000 "Delete a column into the table."
8001 (interactive)
8002 (if (not (org-at-table-p))
8003 (error "Not at a table"))
8004 (org-table-find-dataline)
8005 (org-table-check-inside-data-field)
8006 (let* ((col (org-table-current-column))
8007 (beg (org-table-begin))
8008 (end (org-table-end))
8009 ;; Current cursor position
8010 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8011 (colpos col))
8012 (goto-char beg)
8013 (while (< (point) end)
8014 (if (org-at-table-hline-p)
8015 nil
8016 (org-table-goto-column col t)
8017 (and (looking-at "|[^|\n]+|")
8018 (replace-match "|")))
8019 (beginning-of-line 2))
8020 (move-marker end nil)
8021 (goto-line linepos)
8022 (org-table-goto-column colpos)
8023 (org-table-align)
8024 (org-table-modify-formulas 'remove col)))
8025
8026 (defun org-table-move-column-right ()
8027 "Move column to the right."
8028 (interactive)
8029 (org-table-move-column nil))
8030 (defun org-table-move-column-left ()
8031 "Move column to the left."
8032 (interactive)
8033 (org-table-move-column 'left))
8034
8035 (defun org-table-move-column (&optional left)
8036 "Move the current column to the right. With arg LEFT, move to the left."
8037 (interactive "P")
8038 (if (not (org-at-table-p))
8039 (error "Not at a table"))
8040 (org-table-find-dataline)
8041 (org-table-check-inside-data-field)
8042 (let* ((col (org-table-current-column))
8043 (col1 (if left (1- col) col))
8044 (beg (org-table-begin))
8045 (end (org-table-end))
8046 ;; Current cursor position
8047 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8048 (colpos (if left (1- col) (1+ col))))
8049 (if (and left (= col 1))
8050 (error "Cannot move column further left"))
8051 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8052 (error "Cannot move column further right"))
8053 (goto-char beg)
8054 (while (< (point) end)
8055 (if (org-at-table-hline-p)
8056 nil
8057 (org-table-goto-column col1 t)
8058 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8059 (replace-match "|\\2|\\1|")))
8060 (beginning-of-line 2))
8061 (move-marker end nil)
8062 (goto-line linepos)
8063 (org-table-goto-column colpos)
8064 (org-table-align)
8065 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8066
8067 (defun org-table-move-row-down ()
8068 "move table row down."
8069 (interactive)
8070 (org-table-move-row nil))
8071 (defun org-table-move-row-up ()
8072 "move table row up."
8073 (interactive)
8074 (org-table-move-row 'up))
8075
8076 (defun org-table-move-row (&optional up)
8077 "Move the current table line down. With arg UP, move it up."
8078 (interactive "P")
8079 (let ((col (current-column))
8080 (pos (point))
8081 (tonew (if up 0 2))
8082 txt)
8083 (beginning-of-line tonew)
8084 (if (not (org-at-table-p))
8085 (progn
8086 (goto-char pos)
8087 (error "Cannot move row further")))
8088 (goto-char pos)
8089 (beginning-of-line 1)
8090 (setq pos (point))
8091 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8092 (delete-region (point) (1+ (point-at-eol)))
8093 (beginning-of-line tonew)
8094 (insert txt)
8095 (beginning-of-line 0)
8096 (move-to-column col)))
8097
8098 (defun org-table-insert-row (&optional arg)
8099 "Insert a new row above the current line into the table.
8100 With prefix ARG, insert below the current line."
8101 (interactive "P")
8102 (if (not (org-at-table-p))
8103 (error "Not at a table"))
8104 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8105 new)
8106 (if (string-match "^[ \t]*|-" line)
8107 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8108 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8109 ;; Fix the first field if necessary
8110 (setq new (concat new))
8111 (if (string-match "^[ \t]*| *[#$] *|" line)
8112 (setq new (replace-match (match-string 0 line) t t new)))
8113 (beginning-of-line (if arg 2 1))
8114 (let (org-table-may-need-update)
8115 (insert-before-markers new)
8116 (insert-before-markers "\n"))
8117 (beginning-of-line 0)
8118 (re-search-forward "| ?" (point-at-eol) t)
8119 (and org-table-may-need-update (org-table-align))))
8120
8121 (defun org-table-insert-hline (&optional arg)
8122 "Insert a horizontal-line below the current line into the table.
8123 With prefix ARG, insert above the current line."
8124 (interactive "P")
8125 (if (not (org-at-table-p))
8126 (error "Not at a table"))
8127 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8128 (col (current-column))
8129 start)
8130 (if (string-match "^[ \t]*|-" line)
8131 (setq line
8132 (mapcar (lambda (x) (if (member x '(?| ?+))
8133 (prog1 (if start ?+ ?|) (setq start t))
8134 (if start ?- ?\ )))
8135 line))
8136 (setq line
8137 (mapcar (lambda (x) (if (equal x ?|)
8138 (prog1 (if start ?+ ?|) (setq start t))
8139 (if start ?- ?\ )))
8140 line)))
8141 (beginning-of-line (if arg 1 2))
8142 (apply 'insert line)
8143 (if (equal (char-before (point)) ?+)
8144 (progn (backward-delete-char 1) (insert "|")))
8145 (insert "\n")
8146 (beginning-of-line 0)
8147 (move-to-column col)))
8148
8149 (defun org-table-kill-row ()
8150 "Delete the current row or horizontal line from the table."
8151 (interactive)
8152 (if (not (org-at-table-p))
8153 (error "Not at a table"))
8154 (let ((col (current-column)))
8155 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8156 (if (not (org-at-table-p)) (beginning-of-line 0))
8157 (move-to-column col)))
8158
8159 (defun org-table-sort-lines (beg end numericp)
8160 "Sort table lines in region.
8161 Point and mark define the first and last line to include. Both point and
8162 mark should be in the column that is used for sorting. For example, to
8163 sort according to column 3, put the mark in the first line to sort, in
8164 table column 3. Put point into the last line to be included in the sorting,
8165 also in table column 3. The command will prompt for the sorting method (n for
8166 numerical, a for alphanumeric)."
8167 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8168 (setq numericp (string-match "[nN]" numericp))
8169 (org-table-align) ;; Just to be safe
8170 (let* (bcol ecol cmp column lns)
8171 (goto-char beg)
8172 (org-table-check-inside-data-field)
8173 (setq column (org-table-current-column)
8174 beg (move-marker (make-marker) (point-at-bol)))
8175 (goto-char end)
8176 (org-table-check-inside-data-field)
8177 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8178 (untabify beg end)
8179 (goto-char beg)
8180 (org-table-goto-column column)
8181 (skip-chars-backward "^|")
8182 (setq bcol (current-column))
8183 (org-table-goto-column (1+ column))
8184 (skip-chars-backward "^|")
8185 (setq ecol (1- (current-column)))
8186 (setq cmp (if numericp
8187 (lambda (a b) (< (car a) (car b)))
8188 (lambda (a b) (string< (car a) (car b)))))
8189 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8190 (split-string (buffer-substring beg end) "\n")))
8191 (if numericp
8192 (setq lns (mapcar (lambda(x)
8193 (cons (string-to-number (car x)) (cdr x)))
8194 lns)))
8195 (delete-region beg end)
8196 (move-marker beg nil)
8197 (move-marker end nil)
8198 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8199 (message "%d lines sorted %s based on column %d"
8200 (length lns)
8201 (if numericp "numerically" "alphabetically") column)))
8202
8203 (defun org-table-cut-region (beg end)
8204 "Copy region in table to the clipboard and blank all relevant fields."
8205 (interactive "r")
8206 (org-table-copy-region beg end 'cut))
8207
8208 (defun org-table-copy-region (beg end &optional cut)
8209 "Copy rectangular region in table to clipboard.
8210 A special clipboard is used which can only be accessed
8211 with `org-table-paste-rectangle'"
8212 (interactive "rP")
8213 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8214 region cols
8215 (rpl (if cut " " nil)))
8216 (goto-char beg)
8217 (org-table-check-inside-data-field)
8218 (setq l01 (count-lines (point-min) (point))
8219 c01 (org-table-current-column))
8220 (goto-char end)
8221 (org-table-check-inside-data-field)
8222 (setq l02 (count-lines (point-min) (point))
8223 c02 (org-table-current-column))
8224 (setq l1 (min l01 l02) l2 (max l01 l02)
8225 c1 (min c01 c02) c2 (max c01 c02))
8226 (catch 'exit
8227 (while t
8228 (catch 'nextline
8229 (if (> l1 l2) (throw 'exit t))
8230 (goto-line l1)
8231 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8232 (setq cols nil ic1 c1 ic2 c2)
8233 (while (< ic1 (1+ ic2))
8234 (push (org-table-get-field ic1 rpl) cols)
8235 (setq ic1 (1+ ic1)))
8236 (push (nreverse cols) region)
8237 (setq l1 (1+ l1)))))
8238 (setq org-table-clip (nreverse region))
8239 (if cut (org-table-align))
8240 org-table-clip))
8241
8242 (defun org-table-paste-rectangle ()
8243 "Paste a rectangular region into a table.
8244 The upper right corner ends up in the current field. All involved fields
8245 will be overwritten. If the rectangle does not fit into the present table,
8246 the table is enlarged as needed. The process ignores horizontal separator
8247 lines."
8248 (interactive)
8249 (unless (and org-table-clip (listp org-table-clip))
8250 (error "First cut/copy a region to paste!"))
8251 (org-table-check-inside-data-field)
8252 (let* ((clip org-table-clip)
8253 (line (count-lines (point-min) (point)))
8254 (col (org-table-current-column))
8255 (org-enable-table-editor t)
8256 (org-table-automatic-realign nil)
8257 c cols field)
8258 (while (setq cols (pop clip))
8259 (while (org-at-table-hline-p) (beginning-of-line 2))
8260 (if (not (org-at-table-p))
8261 (progn (end-of-line 0) (org-table-next-field)))
8262 (setq c col)
8263 (while (setq field (pop cols))
8264 (org-table-goto-column c nil 'force)
8265 (org-table-get-field nil field)
8266 (setq c (1+ c)))
8267 (beginning-of-line 2))
8268 (goto-line line)
8269 (org-table-goto-column col)
8270 (org-table-align)))
8271
8272 (defun org-table-convert ()
8273 "Convert from `org-mode' table to table.el and back.
8274 Obviously, this only works within limits. When an Org-mode table is
8275 converted to table.el, all horizontal separator lines get lost, because
8276 table.el uses these as cell boundaries and has no notion of horizontal lines.
8277 A table.el table can be converted to an Org-mode table only if it does not
8278 do row or column spanning. Multiline cells will become multiple cells.
8279 Beware, Org-mode does not test if the table can be successfully converted - it
8280 blindly applies a recipe that works for simple tables."
8281 (interactive)
8282 (require 'table)
8283 (if (org-at-table.el-p)
8284 ;; convert to Org-mode table
8285 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8286 (end (move-marker (make-marker) (org-table-end t))))
8287 (table-unrecognize-region beg end)
8288 (goto-char beg)
8289 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8290 (replace-match ""))
8291 (goto-char beg))
8292 (if (org-at-table-p)
8293 ;; convert to table.el table
8294 (let ((beg (move-marker (make-marker) (org-table-begin)))
8295 (end (move-marker (make-marker) (org-table-end))))
8296 ;; first, get rid of all horizontal lines
8297 (goto-char beg)
8298 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8299 (replace-match ""))
8300 ;; insert a hline before first
8301 (goto-char beg)
8302 (org-table-insert-hline 'above)
8303 ;; insert a hline after each line
8304 (while (progn (beginning-of-line 2) (< (point) end))
8305 (org-table-insert-hline))
8306 (goto-char beg)
8307 (setq end (move-marker end (org-table-end)))
8308 ;; replace "+" at beginning and ending of hlines
8309 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8310 (replace-match "\\1+-"))
8311 (goto-char beg)
8312 (while (re-search-forward "-|[ \t]*$" end t)
8313 (replace-match "-+"))
8314 (goto-char beg)))))
8315
8316 (defun org-table-wrap-region (arg)
8317 "Wrap several fields in a column like a paragraph.
8318 This is useful if you'd like to spread the contents of a field over several
8319 lines, in order to keep the table compact.
8320
8321 If there is an active region, and both point and mark are in the same column,
8322 the text in the column is wrapped to minimum width for the given number of
8323 lines. Generally, this makes the table more compact. A prefix ARG may be
8324 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8325 formats the selected text to two lines. If the region was longer than 2
8326 lines, the remaining lines remain empty. A negative prefix argument reduces
8327 the current number of lines by that amount. The wrapped text is pasted back
8328 into the table. If you formatted it to more lines than it was before, fields
8329 further down in the table get overwritten - so you might need to make space in
8330 the table first.
8331
8332 If there is no region, the current field is split at the cursor position and
8333 the text fragment to the right of the cursor is prepended to the field one
8334 line down.
8335
8336 If there is no region, but you specify a prefix ARG, the current field gets
8337 blank, and the content is appended to the field above."
8338 (interactive "P")
8339 (org-table-check-inside-data-field)
8340 (if (org-region-active-p)
8341 ;; There is a region: fill as a paragraph
8342 (let ((beg (region-beginning))
8343 nlines)
8344 (org-table-cut-region (region-beginning) (region-end))
8345 (if (> (length (car org-table-clip)) 1)
8346 (error "Region must be limited to single column"))
8347 (setq nlines (if arg
8348 (if (< arg 1)
8349 (+ (length org-table-clip) arg)
8350 arg)
8351 (length org-table-clip)))
8352 (setq org-table-clip
8353 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8354 nil nlines)))
8355 (goto-char beg)
8356 (org-table-paste-rectangle))
8357 ;; No region, split the current field at point
8358 (if arg
8359 ;; combine with field above
8360 (let ((s (org-table-blank-field))
8361 (col (org-table-current-column)))
8362 (beginning-of-line 0)
8363 (while (org-at-table-hline-p) (beginning-of-line 0))
8364 (org-table-goto-column col)
8365 (skip-chars-forward "^|")
8366 (skip-chars-backward " ")
8367 (insert " " (org-trim s))
8368 (org-table-align))
8369 ;; split field
8370 (when (looking-at "\\([^|]+\\)+|")
8371 (let ((s (match-string 1)))
8372 (replace-match " |")
8373 (goto-char (match-beginning 0))
8374 (org-table-next-row)
8375 (insert (org-trim s) " ")
8376 (org-table-align))))))
8377
8378 (defun org-trim (s)
8379 "Remove whitespace at beginning and end of string."
8380 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8381 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8382 s)
8383
8384 (defun org-wrap (string &optional width lines)
8385 "Wrap string to either a number of lines, or a width in characters.
8386 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8387 that costs. If there is a word longer than WIDTH, the text is actually
8388 wrapped to the length of that word.
8389 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8390 many lines, whatever width that takes.
8391 The return value is a list of lines, without newlines at the end."
8392 (let* ((words (org-split-string string "[ \t\n]+"))
8393 (maxword (apply 'max (mapcar 'length words)))
8394 w ll)
8395 (cond (width
8396 (org-do-wrap words (max maxword width)))
8397 (lines
8398 (setq w maxword)
8399 (setq ll (org-do-wrap words maxword))
8400 (if (<= (length ll) lines)
8401 ll
8402 (setq ll words)
8403 (while (> (length ll) lines)
8404 (setq w (1+ w))
8405 (setq ll (org-do-wrap words w)))
8406 ll))
8407 (t (error "Cannot wrap this")))))
8408
8409
8410 (defun org-do-wrap (words width)
8411 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8412 (let (lines line)
8413 (while words
8414 (setq line (pop words))
8415 (while (and words (< (+ (length line) (length (car words))) width))
8416 (setq line (concat line " " (pop words))))
8417 (setq lines (push line lines)))
8418 (nreverse lines)))
8419
8420 ;; FIXME: I think I can make this more efficient
8421 (defun org-split-string (string &optional separators)
8422 "Splits STRING into substrings at SEPARATORS.
8423 No empty strings are returned if there are matches at the beginning
8424 and end of string."
8425 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8426 (start 0)
8427 notfirst
8428 (list nil))
8429 (while (and (string-match rexp string
8430 (if (and notfirst
8431 (= start (match-beginning 0))
8432 (< start (length string)))
8433 (1+ start) start))
8434 (< (match-beginning 0) (length string)))
8435 (setq notfirst t)
8436 (or (eq (match-beginning 0) 0)
8437 (and (eq (match-beginning 0) (match-end 0))
8438 (eq (match-beginning 0) start))
8439 (setq list
8440 (cons (substring string start (match-beginning 0))
8441 list)))
8442 (setq start (match-end 0)))
8443 (or (eq start (length string))
8444 (setq list
8445 (cons (substring string start)
8446 list)))
8447 (nreverse list)))
8448
8449 (defun org-table-add-invisible-to-vertical-lines ()
8450 "Add an `invisible' property to vertical lines of current table."
8451 (interactive)
8452 (let* ((beg (org-table-begin))
8453 (end (org-table-end))
8454 (end1))
8455 (save-excursion
8456 (goto-char beg)
8457 (while (< (point) end)
8458 (setq end1 (point-at-eol))
8459 (if (looking-at org-table-dataline-regexp)
8460 (while (re-search-forward "|" end1 t)
8461 (add-text-properties (1- (point)) (point)
8462 '(invisible org-table)))
8463 (while (re-search-forward "[+|]" end1 t)
8464 (add-text-properties (1- (point)) (point)
8465 '(invisible org-table))))
8466 (beginning-of-line 2)))))
8467
8468 (defun org-table-toggle-vline-visibility (&optional arg)
8469 "Toggle the visibility of table vertical lines.
8470 The effect is immediate and on all tables in the file.
8471 With prefix ARG, make lines invisible when ARG is positive, make lines
8472 visible when ARG is not positive"
8473 (interactive "P")
8474 (let ((action (cond
8475 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8476 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8477 (t (if (org-in-invisibility-spec-p '(org-table))
8478 'off
8479 'on)))))
8480 (if (eq action 'off)
8481 (progn
8482 (org-remove-from-invisibility-spec '(org-table))
8483 (org-table-map-tables 'org-table-align)
8484 (message "Vertical table lines visible")
8485 (if (org-at-table-p)
8486 (org-table-align)))
8487 (org-add-to-invisibility-spec '(org-table))
8488 (org-table-map-tables 'org-table-align)
8489 (message "Vertical table lines invisible"))
8490 (redraw-frame (selected-frame))))
8491
8492 (defun org-table-map-tables (function)
8493 "Apply FUNCTION to the start of all tables in the buffer."
8494 (save-excursion
8495 (save-restriction
8496 (widen)
8497 (goto-char (point-min))
8498 (while (re-search-forward org-table-any-line-regexp nil t)
8499 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8500 (beginning-of-line 1)
8501 (if (looking-at org-table-line-regexp)
8502 (save-excursion (funcall function)))
8503 (re-search-forward org-table-any-border-regexp nil 1)))))
8504
8505 (defun org-table-sum (&optional beg end nlast)
8506 "Sum numbers in region of current table column.
8507 The result will be displayed in the echo area, and will be available
8508 as kill to be inserted with \\[yank].
8509
8510 If there is an active region, it is interpreted as a rectangle and all
8511 numbers in that rectangle will be summed. If there is no active
8512 region and point is located in a table column, sum all numbers in that
8513 column.
8514
8515 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8516 numbers are assumed to be times as well (in decimal hours) and the
8517 numbers are added as such.
8518
8519 If NLAST is a number, only the NLAST fields will actually be summed."
8520 (interactive)
8521 (save-excursion
8522 (let (col (timecnt 0) diff h m s org-table-clip)
8523 (cond
8524 ((and beg end)) ; beg and end given explicitly
8525 ((org-region-active-p)
8526 (setq beg (region-beginning) end (region-end)))
8527 (t
8528 (setq col (org-table-current-column))
8529 (goto-char (org-table-begin))
8530 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8531 (error "No table data"))
8532 (org-table-goto-column col)
8533 ;not needed? (skip-chars-backward "^|")
8534 (setq beg (point))
8535 (goto-char (org-table-end))
8536 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8537 (error "No table data"))
8538 (org-table-goto-column col)
8539 ;not needed? (skip-chars-forward "^|")
8540 (setq end (point))))
8541 (let* ((items (apply 'append (org-table-copy-region beg end)))
8542 (items1 (cond ((not nlast) items)
8543 ((>= nlast (length items)) items)
8544 (t (setq items (reverse items))
8545 (setcdr (nthcdr (1- nlast) items) nil)
8546 (nreverse items))))
8547 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8548 items1)))
8549 (res (apply '+ numbers))
8550 (sres (if (= timecnt 0)
8551 (format "%g" res)
8552 (setq diff (* 3600 res)
8553 h (floor (/ diff 3600)) diff (mod diff 3600)
8554 m (floor (/ diff 60)) diff (mod diff 60)
8555 s diff)
8556 (format "%d:%02d:%02d" h m s))))
8557 (kill-new sres)
8558 (if (interactive-p)
8559 (message "%s"
8560 (substitute-command-keys
8561 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8562 (length numbers) sres))))
8563 sres))))
8564
8565 (defun org-table-get-number-for-summing (s)
8566 (let (n)
8567 (if (string-match "^ *|? *" s)
8568 (setq s (replace-match "" nil nil s)))
8569 (if (string-match " *|? *$" s)
8570 (setq s (replace-match "" nil nil s)))
8571 (setq n (string-to-number s))
8572 (cond
8573 ((and (string-match "0" s)
8574 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8575 ((string-match "\\`[ \t]+\\'" s) nil)
8576 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8577 (let ((h (string-to-number (or (match-string 1 s) "0")))
8578 (m (string-to-number (or (match-string 2 s) "0")))
8579 (s (string-to-number (or (match-string 4 s) "0"))))
8580 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8581 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8582 ((equal n 0) nil)
8583 (t n))))
8584
8585 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8586 "Get a calc vector from a column, accorting to desctiptor DESC.
8587 Optional arguments TBEG and COL can give the beginning of the table and
8588 the current column, to avoid unnecessary parsing."
8589 (save-excursion
8590 (or tbeg (setq tbeg (org-table-begin)))
8591 (or col (setq col (org-table-current-column)))
8592 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8593 (cond
8594 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8595 (setq n1 (- (match-end 1) (match-beginning 1)))
8596 (if (match-beginning 3)
8597 (setq n2 (- (match-end 2) (match-beginning 3))))
8598 (setq n (if n2 (max n1 n2) n1))
8599 (setq n1 (if n2 (min n1 n2)))
8600 (setq nn n)
8601 (while (and (> nn 0)
8602 (re-search-backward org-table-hline-regexp tbeg t))
8603 (push (org-current-line) hline-list)
8604 (setq nn (1- nn)))
8605 (setq hline-list (nreverse hline-list))
8606 (goto-line (nth (1- n) hline-list))
8607 (when (re-search-forward org-table-dataline-regexp)
8608 (org-table-goto-column col)
8609 (setq beg (point)))
8610 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8611 (when (re-search-backward org-table-dataline-regexp)
8612 (org-table-goto-column col)
8613 (setq end (point)))
8614 (setq l (apply 'append (org-table-copy-region beg end)))
8615 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8616 (if (equal x "") "0" x))
8617 l ",") "]"))
8618 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8619 (setq n1 (string-to-number (match-string 1 desc))
8620 n2 (string-to-number (match-string 2 desc)))
8621 (beginning-of-line 1)
8622 (save-excursion
8623 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8624 (org-table-goto-column col)
8625 (setq beg (point))))
8626 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8627 (org-table-goto-column col)
8628 (setq end (point)))
8629 (setq l (apply 'append (org-table-copy-region beg end)))
8630 (concat "[" (mapconcat
8631 (lambda (x) (setq x (org-trim x))
8632 (if (equal x "") "0" x))
8633 l ",") "]"))
8634 ((string-match "\\([0-9]+\\)" desc)
8635 (beginning-of-line 1)
8636 (when (re-search-backward org-table-dataline-regexp tbeg t
8637 (string-to-number (match-string 0 desc)))
8638 (org-table-goto-column col)
8639 (org-trim (org-table-get-field))))))))
8640
8641 (defvar org-table-formula-history nil)
8642
8643 (defvar org-table-column-names nil
8644 "Alist with column names, derived from the `!' line.")
8645 (defvar org-table-column-name-regexp nil
8646 "Regular expression matching the current column names.")
8647 (defvar org-table-local-parameters nil
8648 "Alist with parameter names, derived from the `$' line.")
8649 (defvar org-table-named-field-locations nil
8650 "Alist with locations of named fields.")
8651
8652 (defun org-table-get-formula (&optional equation named)
8653 "Read a formula from the minibuffer, offer stored formula as default."
8654 (let* ((name (car (rassoc (list (org-current-line)
8655 (org-table-current-column))
8656 org-table-named-field-locations)))
8657 (scol (if named
8658 (if name name
8659 (error "Not in a named field"))
8660 (int-to-string (org-table-current-column))))
8661 (dummy (and name (not named)
8662 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8663 (error "Abort")))
8664 (org-table-may-need-update nil)
8665 (stored-list (org-table-get-stored-formulas))
8666 (stored (cdr (assoc scol stored-list)))
8667 (eq (cond
8668 ((and stored equation (string-match "^ *=? *$" equation))
8669 stored)
8670 ((stringp equation)
8671 equation)
8672 (t (read-string
8673 (format "%s formula $%s=" (if named "Field" "Column") scol)
8674 (or stored "") 'org-table-formula-history
8675 ;stored
8676 ))))
8677 mustsave)
8678 (when (not (string-match "\\S-" eq))
8679 ;; remove formula
8680 (setq stored-list (delq (assoc scol stored-list) stored-list))
8681 (org-table-store-formulas stored-list)
8682 (error "Formula removed"))
8683 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8684 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8685 (if (and name (not named))
8686 ;; We set the column equation, delete the named one.
8687 (setq stored-list (delq (assoc name stored-list) stored-list)
8688 mustsave t))
8689 (if stored
8690 (setcdr (assoc scol stored-list) eq)
8691 (setq stored-list (cons (cons scol eq) stored-list)))
8692 (if (or mustsave (not (equal stored eq)))
8693 (org-table-store-formulas stored-list))
8694 eq))
8695
8696 (defun org-table-store-formulas (alist)
8697 "Store the list of formulas below the current table."
8698 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8699 (save-excursion
8700 (goto-char (org-table-end))
8701 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8702 (delete-region (point) (match-end 0)))
8703 (insert "#+TBLFM: "
8704 (mapconcat (lambda (x)
8705 (concat "$" (car x) "=" (cdr x)))
8706 alist "::")
8707 "\n")))
8708
8709 (defun org-table-get-stored-formulas ()
8710 "Return an alist with the t=stored formulas directly after current table."
8711 (interactive)
8712 (let (scol eq eq-alist strings string seen)
8713 (save-excursion
8714 (goto-char (org-table-end))
8715 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8716 (setq strings (org-split-string (match-string 2) " *:: *"))
8717 (while (setq string (pop strings))
8718 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8719 (setq scol (match-string 1 string)
8720 eq (match-string 2 string)
8721 eq-alist (cons (cons scol eq) eq-alist))
8722 (if (member scol seen)
8723 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8724 (push scol seen))))))
8725 (nreverse eq-alist)))
8726
8727 (defun org-table-modify-formulas (action &rest columns)
8728 "Modify the formulas stored below the current table.
8729 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8730 expected, for the other action only a single column number is needed."
8731 (let ((list (org-table-get-stored-formulas))
8732 (nmax (length (org-split-string
8733 (buffer-substring (point-at-bol) (point-at-eol))
8734 "|")))
8735 col col1 col2 scol si sc1 sc2)
8736 (cond
8737 ((null list)) ; No action needed if there are no stored formulas
8738 ((eq action 'remove)
8739 (setq col (car columns)
8740 scol (int-to-string col))
8741 (org-table-replace-in-formulas list scol "INVALID")
8742 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8743 (loop for i from (1+ col) upto nmax by 1 do
8744 (setq si (int-to-string i))
8745 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8746 (if (assoc si list) (setcar (assoc si list)
8747 (int-to-string (1- i))))))
8748 ((eq action 'insert)
8749 (setq col (car columns))
8750 (loop for i from nmax downto col by 1 do
8751 (setq si (int-to-string i))
8752 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8753 (if (assoc si list) (setcar (assoc si list)
8754 (int-to-string (1+ i))))))
8755 ((eq action 'swap)
8756 (setq col1 (car columns) col2 (nth 1 columns)
8757 sc1 (int-to-string col1) sc2 (int-to-string col2))
8758 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8759 (org-table-replace-in-formulas list sc1 "ZqZ")
8760 (org-table-replace-in-formulas list sc2 sc1)
8761 (org-table-replace-in-formulas list "ZqZ" sc2)
8762 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8763 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8764 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8765 (t (error "Invalid action in `org-table-modify-formulas'")))
8766 (if list (org-table-store-formulas list))))
8767
8768 (defun org-table-replace-in-formulas (list s1 s2)
8769 (let (elt re s)
8770 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8771 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8772 re (concat (regexp-quote s1) "\\>"))
8773 (while (setq elt (pop list))
8774 (setq s (cdr elt))
8775 (while (string-match re s)
8776 (setq s (replace-match s2 t t s)))
8777 (setcdr elt s))))
8778
8779 (defun org-table-get-specials ()
8780 "Get the column nmaes and local parameters for this table."
8781 (save-excursion
8782 (let ((beg (org-table-begin)) (end (org-table-end))
8783 names name fields fields1 field cnt c v line col)
8784 (setq org-table-column-names nil
8785 org-table-local-parameters nil
8786 org-table-named-field-locations nil)
8787 (goto-char beg)
8788 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8789 (setq names (org-split-string (match-string 1) " *| *")
8790 cnt 1)
8791 (while (setq name (pop names))
8792 (setq cnt (1+ cnt))
8793 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8794 (push (cons name (int-to-string cnt)) org-table-column-names))))
8795 (setq org-table-column-names (nreverse org-table-column-names))
8796 (setq org-table-column-name-regexp
8797 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8798 (goto-char beg)
8799 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8800 (setq fields (org-split-string (match-string 1) " *| *"))
8801 (while (setq field (pop fields))
8802 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8803 (push (cons (match-string 1 field) (match-string 2 field))
8804 org-table-local-parameters))))
8805 (goto-char beg)
8806 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8807 (setq c (match-string 1)
8808 fields (org-split-string (match-string 2) " *| *"))
8809 (save-excursion
8810 (beginning-of-line (if (equal c "_") 2 0))
8811 (setq line (org-current-line) col 1)
8812 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8813 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8814 (while (and fields1 (setq field (pop fields)))
8815 (setq v (pop fields1) col (1+ col))
8816 (when (and (stringp field) (stringp v)
8817 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8818 (push (cons field v) org-table-local-parameters)
8819 (push (list field line col) org-table-named-field-locations)))))))
8820
8821 (defun org-this-word ()
8822 ;; Get the current word
8823 (save-excursion
8824 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8825 (end (progn (skip-chars-forward "^ \t\n") (point))))
8826 (buffer-substring-no-properties beg end))))
8827
8828 (defun org-table-maybe-eval-formula ()
8829 "Check if the current field starts with \"=\" or \":=\".
8830 If yes, store the formula and apply it."
8831 ;; We already know we are in a table. Get field will only return a formula
8832 ;; when appropriate. It might return a separator line, but no problem.
8833 (when org-table-formula-evaluate-inline
8834 (let* ((field (org-trim (or (org-table-get-field) "")))
8835 named eq)
8836 (when (string-match "^:?=\\(.*\\)" field)
8837 (setq named (equal (string-to-char field) ?:)
8838 eq (match-string 1 field))
8839 (if (fboundp 'calc-eval)
8840 (org-table-eval-formula (if named '(4) nil) eq))))))
8841
8842 (defvar org-recalc-commands nil
8843 "List of commands triggering the reccalculation of a line.
8844 Will be filled automatically during use.")
8845
8846 (defvar org-recalc-marks
8847 '((" " . "Unmarked: no special line, no automatic recalculation")
8848 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8849 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8850 ("!" . "Column name definition line. Reference in formula as $name.")
8851 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8852 ("_" . "Names for values in row below this one.")
8853 ("^" . "Names for values in row above this one.")))
8854
8855 (defun org-table-rotate-recalc-marks (&optional newchar)
8856 "Rotate the recalculation mark in the first column.
8857 If in any row, the first field is not consistent with a mark,
8858 insert a new column for the makers.
8859 When there is an active region, change all the lines in the region,
8860 after prompting for the marking character.
8861 After each change, a message will be displayed indication the meaning
8862 of the new mark."
8863 (interactive)
8864 (unless (org-at-table-p) (error "Not at a table"))
8865 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8866 (beg (org-table-begin))
8867 (end (org-table-end))
8868 (l (org-current-line))
8869 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8870 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8871 (have-col
8872 (save-excursion
8873 (goto-char beg)
8874 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8875 (col (org-table-current-column))
8876 (forcenew (car (assoc newchar org-recalc-marks)))
8877 epos new)
8878 (when l1
8879 (message "Change region to what mark? Type # * ! $ or SPC: ")
8880 (setq newchar (char-to-string (read-char-exclusive))
8881 forcenew (car (assoc newchar org-recalc-marks))))
8882 (if (and newchar (not forcenew))
8883 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8884 newchar))
8885 (if l1 (goto-line l1))
8886 (save-excursion
8887 (beginning-of-line 1)
8888 (unless (looking-at org-table-dataline-regexp)
8889 (error "Not at a table data line")))
8890 (unless have-col
8891 (org-table-goto-column 1)
8892 (org-table-insert-column)
8893 (org-table-goto-column (1+ col)))
8894 (setq epos (point-at-eol))
8895 (save-excursion
8896 (beginning-of-line 1)
8897 (org-table-get-field
8898 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8899 (concat " "
8900 (setq new (or forcenew
8901 (cadr (member (match-string 1) marks))))
8902 " ")
8903 " # ")))
8904 (if (and l1 l2)
8905 (progn
8906 (goto-line l1)
8907 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8908 (and (looking-at org-table-dataline-regexp)
8909 (org-table-get-field 1 (concat " " new " "))))
8910 (goto-line l1)))
8911 (if (not (= epos (point-at-eol))) (org-table-align))
8912 (goto-line l)
8913 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8914
8915 (defun org-table-maybe-recalculate-line ()
8916 "Recompute the current line if marked for it, and if we haven't just done it."
8917 (interactive)
8918 (and org-table-allow-automatic-line-recalculation
8919 (not (and (memq last-command org-recalc-commands)
8920 (equal org-last-recalc-line (org-current-line))))
8921 (save-excursion (beginning-of-line 1)
8922 (looking-at org-table-auto-recalculate-regexp))
8923 (fboundp 'calc-eval)
8924 (org-table-recalculate) t))
8925
8926 (defvar org-table-formula-debug nil
8927 "Non-nil means, debug table formulas.
8928 When nil, simply write \"#ERROR\" in corrupted fields.")
8929
8930 (defvar modes)
8931 (defsubst org-set-calc-mode (var &optional value)
8932 (if (stringp var)
8933 (setq var (assoc var '(("D" calc-angle-mode deg)
8934 ("R" calc-angle-mode rad)
8935 ("F" calc-prefer-frac t)
8936 ("S" calc-symbolic-mode t)))
8937 value (nth 2 var) var (nth 1 var)))
8938 (if (memq var modes)
8939 (setcar (cdr (memq var modes)) value)
8940 (cons var (cons value modes)))
8941 modes)
8942
8943 (defun org-table-eval-formula (&optional arg equation
8944 suppress-align suppress-const
8945 suppress-store)
8946 "Replace the table field value at the cursor by the result of a calculation.
8947
8948 This function makes use of Dave Gillespie's calc package, in my view the
8949 most exciting program ever written for GNU Emacs. So you need to have calc
8950 installed in order to use this function.
8951
8952 In a table, this command replaces the value in the current field with the
8953 result of a formula. It also installes the formula as the \"current\" column
8954 formula, by storing it in a special line below the table. When called
8955 with a `C-u' prefix, the current field must ba a named field, and the
8956 formula is installed as valid in only this specific field.
8957
8958 When called, the command first prompts for a formula, which is read in
8959 the minibuffer. Previously entered formulas are available through the
8960 history list, and the last used formula is offered as a default.
8961 These stored formulas are adapted correctly when moving, inserting, or
8962 deleting columns with the corresponding commands.
8963
8964 The formula can be any algebraic expression understood by the calc package.
8965 For details, see the Org-mode manual.
8966
8967 This function can also be called from Lisp programs and offers
8968 additional Arguments: EQUATION can be the formula to apply. If this
8969 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8970 used to speed-up recursive calls by by-passing unnecessary aligns.
8971 SUPPRESS-CONST suppresses the interpretation of constants in the
8972 formula, assuming that this has been done already outside the fuction.
8973 SUPPRESS-STORE means the formula should not be stored, either because
8974 it is already stored, or because it is a modified equation that should
8975 not overwrite the stored one."
8976 (interactive "P")
8977 (require 'calc)
8978 (org-table-check-inside-data-field)
8979 (org-table-get-specials)
8980 (let* (fields
8981 (ndown (if (integerp arg) arg 1))
8982 (org-table-automatic-realign nil)
8983 (case-fold-search nil)
8984 (down (> ndown 1))
8985 (formula (if (and equation suppress-store)
8986 equation
8987 (org-table-get-formula equation (equal arg '(4)))))
8988 (n0 (org-table-current-column))
8989 (modes (copy-sequence org-calc-default-modes))
8990 n form fmt x ev orig c)
8991 ;; Parse the format string. Since we have a lot of modes, this is
8992 ;; a lot of work. However, I think calc still uses most of the time.
8993 (if (string-match ";" formula)
8994 (let ((tmp (org-split-string formula ";")))
8995 (setq formula (car tmp)
8996 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8997 (nth 1 tmp)))
8998 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
8999 (setq c (string-to-char (match-string 1 fmt))
9000 n (string-to-number (or (match-string 1 fmt) "")))
9001 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9002 (setq modes (org-set-calc-mode
9003 'calc-float-format
9004 (list (cdr (assoc c '((?n. float) (?f. fix)
9005 (?s. sci) (?e. eng))))
9006 n))))
9007 (setq fmt (replace-match "" t t fmt)))
9008 (while (string-match "[DRFS]" fmt)
9009 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9010 (setq fmt (replace-match "" t t fmt)))
9011 (unless (string-match "\\S-" fmt)
9012 (setq fmt nil))))
9013 (if (and (not suppress-const) org-table-formula-use-constants)
9014 (setq formula (org-table-formula-substitute-names formula)))
9015 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9016 (while (> ndown 0)
9017 (setq fields (org-split-string
9018 (buffer-substring
9019 (point-at-bol) (point-at-eol)) " *| *"))
9020 (if org-table-formula-numbers-only
9021 (setq fields (mapcar
9022 (lambda (x) (number-to-string (string-to-number x)))
9023 fields)))
9024 (setq ndown (1- ndown))
9025 (setq form (copy-sequence formula))
9026 ;; Insert the references to fields in same row
9027 (while (string-match "\\$\\([0-9]+\\)?" form)
9028 (setq n (if (match-beginning 1)
9029 (string-to-number (match-string 1 form))
9030 n0)
9031 x (nth (1- n) fields))
9032 (unless x (error "Invalid field specifier \"%s\""
9033 (match-string 0 form)))
9034 (if (equal x "") (setq x "0"))
9035 (setq form (replace-match (concat "(" x ")") t t form)))
9036 ;; Insert ranges in current column
9037 (while (string-match "\\&[-I0-9]+" form)
9038 (setq form (replace-match
9039 (save-match-data
9040 (org-table-get-vertical-vector (match-string 0 form)
9041 nil n0))
9042 t t form)))
9043 (setq ev (calc-eval (cons form modes)
9044 (if org-table-formula-numbers-only 'num)))
9045
9046 (when org-table-formula-debug
9047 (with-output-to-temp-buffer "*Help*"
9048 (princ (format "Substitution history of formula
9049 Orig: %s
9050 $xyz-> %s
9051 $1-> %s\n" orig formula form))
9052 (if (listp ev)
9053 (princ (format " %s^\nError: %s"
9054 (make-string (car ev) ?\-) (nth 1 ev)))
9055 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9056 ev (or fmt "NONE")
9057 (if fmt (format fmt (string-to-number ev)) ev)))))
9058 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9059 (unless (and (interactive-p) (not ndown))
9060 (unless (let (inhibit-redisplay)
9061 (y-or-n-p "Debugging Formula. Continue to next? "))
9062 (org-table-align)
9063 (error "Abort"))
9064 (delete-window (get-buffer-window "*Help*"))
9065 (message "")))
9066 (if (listp ev) (setq fmt nil ev "#ERROR"))
9067 (org-table-justify-field-maybe
9068 (if fmt (format fmt (string-to-number ev)) ev))
9069 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9070 (call-interactively 'org-return)
9071 (setq ndown 0)))
9072 (and down (org-table-maybe-recalculate-line))
9073 (or suppress-align (and org-table-may-need-update
9074 (org-table-align)))))
9075
9076 (defun org-table-recalculate (&optional all noalign)
9077 "Recalculate the current table line by applying all stored formulas."
9078 (interactive "P")
9079 (or (memq this-command org-recalc-commands)
9080 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9081 (unless (org-at-table-p) (error "Not at a table"))
9082 (org-table-get-specials)
9083 (let* ((eqlist (sort (org-table-get-stored-formulas)
9084 (lambda (a b) (string< (car a) (car b)))))
9085 (inhibit-redisplay t)
9086 (line-re org-table-dataline-regexp)
9087 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9088 (thiscol (org-table-current-column))
9089 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9090 ;; Insert constants in all formulas
9091 (setq eqlist
9092 (mapcar (lambda (x)
9093 (setcdr x (org-table-formula-substitute-names (cdr x)))
9094 x)
9095 eqlist))
9096 ;; Split the equation list
9097 (while (setq eq (pop eqlist))
9098 (if (<= (string-to-char (car eq)) ?9)
9099 (push eq eqlnum)
9100 (push eq eqlname)))
9101 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9102 (if all
9103 (progn
9104 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9105 (goto-char (setq beg (org-table-begin)))
9106 (if (re-search-forward org-table-calculate-mark-regexp end t)
9107 ;; This is a table with marked lines, only compute selected lines
9108 (setq line-re org-table-recalculate-regexp)
9109 ;; Move forward to the first non-header line
9110 (if (and (re-search-forward org-table-dataline-regexp end t)
9111 (re-search-forward org-table-hline-regexp end t)
9112 (re-search-forward org-table-dataline-regexp end t))
9113 (setq beg (match-beginning 0))
9114 nil))) ;; just leave beg where it is
9115 (setq beg (point-at-bol)
9116 end (move-marker (make-marker) (1+ (point-at-eol)))))
9117 (goto-char beg)
9118 (and all (message "Re-applying formulas to full table..."))
9119 (while (re-search-forward line-re end t)
9120 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9121 ;; Unprotected line, recalculate
9122 (and all (message "Re-applying formulas to full table...(line %d)"
9123 (setq cnt (1+ cnt))))
9124 (setq org-last-recalc-line (org-current-line))
9125 (setq eql eqlnum)
9126 (while (setq entry (pop eql))
9127 (goto-line org-last-recalc-line)
9128 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9129 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9130 (goto-line thisline)
9131 (org-table-goto-column thiscol)
9132 (or noalign (and org-table-may-need-update (org-table-align))
9133 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9134 ;; Now do the names fields
9135 (while (setq eq (pop eqlname))
9136 (setq name (car eq)
9137 a (assoc name org-table-named-field-locations))
9138 (when a
9139 (message "Re-applying formula to named field: %s" name)
9140 (goto-line (nth 1 a))
9141 (org-table-goto-column (nth 2 a))
9142 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9143 ;; back to initial position
9144 (goto-line thisline)
9145 (org-table-goto-column thiscol)
9146 (or noalign (and org-table-may-need-update (org-table-align))
9147 (and all (message "Re-applying formulas...done")))))
9148
9149 (defun org-table-formula-substitute-names (f)
9150 "Replace $const with values in string F."
9151 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9152 ;; First, check for column names
9153 (while (setq start (string-match org-table-column-name-regexp f start))
9154 (setq start (1+ start))
9155 (setq a (assoc (match-string 1 f) org-table-column-names))
9156 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9157 ;; Expand ranges to vectors
9158 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9159 (setq n1 (string-to-number (match-string 1 f))
9160 n2 (string-to-number (match-string 2 f))
9161 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9162 s (concat "[($" (number-to-string (1- nn1)) ")"))
9163 (loop for i from nn1 upto nn2 do
9164 (setq s (concat s ",($" (int-to-string i) ")")))
9165 (setq s (concat s "]"))
9166 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9167 (setq f (replace-match s t t f)))
9168 ;; Parameters and constants
9169 (setq start 0)
9170 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9171 (setq start (1+ start))
9172 (if (setq a (save-match-data
9173 (org-table-get-constant (match-string 1 f))))
9174 (setq f (replace-match (concat "(" a ")") t t f))))
9175 (if org-table-formula-debug
9176 (put-text-property 0 (length f) :orig-formula f1 f))
9177 f))
9178
9179 (defun org-table-get-constant (const)
9180 "Find the value for a parameter or constant in a formula.
9181 Parameters get priority."
9182 (or (cdr (assoc const org-table-local-parameters))
9183 (cdr (assoc const org-table-formula-constants))
9184 (and (fboundp 'constants-get) (constants-get const))
9185 "#UNDEFINED_NAME"))
9186
9187 (defvar org-edit-formulas-map (make-sparse-keymap))
9188 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9189 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9190 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9191
9192 (defvar org-pos)
9193 (defvar org-window-configuration)
9194
9195 (defun org-table-edit-formulas ()
9196 "Edit the formulas of the current table in a separate buffer."
9197 (interactive)
9198 (unless (org-at-table-p)
9199 (error "Not at a table"))
9200 (org-table-get-specials)
9201 (let ((eql (org-table-get-stored-formulas))
9202 (pos (move-marker (make-marker) (point)))
9203 (wc (current-window-configuration))
9204 entry loc s)
9205 (switch-to-buffer-other-window "*Edit Formulas*")
9206 (erase-buffer)
9207 (fundamental-mode)
9208 (set (make-local-variable 'org-pos) pos)
9209 (set (make-local-variable 'org-window-configuration) wc)
9210 (use-local-map org-edit-formulas-map)
9211 (setq s "# Edit formulas and finish with `C-c C-c'.
9212 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9213 # Use `C-c ?' to get information about $name at point.
9214 # To cancel editing, press `C-c C-q'.\n")
9215 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9216 (insert s)
9217 (while (setq entry (pop eql))
9218 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9219 (setq s (format "# Named formula, referring to column %d in line %d\n"
9220 (nth 2 loc) (nth 1 loc)))
9221 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9222 (insert s))
9223 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9224 (remove-text-properties 0 (length s) '(face nil) s)
9225 (insert s))
9226 (goto-char (point-min))
9227 (message "Edit formulas and finish with `C-c C-c'.")))
9228
9229 (defun org-show-variable ()
9230 "Show the location/value of the $ expression at point."
9231 (interactive)
9232 (let (var (pos org-pos) (win (selected-window)) e)
9233 (save-excursion
9234 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9235 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9236 (setq var (match-string 1))
9237 (error "No variable at point")))
9238 (cond
9239 ((setq e (assoc var org-table-named-field-locations))
9240 (switch-to-buffer-other-window (marker-buffer pos))
9241 (goto-line (nth 1 e))
9242 (org-table-goto-column (nth 2 e))
9243 (select-window win)
9244 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9245 ((setq e (assoc var org-table-column-names))
9246 (switch-to-buffer-other-window (marker-buffer pos))
9247 (goto-char pos)
9248 (goto-char (org-table-begin))
9249 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9250 (org-table-end) t)
9251 (progn
9252 (goto-char (match-beginning 1))
9253 (message "Named column (column %s)" (cdr e)))
9254 (error "Column name not found"))
9255 (select-window win))
9256 ((string-match "^[0-9]$" var)
9257 ;; column number
9258 (switch-to-buffer-other-window (marker-buffer pos))
9259 (goto-char pos)
9260 (goto-char (org-table-begin))
9261 (recenter 1)
9262 (if (re-search-forward org-table-dataline-regexp
9263 (org-table-end) t)
9264 (progn
9265 (goto-char (match-beginning 0))
9266 (org-table-goto-column (string-to-number var))
9267 (message "Column %s" var))
9268 (error "Column name not found"))
9269 (select-window win))
9270 ((setq e (assoc var org-table-local-parameters))
9271 (switch-to-buffer-other-window (marker-buffer pos))
9272 (goto-char pos)
9273 (goto-char (org-table-begin))
9274 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9275 (progn
9276 (goto-char (match-beginning 1))
9277 (message "Local parameter."))
9278 (error "Parameter not found"))
9279 (select-window win))
9280 (t
9281 (cond
9282 ((setq e (assoc var org-table-formula-constants))
9283 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9284 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9285 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9286 (t (error "Undefined name $%s" var)))))))
9287
9288 (defun org-finish-edit-formulas (&optional arg)
9289 "Parse the buffer for formula definitions and install them.
9290 With prefix ARG, apply the new formulas to the table."
9291 (interactive "P")
9292 (let ((pos org-pos) eql)
9293 (goto-char (point-min))
9294 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9295 (push (cons (match-string 1) (match-string 2)) eql))
9296 (set-window-configuration org-window-configuration)
9297 (select-window (get-buffer-window (marker-buffer pos)))
9298 (goto-char pos)
9299 (unless (org-at-table-p)
9300 (error "Lost table position - cannot install formulae"))
9301 (org-table-store-formulas eql)
9302 (move-marker pos nil)
9303 (kill-buffer "*Edit Formulas*")
9304 (if arg
9305 (org-table-recalculate 'all)
9306 (message "New formulas installed - press C-u C-c C-c to apply."))))
9307
9308 (defun org-abort-edit-formulas ()
9309 "Abort editing formulas, without installing the changes."
9310 (interactive)
9311 (let ((pos org-pos))
9312 (set-window-configuration org-window-configuration)
9313 (select-window (get-buffer-window (marker-buffer pos)))
9314 (goto-char pos)
9315 (message "Formula editing aborted without installing changes")))
9316
9317 ;;; The orgtbl minor mode
9318
9319 ;; Define a minor mode which can be used in other modes in order to
9320 ;; integrate the org-mode table editor.
9321
9322 ;; This is really a hack, because the org-mode table editor uses several
9323 ;; keys which normally belong to the major mode, for example the TAB and
9324 ;; RET keys. Here is how it works: The minor mode defines all the keys
9325 ;; necessary to operate the table editor, but wraps the commands into a
9326 ;; function which tests if the cursor is currently inside a table. If that
9327 ;; is the case, the table editor command is executed. However, when any of
9328 ;; those keys is used outside a table, the function uses `key-binding' to
9329 ;; look up if the key has an associated command in another currently active
9330 ;; keymap (minor modes, major mode, global), and executes that command.
9331 ;; There might be problems if any of the keys used by the table editor is
9332 ;; otherwise used as a prefix key.
9333
9334 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9335 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9336 ;; addresses this by checking explicitly for both bindings.
9337
9338 ;; The optimized version (see variable `orgtbl-optimized') takes over
9339 ;; all keys which are bound to `self-insert-command' in the *global map*.
9340 ;; Some modes bind other commands to simple characters, for example
9341 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9342 ;; active, this binding is ignored inside tables and replaced with a
9343 ;; modified self-insert.
9344
9345 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9346 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9347 In the optimized version, the table editor takes over all simple keys that
9348 normally just insert a character. In tables, the characters are inserted
9349 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9350 for empty fields). Outside tables, the correct binding of the keys is
9351 restored.
9352
9353 The default for this option is t if the optimized version is also used in
9354 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9355 this variable requires a restart of Emacs to become effective."
9356 :group 'org-table
9357 :type 'boolean)
9358
9359 (defvar orgtbl-mode nil
9360 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9361 table editor in arbitrary modes.")
9362 (make-variable-buffer-local 'orgtbl-mode)
9363
9364 (defvar orgtbl-mode-map (make-keymap)
9365 "Keymap for `orgtbl-mode'.")
9366
9367 ;;;###autoload
9368 (defun turn-on-orgtbl ()
9369 "Unconditionally turn on `orgtbl-mode'."
9370 (orgtbl-mode 1))
9371
9372 ;;;###autoload
9373 (defun orgtbl-mode (&optional arg)
9374 "The `org-mode' table editor as a minor mode for use in other modes."
9375 (interactive)
9376 (if (eq major-mode 'org-mode)
9377 ;; Exit without error, in case some hook functions calls this
9378 ;; by accident in org-mode.
9379 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9380 (setq orgtbl-mode
9381 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9382 (if orgtbl-mode
9383 (progn
9384 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9385 ;; Make sure we are first in minor-mode-map-alist
9386 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9387 (and c (setq minor-mode-map-alist
9388 (cons c (delq c minor-mode-map-alist)))))
9389 (set (make-local-variable (quote org-table-may-need-update)) t)
9390 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9391 (add-hook 'before-change-functions 'org-before-change-function
9392 nil 'local)
9393 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9394 auto-fill-inhibit-regexp)
9395 (set (make-local-variable 'auto-fill-inhibit-regexp)
9396 (if auto-fill-inhibit-regexp
9397 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9398 "[ \t]*|"))
9399 (easy-menu-add orgtbl-mode-menu)
9400 (run-hooks 'orgtbl-mode-hook))
9401 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9402 (remove-hook 'before-change-functions 'org-before-change-function t)
9403 (easy-menu-remove orgtbl-mode-menu)
9404 (force-mode-line-update 'all))))
9405
9406 ;; Install it as a minor mode.
9407 (put 'orgtbl-mode :included t)
9408 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9409 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9410
9411 (defun orgtbl-make-binding (fun n &rest keys)
9412 "Create a function for binding in the table minor mode.
9413 FUN is the command to call inside a table. N is used to create a unique
9414 command name. KEYS are keys that should be checked in for a command
9415 to execute outside of tables."
9416 (eval
9417 (list 'defun
9418 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9419 '(arg)
9420 (concat "In tables, run `" (symbol-name fun) "'.\n"
9421 "Outside of tables, run the binding of `"
9422 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9423 "'.")
9424 '(interactive "p")
9425 (list 'if
9426 '(org-at-table-p)
9427 (list 'call-interactively (list 'quote fun))
9428 (list 'let '(orgtbl-mode)
9429 (list 'call-interactively
9430 (append '(or)
9431 (mapcar (lambda (k)
9432 (list 'key-binding k))
9433 keys)
9434 '('orgtbl-error))))))))
9435
9436 (defun orgtbl-error ()
9437 "Error when there is no default binding for a table key."
9438 (interactive)
9439 (error "This key is has no function outside tables"))
9440
9441 (defun orgtbl-setup ()
9442 "Setup orgtbl keymaps."
9443 (let ((nfunc 0)
9444 (bindings
9445 (list
9446 '([(meta shift left)] org-table-delete-column)
9447 '([(meta left)] org-table-move-column-left)
9448 '([(meta right)] org-table-move-column-right)
9449 '([(meta shift right)] org-table-insert-column)
9450 '([(meta shift up)] org-table-kill-row)
9451 '([(meta shift down)] org-table-insert-row)
9452 '([(meta up)] org-table-move-row-up)
9453 '([(meta down)] org-table-move-row-down)
9454 '("\C-c\C-w" org-table-cut-region)
9455 '("\C-c\M-w" org-table-copy-region)
9456 '("\C-c\C-y" org-table-paste-rectangle)
9457 '("\C-c-" org-table-insert-hline)
9458 ; '([(shift tab)] org-table-previous-field)
9459 '("\C-m" org-table-next-row)
9460 (list (org-key 'S-return) 'org-table-copy-down)
9461 '([(meta return)] org-table-wrap-region)
9462 '("\C-c\C-q" org-table-wrap-region)
9463 '("\C-c?" org-table-current-column)
9464 '("\C-c " org-table-blank-field)
9465 '("\C-c+" org-table-sum)
9466 '("\C-c|" org-table-toggle-vline-visibility)
9467 '("\C-c=" org-table-eval-formula)
9468 '("\C-c'" org-table-edit-formulas)
9469 '("\C-c*" org-table-recalculate)
9470 '("\C-c^" org-table-sort-lines)
9471 '([(control ?#)] org-table-rotate-recalc-marks)))
9472 elt key fun cmd)
9473 (while (setq elt (pop bindings))
9474 (setq nfunc (1+ nfunc))
9475 (setq key (car elt)
9476 fun (nth 1 elt)
9477 cmd (orgtbl-make-binding fun nfunc key))
9478 (define-key orgtbl-mode-map key cmd))
9479 ;; Special treatment needed for TAB and RET
9480 (define-key orgtbl-mode-map [(return)]
9481 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9482 (define-key orgtbl-mode-map "\C-m"
9483 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9484 (define-key orgtbl-mode-map [(tab)]
9485 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9486 (define-key orgtbl-mode-map "\C-i"
9487 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9488 (define-key orgtbl-mode-map "\C-i"
9489 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9490 (define-key orgtbl-mode-map "\C-c\C-c"
9491 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9492 (when orgtbl-optimized
9493 ;; If the user wants maximum table support, we need to hijack
9494 ;; some standard editing functions
9495 (org-remap orgtbl-mode-map
9496 'self-insert-command 'orgtbl-self-insert-command
9497 'delete-char 'orgtbl-delete-char
9498 'delete-backward-char 'orgtbl-delete-backward-char)
9499 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9500 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9501 '("OrgTbl"
9502 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9503 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9504 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9505 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9506 "--"
9507 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9508 ["Copy Field from Above"
9509 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9510 "--"
9511 ("Column"
9512 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9513 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9514 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9515 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9516 ("Row"
9517 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9518 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9519 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9520 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9521 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9522 "--"
9523 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9524 ("Rectangle"
9525 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9526 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9527 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9528 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9529 "--"
9530 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9531 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9532 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9533 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9534 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9535 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9536 ["Sum Column/Rectangle" org-table-sum
9537 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9538 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9539 ["Debug Formulas"
9540 (setq org-table-formula-debug (not org-table-formula-debug))
9541 :style toggle :selected org-table-formula-debug]
9542 ))
9543 t)
9544
9545 (defun orgtbl-tab ()
9546 "Justification and field motion for `orgtbl-mode'."
9547 (interactive)
9548 (org-table-justify-field-maybe)
9549 (org-table-next-field))
9550
9551 (defun orgtbl-ret ()
9552 "Justification and field motion for `orgtbl-mode'."
9553 (interactive)
9554 (org-table-justify-field-maybe)
9555 (org-table-next-row))
9556
9557 (defun orgtbl-self-insert-command (N)
9558 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9559 If the cursor is in a table looking at whitespace, the whitespace is
9560 overwritten, and the table is not marked as requiring realignment."
9561 (interactive "p")
9562 (if (and (org-at-table-p)
9563 (or
9564 (and org-table-auto-blank-field
9565 (member last-command
9566 '(orgtbl-hijacker-command-100
9567 orgtbl-hijacker-command-101
9568 orgtbl-hijacker-command-102
9569 orgtbl-hijacker-command-103
9570 orgtbl-hijacker-command-104
9571 orgtbl-hijacker-command-105))
9572 (org-table-blank-field))
9573 t)
9574 (eq N 1)
9575 (looking-at "[^|\n]* +|"))
9576 (let (org-table-may-need-update)
9577 (goto-char (1- (match-end 0)))
9578 (delete-backward-char 1)
9579 (goto-char (match-beginning 0))
9580 (self-insert-command N))
9581 (setq org-table-may-need-update t)
9582 (let (orgtbl-mode)
9583 (call-interactively (key-binding (vector last-input-event))))))
9584
9585 (defun org-force-self-insert (N)
9586 "Needed to enforce self-insert under remapping."
9587 (interactive "p")
9588 (self-insert-command N))
9589
9590 (defun orgtbl-delete-backward-char (N)
9591 "Like `delete-backward-char', insert whitespace at field end in tables.
9592 When deleting backwards, in tables this function will insert whitespace in
9593 front of the next \"|\" separator, to keep the table aligned. The table will
9594 still be marked for re-alignment, because a narrow field may lead to a
9595 reduced column width."
9596 (interactive "p")
9597 (if (and (org-at-table-p)
9598 (eq N 1)
9599 (string-match "|" (buffer-substring (point-at-bol) (point)))
9600 (looking-at ".*?|"))
9601 (let ((pos (point)))
9602 (backward-delete-char N)
9603 (skip-chars-forward "^|")
9604 (insert " ")
9605 (goto-char (1- pos)))
9606 (delete-backward-char N)))
9607
9608 (defun orgtbl-delete-char (N)
9609 "Like `delete-char', but insert whitespace at field end in tables.
9610 When deleting characters, in tables this function will insert whitespace in
9611 front of the next \"|\" separator, to keep the table aligned. The table
9612 will still be marked for re-alignment, because a narrow field may lead to
9613 a reduced column width."
9614 (interactive "p")
9615 (if (and (org-at-table-p)
9616 (not (bolp))
9617 (not (= (char-after) ?|))
9618 (eq N 1))
9619 (if (looking-at ".*?|")
9620 (let ((pos (point)))
9621 (replace-match (concat
9622 (substring (match-string 0) 1 -1)
9623 " |"))
9624 (goto-char pos)))
9625 (delete-char N)))
9626
9627 ;;; Exporting
9628
9629 (defconst org-level-max 20)
9630
9631 (defun org-export-find-first-heading-line (list)
9632 "Remove all lines from LIST which are before the first headline."
9633 (let ((orig-list list)
9634 (re (concat "^" outline-regexp)))
9635 (while (and list
9636 (not (string-match re (car list))))
9637 (pop list))
9638 (or list orig-list)))
9639
9640 (defun org-skip-comments (lines)
9641 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9642 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9643 (re2 "^\\(\\*+\\)[ \t\n\r]")
9644 rtn line level)
9645 (while (setq line (pop lines))
9646 (cond
9647 ((and (string-match re1 line)
9648 (setq level (- (match-end 1) (match-beginning 1))))
9649 ;; Beginning of a COMMENT subtree. Skip it.
9650 (while (and (setq line (pop lines))
9651 (or (not (string-match re2 line))
9652 (> (- (match-end 1) (match-beginning 1)) level))))
9653 (setq lines (cons line lines)))
9654 ((string-match "^#" line)
9655 ;; an ordinary comment line
9656 )
9657 (t (setq rtn (cons line rtn)))))
9658 (nreverse rtn)))
9659
9660 ;; ASCII
9661
9662 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9663 "Characters for underlining headings in ASCII export.")
9664
9665 (defconst org-html-entities
9666 '(("nbsp")
9667 ("iexcl")
9668 ("cent")
9669 ("pound")
9670 ("curren")
9671 ("yen")
9672 ("brvbar")
9673 ("sect")
9674 ("uml")
9675 ("copy")
9676 ("ordf")
9677 ("laquo")
9678 ("not")
9679 ("shy")
9680 ("reg")
9681 ("macr")
9682 ("deg")
9683 ("plusmn")
9684 ("sup2")
9685 ("sup3")
9686 ("acute")
9687 ("micro")
9688 ("para")
9689 ("middot")
9690 ("odot"."o")
9691 ("star"."*")
9692 ("cedil")
9693 ("sup1")
9694 ("ordm")
9695 ("raquo")
9696 ("frac14")
9697 ("frac12")
9698 ("frac34")
9699 ("iquest")
9700 ("Agrave")
9701 ("Aacute")
9702 ("Acirc")
9703 ("Atilde")
9704 ("Auml")
9705 ("Aring") ("AA"."&Aring;")
9706 ("AElig")
9707 ("Ccedil")
9708 ("Egrave")
9709 ("Eacute")
9710 ("Ecirc")
9711 ("Euml")
9712 ("Igrave")
9713 ("Iacute")
9714 ("Icirc")
9715 ("Iuml")
9716 ("ETH")
9717 ("Ntilde")
9718 ("Ograve")
9719 ("Oacute")
9720 ("Ocirc")
9721 ("Otilde")
9722 ("Ouml")
9723 ("times")
9724 ("Oslash")
9725 ("Ugrave")
9726 ("Uacute")
9727 ("Ucirc")
9728 ("Uuml")
9729 ("Yacute")
9730 ("THORN")
9731 ("szlig")
9732 ("agrave")
9733 ("aacute")
9734 ("acirc")
9735 ("atilde")
9736 ("auml")
9737 ("aring")
9738 ("aelig")
9739 ("ccedil")
9740 ("egrave")
9741 ("eacute")
9742 ("ecirc")
9743 ("euml")
9744 ("igrave")
9745 ("iacute")
9746 ("icirc")
9747 ("iuml")
9748 ("eth")
9749 ("ntilde")
9750 ("ograve")
9751 ("oacute")
9752 ("ocirc")
9753 ("otilde")
9754 ("ouml")
9755 ("divide")
9756 ("oslash")
9757 ("ugrave")
9758 ("uacute")
9759 ("ucirc")
9760 ("uuml")
9761 ("yacute")
9762 ("thorn")
9763 ("yuml")
9764 ("fnof")
9765 ("Alpha")
9766 ("Beta")
9767 ("Gamma")
9768 ("Delta")
9769 ("Epsilon")
9770 ("Zeta")
9771 ("Eta")
9772 ("Theta")
9773 ("Iota")
9774 ("Kappa")
9775 ("Lambda")
9776 ("Mu")
9777 ("Nu")
9778 ("Xi")
9779 ("Omicron")
9780 ("Pi")
9781 ("Rho")
9782 ("Sigma")
9783 ("Tau")
9784 ("Upsilon")
9785 ("Phi")
9786 ("Chi")
9787 ("Psi")
9788 ("Omega")
9789 ("alpha")
9790 ("beta")
9791 ("gamma")
9792 ("delta")
9793 ("epsilon")
9794 ("varepsilon"."&epsilon;")
9795 ("zeta")
9796 ("eta")
9797 ("theta")
9798 ("iota")
9799 ("kappa")
9800 ("lambda")
9801 ("mu")
9802 ("nu")
9803 ("xi")
9804 ("omicron")
9805 ("pi")
9806 ("rho")
9807 ("sigmaf") ("varsigma"."&sigmaf;")
9808 ("sigma")
9809 ("tau")
9810 ("upsilon")
9811 ("phi")
9812 ("chi")
9813 ("psi")
9814 ("omega")
9815 ("thetasym") ("vartheta"."&thetasym;")
9816 ("upsih")
9817 ("piv")
9818 ("bull") ("bullet"."&bull;")
9819 ("hellip") ("dots"."&hellip;")
9820 ("prime")
9821 ("Prime")
9822 ("oline")
9823 ("frasl")
9824 ("weierp")
9825 ("image")
9826 ("real")
9827 ("trade")
9828 ("alefsym")
9829 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
9830 ("uarr") ("uparrow"."&uarr;")
9831 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
9832 ("darr")("downarrow"."&darr;")
9833 ("harr") ("leftrightarrow"."&harr;")
9834 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
9835 ("lArr") ("Leftarrow"."&lArr;")
9836 ("uArr") ("Uparrow"."&uArr;")
9837 ("rArr") ("Rightarrow"."&rArr;")
9838 ("dArr") ("Downarrow"."&dArr;")
9839 ("hArr") ("Leftrightarrow"."&hArr;")
9840 ("forall")
9841 ("part") ("partial"."&part;")
9842 ("exist") ("exists"."&exist;")
9843 ("empty") ("emptyset"."&empty;")
9844 ("nabla")
9845 ("isin") ("in"."&isin;")
9846 ("notin")
9847 ("ni")
9848 ("prod")
9849 ("sum")
9850 ("minus")
9851 ("lowast") ("ast"."&lowast;")
9852 ("radic")
9853 ("prop") ("proptp"."&prop;")
9854 ("infin") ("infty"."&infin;")
9855 ("ang") ("angle"."&ang;")
9856 ("and") ("vee"."&and;")
9857 ("or") ("wedge"."&or;")
9858 ("cap")
9859 ("cup")
9860 ("int")
9861 ("there4")
9862 ("sim")
9863 ("cong") ("simeq"."&cong;")
9864 ("asymp")("approx"."&asymp;")
9865 ("ne") ("neq"."&ne;")
9866 ("equiv")
9867 ("le")
9868 ("ge")
9869 ("sub") ("subset"."&sub;")
9870 ("sup") ("supset"."&sup;")
9871 ("nsub")
9872 ("sube")
9873 ("supe")
9874 ("oplus")
9875 ("otimes")
9876 ("perp")
9877 ("sdot") ("cdot"."&sdot;")
9878 ("lceil")
9879 ("rceil")
9880 ("lfloor")
9881 ("rfloor")
9882 ("lang")
9883 ("rang")
9884 ("loz") ("Diamond"."&loz;")
9885 ("spades") ("spadesuit"."&spades;")
9886 ("clubs") ("clubsuit"."&clubs;")
9887 ("hearts") ("diamondsuit"."&hearts;")
9888 ("diams") ("diamondsuit"."&diams;")
9889 ("quot")
9890 ("amp")
9891 ("lt")
9892 ("gt")
9893 ("OElig")
9894 ("oelig")
9895 ("Scaron")
9896 ("scaron")
9897 ("Yuml")
9898 ("circ")
9899 ("tilde")
9900 ("ensp")
9901 ("emsp")
9902 ("thinsp")
9903 ("zwnj")
9904 ("zwj")
9905 ("lrm")
9906 ("rlm")
9907 ("ndash")
9908 ("mdash")
9909 ("lsquo")
9910 ("rsquo")
9911 ("sbquo")
9912 ("ldquo")
9913 ("rdquo")
9914 ("bdquo")
9915 ("dagger")
9916 ("Dagger")
9917 ("permil")
9918 ("lsaquo")
9919 ("rsaquo")
9920 ("euro")
9921
9922 ("arccos"."arccos")
9923 ("arcsin"."arcsin")
9924 ("arctan"."arctan")
9925 ("arg"."arg")
9926 ("cos"."cos")
9927 ("cosh"."cosh")
9928 ("cot"."cot")
9929 ("coth"."coth")
9930 ("csc"."csc")
9931 ("deg"."deg")
9932 ("det"."det")
9933 ("dim"."dim")
9934 ("exp"."exp")
9935 ("gcd"."gcd")
9936 ("hom"."hom")
9937 ("inf"."inf")
9938 ("ker"."ker")
9939 ("lg"."lg")
9940 ("lim"."lim")
9941 ("liminf"."liminf")
9942 ("limsup"."limsup")
9943 ("ln"."ln")
9944 ("log"."log")
9945 ("max"."max")
9946 ("min"."min")
9947 ("Pr"."Pr")
9948 ("sec"."sec")
9949 ("sin"."sin")
9950 ("sinh"."sinh")
9951 ("sup"."sup")
9952 ("tan"."tan")
9953 ("tanh"."tanh")
9954 )
9955 "Entities for TeX->HTML translation.
9956 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9957 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9958 In that case, \"\\ent\" will be translated to \"&other;\".
9959 The list contains HTML entities for Latin-1, Greek and other symbols.
9960 It is supplemented by a number of commonly used TeX macros with appropriate
9961 translations. There is currently no way for users to extend this.")
9962
9963 (defvar org-last-level nil) ; dynamically scoped variable
9964
9965 (defun org-export-as-ascii (arg)
9966 "Export the outline as a pretty ASCII file.
9967 If there is an active region, export only the region.
9968 The prefix ARG specifies how many levels of the outline should become
9969 underlined headlines. The default is 3."
9970 (interactive "P")
9971 (setq-default org-todo-line-regexp org-todo-line-regexp)
9972 (let* ((region
9973 (buffer-substring
9974 (if (org-region-active-p) (region-beginning) (point-min))
9975 (if (org-region-active-p) (region-end) (point-max))))
9976 (lines (org-export-find-first-heading-line
9977 (org-skip-comments (org-split-string region "[\r\n]"))))
9978 (org-startup-with-deadline-check nil)
9979 (level 0) line txt
9980 (umax nil)
9981 (case-fold-search nil)
9982 (filename (concat (file-name-sans-extension (buffer-file-name))
9983 ".txt"))
9984 (buffer (find-file-noselect filename))
9985 (levels-open (make-vector org-level-max nil))
9986 (date (format-time-string "%Y/%m/%d" (current-time)))
9987 (time (format-time-string "%X" (current-time)))
9988 (author user-full-name)
9989 (title (buffer-name))
9990 (options nil)
9991 (email user-mail-address)
9992 (language org-export-default-language)
9993 (text nil)
9994 (todo nil)
9995 (lang-words nil))
9996
9997 (setq org-last-level 1)
9998 (org-init-section-numbers)
9999
10000 (find-file-noselect filename)
10001
10002 ;; Search for the export key lines
10003 (org-parse-key-lines)
10004
10005 (setq lang-words (or (assoc language org-export-language-setup)
10006 (assoc "en" org-export-language-setup)))
10007 (if org-export-ascii-show-new-buffer
10008 (switch-to-buffer-other-window buffer)
10009 (set-buffer buffer))
10010 (erase-buffer)
10011 (fundamental-mode)
10012 (if options (org-parse-export-options options))
10013 (setq umax (if arg (prefix-numeric-value arg)
10014 org-export-headline-levels))
10015
10016 ;; File header
10017 (if title (org-insert-centered title ?=))
10018 (insert "\n")
10019 (if (or author email)
10020 (insert (concat (nth 1 lang-words) ": " (or author "")
10021 (if email (concat " <" email ">") "")
10022 "\n")))
10023 (if (and date time)
10024 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10025 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10026
10027 (insert "\n\n")
10028
10029 (if org-export-with-toc
10030 (progn
10031 (insert (nth 3 lang-words) "\n"
10032 (make-string (length (nth 3 lang-words)) ?=) "\n")
10033 (mapcar '(lambda (line)
10034 (if (string-match org-todo-line-regexp
10035 line)
10036 ;; This is a headline
10037 (progn
10038 (setq level (- (match-end 1) (match-beginning 1))
10039 txt (match-string 3 line)
10040 todo
10041 (or (and (match-beginning 2)
10042 (not (equal (match-string 2 line)
10043 org-done-string)))
10044 ; TODO, not DONE
10045 (and (= level umax)
10046 (org-search-todo-below
10047 line lines level))))
10048 (setq txt (org-html-expand-for-ascii txt))
10049
10050 (if org-export-with-section-numbers
10051 (setq txt (concat (org-section-number level)
10052 " " txt)))
10053 (if (<= level umax)
10054 (progn
10055 (insert
10056 (make-string (* (1- level) 4) ?\ )
10057 (format (if todo "%s (*)\n" "%s\n") txt))
10058 (setq org-last-level level))
10059 ))))
10060 lines)))
10061
10062 (org-init-section-numbers)
10063 (while (setq line (pop lines))
10064 ;; Remove the quoted HTML tags.
10065 (setq line (org-html-expand-for-ascii line))
10066 (cond
10067 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10068 ;; a Headline
10069 (setq level (- (match-end 1) (match-beginning 1))
10070 txt (match-string 2 line))
10071 (org-ascii-level-start level txt umax))
10072 (t (insert line "\n"))))
10073 (normal-mode)
10074 (save-buffer)
10075 (goto-char (point-min))))
10076
10077 (defun org-search-todo-below (line lines level)
10078 "Search the subtree below LINE for any TODO entries."
10079 (let ((rest (cdr (memq line lines)))
10080 (re org-todo-line-regexp)
10081 line lv todo)
10082 (catch 'exit
10083 (while (setq line (pop rest))
10084 (if (string-match re line)
10085 (progn
10086 (setq lv (- (match-end 1) (match-beginning 1))
10087 todo (and (match-beginning 2)
10088 (not (equal (match-string 2 line)
10089 org-done-string))))
10090 ; TODO, not DONE
10091 (if (<= lv level) (throw 'exit nil))
10092 (if todo (throw 'exit t))))))))
10093
10094 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10095 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10096 (defun org-html-expand-for-ascii (line)
10097 "Handle quoted HTML for ASCII export."
10098 (if org-export-html-expand
10099 (while (string-match "@<[^<>\n]*>" line)
10100 ;; We just remove the tags for now.
10101 (setq line (replace-match "" nil nil line))))
10102 line)
10103
10104 (defun org-insert-centered (s &optional underline)
10105 "Insert the string S centered and underline it with character UNDERLINE."
10106 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10107 (insert (make-string ind ?\ ) s "\n")
10108 (if underline
10109 (insert (make-string ind ?\ )
10110 (make-string (length s) underline)
10111 "\n"))))
10112
10113 (defun org-ascii-level-start (level title umax)
10114 "Insert a new level in ASCII export."
10115 (let (char)
10116 (if (> level umax)
10117 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10118 (if (or (not (equal (char-before) ?\n))
10119 (not (equal (char-before (1- (point))) ?\n)))
10120 (insert "\n"))
10121 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10122 (if org-export-with-section-numbers
10123 (setq title (concat (org-section-number level) " " title)))
10124 (insert title "\n" (make-string (string-width title) char) "\n"))))
10125
10126 (defun org-export-copy-visible ()
10127 "Copy the visible part of the buffer to another buffer, for printing.
10128 Also removes the first line of the buffer if it specifies a mode,
10129 and all options lines."
10130 (interactive)
10131 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10132 ".txt"))
10133 (buffer (find-file-noselect filename))
10134 (ore (concat
10135 (org-make-options-regexp
10136 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10137 "STARTUP" "ARCHIVE"
10138 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10139 (if org-noutline-p "\\(\n\\|$\\)" "")))
10140 s e)
10141 (with-current-buffer buffer
10142 (erase-buffer)
10143 (text-mode))
10144 (save-excursion
10145 (setq s (goto-char (point-min)))
10146 (while (not (= (point) (point-max)))
10147 (goto-char (org-find-invisible))
10148 (append-to-buffer buffer s (point))
10149 (setq s (goto-char (org-find-visible)))))
10150 (switch-to-buffer-other-window buffer)
10151 (newline)
10152 (goto-char (point-min))
10153 (if (looking-at ".*-\\*- mode:.*\n")
10154 (replace-match ""))
10155 (while (re-search-forward ore nil t)
10156 (replace-match ""))
10157 (goto-char (point-min))))
10158
10159 (defun org-find-visible ()
10160 (if (featurep 'noutline)
10161 (let ((s (point)))
10162 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10163 (get-char-property s 'invisible)))
10164 s)
10165 (skip-chars-forward "^\n")
10166 (point)))
10167 (defun org-find-invisible ()
10168 (if (featurep 'noutline)
10169 (let ((s (point)))
10170 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10171 (not (get-char-property s 'invisible))))
10172 s)
10173 (skip-chars-forward "^\r")
10174 (point)))
10175
10176 ;; HTML
10177
10178 (defun org-get-current-options ()
10179 "Return a string with current options as keyword options.
10180 Does include HTML export options as well as TODO and CATEGORY stuff."
10181 (format
10182 "#+TITLE: %s
10183 #+AUTHOR: %s
10184 #+EMAIL: %s
10185 #+LANGUAGE: %s
10186 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10187 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10188 #+CATEGORY: %s
10189 #+SEQ_TODO: %s
10190 #+TYP_TODO: %s
10191 #+STARTUP: %s %s
10192 #+ARCHIVE: %s
10193 "
10194 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10195 org-export-headline-levels
10196 org-export-with-section-numbers
10197 org-export-with-toc
10198 org-export-preserve-breaks
10199 org-export-html-expand
10200 org-export-with-fixed-width
10201 org-export-with-tables
10202 org-export-with-sub-superscripts
10203 org-export-with-emphasize
10204 org-export-with-TeX-macros
10205 (file-name-nondirectory (buffer-file-name))
10206 (if (equal org-todo-interpretation 'sequence)
10207 (mapconcat 'identity org-todo-keywords " ")
10208 "TODO FEEDBACK VERIFY DONE")
10209 (if (equal org-todo-interpretation 'type)
10210 (mapconcat 'identity org-todo-keywords " ")
10211 "Me Jason Marie DONE")
10212 (cdr (assoc org-startup-folded
10213 '((nil . "nofold")(t . "fold")(content . "content"))))
10214 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10215 org-archive-location
10216 ))
10217
10218 (defun org-insert-export-options-template ()
10219 "Insert into the buffer a template with information for exporting."
10220 (interactive)
10221 (if (not (bolp)) (newline))
10222 (let ((s (org-get-current-options)))
10223 (and (string-match "#\\+CATEGORY" s)
10224 (setq s (substring s 0 (match-beginning 0))))
10225 (insert s)))
10226
10227 (defun org-toggle-fixed-width-section (arg)
10228 "Toggle the fixed-width export.
10229 If there is no active region, the QUOTE keyword at the current headline is
10230 inserted or removed. When present, it causes the text between this headline
10231 and the next to be exported as fixed-width text, and unmodified.
10232 If there is an active region, this command adds or removes a colon as the
10233 first character of this line. If the first character of a line is a colon,
10234 this line is also exported in fixed-width font."
10235 (interactive "P")
10236 (let* ((cc 0)
10237 (regionp (org-region-active-p))
10238 (beg (if regionp (region-beginning) (point)))
10239 (end (if regionp (region-end)))
10240 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10241 (re "[ \t]*\\(:\\)")
10242 off)
10243 (if regionp
10244 (save-excursion
10245 (goto-char beg)
10246 (setq cc (current-column))
10247 (beginning-of-line 1)
10248 (setq off (looking-at re))
10249 (while (> nlines 0)
10250 (setq nlines (1- nlines))
10251 (beginning-of-line 1)
10252 (cond
10253 (arg
10254 (move-to-column cc t)
10255 (insert ":\n")
10256 (forward-line -1))
10257 ((and off (looking-at re))
10258 (replace-match "" t t nil 1))
10259 ((not off) (move-to-column cc t) (insert ":")))
10260 (forward-line 1)))
10261 (save-excursion
10262 (org-back-to-heading)
10263 (if (looking-at (concat outline-regexp
10264 "\\( +\\<" org-quote-string "\\>\\)"))
10265 (replace-match "" t t nil 1)
10266 (if (looking-at outline-regexp)
10267 (progn
10268 (goto-char (match-end 0))
10269 (insert " " org-quote-string))))))))
10270
10271 (defun org-export-as-html-and-open (arg)
10272 "Export the outline as HTML and immediately open it with a browser.
10273 If there is an active region, export only the region.
10274 The prefix ARG specifies how many levels of the outline should become
10275 headlines. The default is 3. Lower levels will become bulleted lists."
10276 (interactive "P")
10277 (org-export-as-html arg 'hidden)
10278 (org-open-file (buffer-file-name)))
10279
10280 (defun org-export-as-html-batch ()
10281 "Call `org-export-as-html', may be used in batch processing as
10282 emacs --batch
10283 --load=$HOME/lib/emacs/org.el
10284 --eval \"(setq org-export-headline-levels 2)\"
10285 --visit=MyFile --funcall org-export-as-html-batch"
10286 (org-export-as-html org-export-headline-levels 'hidden))
10287
10288 (defun org-export-as-html (arg &optional hidden)
10289 "Export the outline as a pretty HTML file.
10290 If there is an active region, export only the region.
10291 The prefix ARG specifies how many levels of the outline should become
10292 headlines. The default is 3. Lower levels will become bulleted lists."
10293 (interactive "P")
10294 (setq-default org-todo-line-regexp org-todo-line-regexp)
10295 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10296 (setq-default org-done-string org-done-string)
10297 (let* ((style org-export-html-style)
10298 (region-p (org-region-active-p))
10299 (region
10300 (buffer-substring
10301 (if region-p (region-beginning) (point-min))
10302 (if region-p (region-end) (point-max))))
10303 (all_lines
10304 (org-skip-comments (org-split-string region "[\r\n]")))
10305 (lines (org-export-find-first-heading-line all_lines))
10306 (level 0) (line "") (origline "") txt todo
10307 (umax nil)
10308 (filename (concat (file-name-sans-extension (buffer-file-name))
10309 ".html"))
10310 (buffer (find-file-noselect filename))
10311 (levels-open (make-vector org-level-max nil))
10312 (date (format-time-string "%Y/%m/%d" (current-time)))
10313 (time (format-time-string "%X" (current-time)))
10314 (author user-full-name)
10315 (title (buffer-name))
10316 (options nil)
10317 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10318 (inquote nil)
10319 (infixed nil)
10320 (in-local-list nil)
10321 (local-list-num nil)
10322 (local-list-indent nil)
10323 (llt org-plain-list-ordered-item-terminator)
10324 (email user-mail-address)
10325 (language org-export-default-language)
10326 (text nil)
10327 (lang-words nil)
10328 (head-count 0) cnt
10329 (start 0)
10330 ;; FIXME: The following returns always nil under XEmacs
10331 (coding-system (and (fboundp 'coding-system-get)
10332 (boundp 'buffer-file-coding-system)
10333 buffer-file-coding-system))
10334 (coding-system-for-write (or coding-system coding-system-for-write))
10335 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10336 (charset (and coding-system
10337 (coding-system-get coding-system 'mime-charset)))
10338 table-open type
10339 table-buffer table-orig-buffer
10340 ind start-is-num starter
10341 )
10342 (message "Exporting...")
10343
10344 (setq org-last-level 1)
10345 (org-init-section-numbers)
10346
10347 ;; Search for the export key lines
10348 (org-parse-key-lines)
10349 (setq lang-words (or (assoc language org-export-language-setup)
10350 (assoc "en" org-export-language-setup)))
10351
10352 ;; Switch to the output buffer
10353 (if (or hidden (not org-export-html-show-new-buffer))
10354 (set-buffer buffer)
10355 (switch-to-buffer-other-window buffer))
10356 (erase-buffer)
10357 (fundamental-mode)
10358 (let ((case-fold-search nil))
10359 (if options (org-parse-export-options options))
10360 (setq umax (if arg (prefix-numeric-value arg)
10361 org-export-headline-levels))
10362
10363 ;; File header
10364 (insert (format
10365 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10366 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10367 <html lang=\"%s\"><head>
10368 <title>%s</title>
10369 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10370 <meta name=generator content=\"Org-mode\">
10371 <meta name=generated content=\"%s %s\">
10372 <meta name=author content=\"%s\">
10373 %s
10374 </head><body>
10375 "
10376 language (org-html-expand title) (or charset "iso-8859-1")
10377 date time author style))
10378 (if title (insert (concat "<H1 class=\"title\">"
10379 (org-html-expand title) "</H1>\n")))
10380 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10381 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
10382 email "&gt;</a>\n")))
10383 (if (or author email) (insert "<br>\n"))
10384 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10385 date " " time "<br>\n")))
10386 (if text (insert (concat "<p>\n" (org-html-expand text))))
10387 (if org-export-with-toc
10388 (progn
10389 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10390 (insert "<ul>\n")
10391 (mapcar '(lambda (line)
10392 (if (string-match org-todo-line-regexp line)
10393 ;; This is a headline
10394 (progn
10395 (setq level (- (match-end 1) (match-beginning 1))
10396 txt (save-match-data
10397 (org-html-expand
10398 (match-string 3 line)))
10399 todo
10400 (or (and (match-beginning 2)
10401 (not (equal (match-string 2 line)
10402 org-done-string)))
10403 ; TODO, not DONE
10404 (and (= level umax)
10405 (org-search-todo-below
10406 line lines level))))
10407 (if org-export-with-section-numbers
10408 (setq txt (concat (org-section-number level)
10409 " " txt)))
10410 (if (<= level umax)
10411 (progn
10412 (setq head-count (+ head-count 1))
10413 (if (> level org-last-level)
10414 (progn
10415 (setq cnt (- level org-last-level))
10416 (while (>= (setq cnt (1- cnt)) 0)
10417 (insert "<ul>"))
10418 (insert "\n")))
10419 (if (< level org-last-level)
10420 (progn
10421 (setq cnt (- org-last-level level))
10422 (while (>= (setq cnt (1- cnt)) 0)
10423 (insert "</ul>"))
10424 (insert "\n")))
10425 (insert
10426 (format
10427 (if todo
10428 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10429 "<li><a href=\"#sec-%d\">%s</a>\n")
10430 head-count txt))
10431 (setq org-last-level level))
10432 ))))
10433 lines)
10434 (while (> org-last-level 0)
10435 (setq org-last-level (1- org-last-level))
10436 (insert "</ul>\n"))
10437 ))
10438 (setq head-count 0)
10439 (org-init-section-numbers)
10440
10441 (while (setq line (pop lines) origline line)
10442 (catch 'nextline
10443
10444 ;; end of quote section?
10445 (when (and inquote (string-match "^\\*+" line))
10446 (insert "</pre>\n")
10447 (setq inquote nil))
10448 ;; inside a quote section?
10449 (when inquote
10450 (insert (org-html-protect line) "\n")
10451 (throw 'nextline nil))
10452
10453 ;; verbatim lines
10454 (when (and org-export-with-fixed-width
10455 (string-match "^[ \t]*:\\(.*\\)" line))
10456 (when (not infixed)
10457 (setq infixed t)
10458 (insert "<pre>\n"))
10459 (insert (org-html-protect (match-string 1 line)) "\n")
10460 (when (and lines
10461 (not (string-match "^[ \t]*\\(:.*\\)"
10462 (car lines))))
10463 (setq infixed nil)
10464 (insert "</pre>\n"))
10465 (throw 'nextline nil))
10466
10467 ;; Protect the links
10468 (setq start 0)
10469 (while (string-match org-link-maybe-angles-regexp line start)
10470 (setq start (match-end 0))
10471 (setq line (replace-match
10472 (concat "\000" (match-string 1 line) "\000")
10473 t t line)))
10474
10475 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
10476 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
10477 (setq line (org-html-expand line))
10478
10479 ;; Format the links
10480 (setq start 0)
10481 (while (string-match org-protected-link-regexp line start)
10482 (setq start (- (match-end 0) 2))
10483 (setq type (match-string 1 line))
10484 (cond
10485 ((member type '("http" "https" "ftp" "mailto" "news"))
10486 ;; standard URL
10487 (setq line (replace-match
10488 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
10489 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10490 nil nil line)))
10491 ((string= type "file")
10492 ;; FILE link
10493 (let* ((filename (match-string 2 line))
10494 (abs-p (file-name-absolute-p filename))
10495 (thefile (if abs-p (expand-file-name filename) filename))
10496 (thefile (save-match-data
10497 (if (string-match ":[0-9]+$" thefile)
10498 (replace-match "" t t thefile)
10499 thefile)))
10500 (file-is-image-p
10501 (save-match-data
10502 (string-match (org-image-file-name-regexp) thefile))))
10503 (setq line (replace-match
10504 (if (and org-export-html-inline-images
10505 file-is-image-p)
10506 (concat "<img src=\"" thefile "\"/>")
10507 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10508 nil nil line))))
10509
10510 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10511 (setq line (replace-match
10512 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
10513
10514 ;; TODO items
10515 (if (and (string-match org-todo-line-regexp line)
10516 (match-beginning 2))
10517 (if (equal (match-string 2 line) org-done-string)
10518 (setq line (replace-match
10519 "<span class=\"done\">\\2</span>"
10520 nil nil line 2))
10521 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10522 nil nil line 2))))
10523
10524 ;; DEADLINES
10525 (if (string-match org-deadline-line-regexp line)
10526 (progn
10527 (if (save-match-data
10528 (string-match "<a href"
10529 (substring line 0 (match-beginning 0))))
10530 nil ; Don't do the replacement - it is inside a link
10531 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10532 nil nil line 1)))))
10533 (cond
10534 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10535 ;; This is a headline
10536 (setq level (- (match-end 1) (match-beginning 1))
10537 txt (match-string 2 line))
10538 (if (<= level umax) (setq head-count (+ head-count 1)))
10539 (when in-local-list
10540 ;; Close any local lists before inserting a new header line
10541 (while local-list-num
10542 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10543 (pop local-list-num))
10544 (setq local-list-indent nil
10545 in-local-list nil))
10546 (org-html-level-start level txt umax
10547 (and org-export-with-toc (<= level umax))
10548 head-count)
10549 ;; QUOTES
10550 (when (string-match quote-re line)
10551 (insert "<pre>")
10552 (setq inquote t)))
10553
10554 ((and org-export-with-tables
10555 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10556 (if (not table-open)
10557 ;; New table starts
10558 (setq table-open t table-buffer nil table-orig-buffer nil))
10559 ;; Accumulate lines
10560 (setq table-buffer (cons line table-buffer)
10561 table-orig-buffer (cons origline table-orig-buffer))
10562 (when (or (not lines)
10563 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10564 (car lines))))
10565 (setq table-open nil
10566 table-buffer (nreverse table-buffer)
10567 table-orig-buffer (nreverse table-orig-buffer))
10568 (insert (org-format-table-html table-buffer table-orig-buffer))))
10569 (t
10570 ;; Normal lines
10571 (when (and (> org-export-plain-list-max-depth 0)
10572 (string-match
10573 (cond
10574 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10575 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10576 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10577 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10578 line))
10579 (setq ind (org-get-string-indentation line)
10580 start-is-num (match-beginning 4)
10581 starter (if (match-beginning 2) (match-string 2 line))
10582 line (substring line (match-beginning 5)))
10583 (unless (string-match "[^ \t]" line)
10584 ;; empty line. Pretend indentation is large.
10585 (setq ind (1+ (or (car local-list-indent) 1))))
10586 (while (and in-local-list
10587 (or (and (= ind (car local-list-indent))
10588 (not starter))
10589 (< ind (car local-list-indent))))
10590 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10591 (pop local-list-num) (pop local-list-indent)
10592 (setq in-local-list local-list-indent))
10593 (cond
10594 ((and starter
10595 (or (not in-local-list)
10596 (> ind (car local-list-indent)))
10597 (< (length local-list-indent)
10598 org-export-plain-list-max-depth))
10599 ;; Start new (level of ) list
10600 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10601 (push start-is-num local-list-num)
10602 (push ind local-list-indent)
10603 (setq in-local-list t))
10604 (starter
10605 ;; continue current list
10606 (insert "<li>\n"))))
10607 ;; Empty lines start a new paragraph. If hand-formatted lists
10608 ;; are not fully interpreted, lines starting with "-", "+", "*"
10609 ;; also start a new paragraph.
10610 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10611 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10612 ))
10613 (if org-export-html-with-timestamp
10614 (insert org-export-html-html-helper-timestamp))
10615 (insert "</body>\n</html>\n")
10616 (normal-mode)
10617 (save-buffer)
10618 (goto-char (point-min)))))
10619
10620 (defun org-format-table-html (lines olines)
10621 "Find out which HTML converter to use and return the HTML code."
10622 (if (string-match "^[ \t]*|" (car lines))
10623 ;; A normal org table
10624 (org-format-org-table-html lines)
10625 ;; Table made by table.el - test for spanning
10626 (let* ((hlines (delq nil (mapcar
10627 (lambda (x)
10628 (if (string-match "^[ \t]*\\+-" x) x
10629 nil))
10630 lines)))
10631 (first (car hlines))
10632 (ll (and (string-match "\\S-+" first)
10633 (match-string 0 first)))
10634 (re (concat "^[ \t]*" (regexp-quote ll)))
10635 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10636 hlines))))
10637 (if (and (not spanning)
10638 (not org-export-prefer-native-exporter-for-tables))
10639 ;; We can use my own converter with HTML conversions
10640 (org-format-table-table-html lines)
10641 ;; Need to use the code generator in table.el, with the original text.
10642 (org-format-table-table-html-using-table-generate-source olines)))))
10643
10644 (defun org-format-org-table-html (lines)
10645 "Format a table into html."
10646 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10647 (setq lines (nreverse lines))
10648 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10649 (setq lines (nreverse lines))
10650 (let ((head (and org-export-highlight-first-table-line
10651 (delq nil (mapcar
10652 (lambda (x) (string-match "^[ \t]*|-" x))
10653 (cdr lines)))))
10654 line fields html)
10655 (setq html (concat org-export-html-table-tag "\n"))
10656 (while (setq line (pop lines))
10657 (catch 'next-line
10658 (if (string-match "^[ \t]*|-" line)
10659 (progn
10660 (setq head nil) ;; head ends here, first time around
10661 ;; ignore this line
10662 (throw 'next-line t)))
10663 ;; Break the line into fields
10664 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10665 (setq html (concat
10666 html
10667 "<tr>"
10668 (mapconcat (lambda (x)
10669 (if head
10670 (concat "<th>" x "</th>")
10671 (concat "<td>" x "</td>")))
10672 fields "")
10673 "</tr>\n"))))
10674 (setq html (concat html "</table>\n"))
10675 html))
10676
10677 (defun org-fake-empty-table-line (line)
10678 "Replace everything except \"|\" with spaces."
10679 (let ((i (length line))
10680 (newstr (copy-sequence line)))
10681 (while (> i 0)
10682 (setq i (1- i))
10683 (if (not (eq (aref newstr i) ?|))
10684 (aset newstr i ?\ )))
10685 newstr))
10686
10687 (defun org-format-table-table-html (lines)
10688 "Format a table generated by table.el into html.
10689 This conversion does *not* use `table-generate-source' from table.el.
10690 This has the advantage that Org-mode's HTML conversions can be used.
10691 But it has the disadvantage, that no cell- or row-spanning is allowed."
10692 (let (line field-buffer
10693 (head org-export-highlight-first-table-line)
10694 fields html empty)
10695 (setq html (concat org-export-html-table-tag "\n"))
10696 (while (setq line (pop lines))
10697 (setq empty "&nbsp")
10698 (catch 'next-line
10699 (if (string-match "^[ \t]*\\+-" line)
10700 (progn
10701 (if field-buffer
10702 (progn
10703 (setq html (concat
10704 html
10705 "<tr>"
10706 (mapconcat
10707 (lambda (x)
10708 (if (equal x "") (setq x empty))
10709 (if head
10710 (concat "<th>" x "</th>\n")
10711 (concat "<td>" x "</td>\n")))
10712 field-buffer "\n")
10713 "</tr>\n"))
10714 (setq head nil)
10715 (setq field-buffer nil)))
10716 ;; Ignore this line
10717 (throw 'next-line t)))
10718 ;; Break the line into fields and store the fields
10719 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10720 (if field-buffer
10721 (setq field-buffer (mapcar
10722 (lambda (x)
10723 (concat x "<br>" (pop fields)))
10724 field-buffer))
10725 (setq field-buffer fields))))
10726 (setq html (concat html "</table>\n"))
10727 html))
10728
10729 (defun org-format-table-table-html-using-table-generate-source (lines)
10730 "Format a table into html, using `table-generate-source' from table.el.
10731 This has the advantage that cell- or row-spanning is allowed.
10732 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10733 (require 'table)
10734 (with-current-buffer (get-buffer-create " org-tmp1 ")
10735 (erase-buffer)
10736 (insert (mapconcat 'identity lines "\n"))
10737 (goto-char (point-min))
10738 (if (not (re-search-forward "|[^+]" nil t))
10739 (error "Error processing table"))
10740 (table-recognize-table)
10741 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10742 (table-generate-source 'html " org-tmp2 ")
10743 (set-buffer " org-tmp2 ")
10744 (buffer-substring (point-min) (point-max))))
10745
10746 (defun org-html-protect (s)
10747 ;; convert & to &amp;, < to &lt; and > to &gt;
10748 (let ((start 0))
10749 (while (string-match "&" s start)
10750 (setq s (replace-match "&amp;" t t s)
10751 start (1+ (match-beginning 0))))
10752 (while (string-match "<" s)
10753 (setq s (replace-match "&lt;" t t s)))
10754 (while (string-match ">" s)
10755 (setq s (replace-match "&gt;" t t s))))
10756 s)
10757
10758 (defun org-html-expand (string)
10759 "Prepare STRING for HTML export. Applies all active conversions."
10760 ;; First check if there is a link in the line - if yes, apply conversions
10761 ;; only before the start of the link.
10762 ;; FIXME: This is no longer correct, because links now have an end.
10763 (let* ((m (string-match org-link-regexp string))
10764 (s (if m (substring string 0 m) string))
10765 (r (if m (substring string m) "")))
10766 ;; convert & to &amp;, < to &lt; and > to &gt;
10767 (setq s (org-html-protect s))
10768 (if org-export-html-expand
10769 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
10770 (setq s (replace-match "<\\1>" nil nil s))))
10771 (if org-export-with-emphasize
10772 (setq s (org-export-html-convert-emphasize s)))
10773 (if org-export-with-sub-superscripts
10774 (setq s (org-export-html-convert-sub-super s)))
10775 (if org-export-with-TeX-macros
10776 (let ((start 0) wd ass)
10777 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10778 (setq wd (match-string 1 s))
10779 (if (setq ass (assoc wd org-html-entities))
10780 (setq s (replace-match (or (cdr ass)
10781 (concat "&" (car ass) ";"))
10782 t t s))
10783 (setq start (+ start (length wd)))))))
10784 (concat s r)))
10785
10786 (defun org-create-multibrace-regexp (left right n)
10787 "Create a regular expression which will match a balanced sexp.
10788 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10789 as single character strings.
10790 The regexp returned will match the entire expression including the
10791 delimiters. It will also define a single group which contains the
10792 match except for the outermost delimiters. The maximum depth of
10793 stacked delimiters is N. Escaping delimiters is not possible."
10794 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10795 (or "\\|")
10796 (re nothing)
10797 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10798 (while (> n 1)
10799 (setq n (1- n)
10800 re (concat re or next)
10801 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10802 (concat left "\\(" re "\\)" right)))
10803
10804 (defvar org-match-substring-regexp
10805 (concat
10806 "\\([^\\]\\)\\([_^]\\)\\("
10807 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10808 "\\|"
10809 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10810 "\\|"
10811 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10812 "The regular expression matching a sub- or superscript.")
10813
10814 (defun org-export-html-convert-sub-super (string)
10815 "Convert sub- and superscripts in STRING to HTML."
10816 (let (key c)
10817 (while (string-match org-match-substring-regexp string)
10818 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10819 (setq c (or (match-string 8 string)
10820 (match-string 6 string)
10821 (match-string 5 string)))
10822 (setq string (replace-match
10823 (concat (match-string 1 string)
10824 "<" key ">" c "</" key ">")
10825 t t string)))
10826 (while (string-match "\\\\\\([_^]\\)" string)
10827 (setq string (replace-match (match-string 1 string) t t string))))
10828 string)
10829
10830 (defun org-export-html-convert-emphasize (string)
10831 (while (string-match
10832 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10833 string)
10834 (setq string (replace-match
10835 (concat "<b>" (match-string 3 string) "</b>")
10836 t t string 2)))
10837 (while (string-match
10838 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10839 string)
10840 (setq string (replace-match
10841 (concat "<i>" (match-string 3 string) "</i>")
10842 t t string 2)))
10843 (while (string-match
10844 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10845 string)
10846 (setq string (replace-match
10847 (concat "<u>" (match-string 3 string) "</u>")
10848 t t string 2)))
10849 string)
10850
10851 (defun org-parse-key-lines ()
10852 "Find the special key lines with the information for exporters."
10853 (save-excursion
10854 (goto-char 0)
10855 (let ((re (org-make-options-regexp
10856 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10857 key)
10858 (while (re-search-forward re nil t)
10859 (setq key (match-string 1))
10860 (cond ((string-equal key "TITLE")
10861 (setq title (match-string 2)))
10862 ((string-equal key "AUTHOR")
10863 (setq author (match-string 2)))
10864 ((string-equal key "EMAIL")
10865 (setq email (match-string 2)))
10866 ((string-equal key "LANGUAGE")
10867 (setq language (match-string 2)))
10868 ((string-equal key "TEXT")
10869 (setq text (concat text "\n" (match-string 2))))
10870 ((string-equal key "OPTIONS")
10871 (setq options (match-string 2))))))))
10872
10873 (defun org-parse-export-options (s)
10874 "Parse the export options line."
10875 (let ((op '(("H" . org-export-headline-levels)
10876 ("num" . org-export-with-section-numbers)
10877 ("toc" . org-export-with-toc)
10878 ("\\n" . org-export-preserve-breaks)
10879 ("@" . org-export-html-expand)
10880 (":" . org-export-with-fixed-width)
10881 ("|" . org-export-with-tables)
10882 ("^" . org-export-with-sub-superscripts)
10883 ("*" . org-export-with-emphasize)
10884 ("TeX" . org-export-with-TeX-macros)))
10885 o)
10886 (while (setq o (pop op))
10887 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10888 s)
10889 (set (make-local-variable (cdr o))
10890 (car (read-from-string (match-string 1 s))))))))
10891
10892 (defun org-html-level-start (level title umax with-toc head-count)
10893 "Insert a new level in HTML export."
10894 (let ((l (1+ (max level umax))))
10895 (while (<= l org-level-max)
10896 (if (aref levels-open (1- l))
10897 (progn
10898 (org-html-level-close l)
10899 (aset levels-open (1- l) nil)))
10900 (setq l (1+ l)))
10901 (if (> level umax)
10902 (progn
10903 (if (aref levels-open (1- level))
10904 (insert "<li>" title "<p>\n")
10905 (aset levels-open (1- level) t)
10906 (insert "<ul><li>" title "<p>\n")))
10907 (if org-export-with-section-numbers
10908 (setq title (concat (org-section-number level) " " title)))
10909 (setq level (+ level 1))
10910 (if with-toc
10911 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10912 level head-count title level))
10913 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10914
10915 (defun org-html-level-close (&rest args)
10916 "Terminate one level in HTML export."
10917 (insert "</ul>"))
10918
10919 ;; Variable holding the vector with section numbers
10920 (defvar org-section-numbers (make-vector org-level-max 0))
10921
10922 (defun org-init-section-numbers ()
10923 "Initialize the vector for the section numbers."
10924 (let* ((level -1)
10925 (numbers (nreverse (org-split-string "" "\\.")))
10926 (depth (1- (length org-section-numbers)))
10927 (i depth) number-string)
10928 (while (>= i 0)
10929 (if (> i level)
10930 (aset org-section-numbers i 0)
10931 (setq number-string (or (car numbers) "0"))
10932 (if (string-match "\\`[A-Z]\\'" number-string)
10933 (aset org-section-numbers i
10934 (- (string-to-char number-string) ?A -1))
10935 (aset org-section-numbers i (string-to-number number-string)))
10936 (pop numbers))
10937 (setq i (1- i)))))
10938
10939 (defun org-section-number (&optional level)
10940 "Return a string with the current section number.
10941 When LEVEL is non-nil, increase section numbers on that level."
10942 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10943 (when level
10944 (when (> level -1)
10945 (aset org-section-numbers
10946 level (1+ (aref org-section-numbers level))))
10947 (setq idx (1+ level))
10948 (while (<= idx depth)
10949 (if (not (= idx 1))
10950 (aset org-section-numbers idx 0))
10951 (setq idx (1+ idx))))
10952 (setq idx 0)
10953 (while (<= idx depth)
10954 (setq n (aref org-section-numbers idx))
10955 (setq string (concat string (if (not (string= string "")) "." "")
10956 (int-to-string n)))
10957 (setq idx (1+ idx)))
10958 (save-match-data
10959 (if (string-match "\\`\\([@0]\\.\\)+" string)
10960 (setq string (replace-match "" nil nil string)))
10961 (if (string-match "\\(\\.0\\)+\\'" string)
10962 (setq string (replace-match "" nil nil string))))
10963 string))
10964
10965
10966 (defun org-export-icalendar-this-file ()
10967 "Export current file as an iCalendar file.
10968 The iCalendar file will be located in the same directory as the Org-mode
10969 file, but with extension `.ics'."
10970 (interactive)
10971 (org-export-icalendar nil (buffer-file-name)))
10972
10973 ;;;###autoload
10974 (defun org-export-icalendar-all-agenda-files ()
10975 "Export all files in `org-agenda-files' to iCalendar .ics files.
10976 Each iCalendar file will be located in the same directory as the Org-mode
10977 file, but with extension `.ics'."
10978 (interactive)
10979 (apply 'org-export-icalendar nil org-agenda-files))
10980
10981 ;;;###autoload
10982 (defun org-export-icalendar-combine-agenda-files ()
10983 "Export all files in `org-agenda-files' to a single combined iCalendar file.
10984 The file is stored under the name `org-combined-agenda-icalendar-file'."
10985 (interactive)
10986 (apply 'org-export-icalendar t org-agenda-files))
10987
10988 (defun org-export-icalendar (combine &rest files)
10989 "Create iCalendar files for all elements of FILES.
10990 If COMBINE is non-nil, combine all calendar entries into a single large
10991 file and store it under the name `org-combined-agenda-icalendar-file'."
10992 (save-excursion
10993 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
10994 (when combine
10995 (setq ical-file org-combined-agenda-icalendar-file
10996 ical-buffer (org-get-agenda-file-buffer ical-file))
10997 (set-buffer ical-buffer) (erase-buffer))
10998 (while (setq file (pop files))
10999 (catch 'nextfile
11000 (org-check-agenda-file file)
11001 (unless combine
11002 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11003 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11004 (set-buffer ical-buffer) (erase-buffer))
11005 (set-buffer (org-get-agenda-file-buffer file))
11006 (setq category (or org-category
11007 (file-name-sans-extension
11008 (file-name-nondirectory (buffer-file-name)))))
11009 (if (symbolp category) (setq category (symbol-name category)))
11010 (let ((standard-output ical-buffer))
11011 (if combine
11012 (and (not started) (setq started t)
11013 (org-start-icalendar-file org-icalendar-combined-name))
11014 (org-start-icalendar-file category))
11015 (org-print-icalendar-entries combine category)
11016 (when (or (and combine (not files)) (not combine))
11017 (org-finish-icalendar-file)
11018 (set-buffer ical-buffer)
11019 (save-buffer)
11020 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11021 (org-release-buffers org-agenda-new-buffers))))
11022
11023 (defvar org-after-save-iCalendar-file-hook nil
11024 "Hook run after an iCalendar file has been saved.
11025 The iCalendar buffer is still current when this hook is run.
11026 A good way to use this is to tell a desktop calenndar application to re-read
11027 the iCalendar file.")
11028
11029 (defun org-print-icalendar-entries (&optional combine category)
11030 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11031 When COMBINE is non nil, add the category to each line."
11032 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11033 (dts (org-ical-ts-to-string
11034 (format-time-string (cdr org-time-stamp-formats) (current-time))
11035 "DTSTART"))
11036 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11037 (save-excursion
11038 (goto-char (point-min))
11039 (while (re-search-forward org-ts-regexp nil t)
11040 (setq pos (match-beginning 0)
11041 ts (match-string 0)
11042 inc t
11043 hd (org-get-heading))
11044 (if (looking-at re2)
11045 (progn
11046 (goto-char (match-end 0))
11047 (setq ts2 (match-string 1) inc nil))
11048 (setq ts2 ts
11049 tmp (buffer-substring (max (point-min)
11050 (- pos org-ds-keyword-length))
11051 pos)
11052 deadlinep (string-match org-deadline-regexp tmp)
11053 scheduledp (string-match org-scheduled-regexp tmp)
11054 ;; donep (org-entry-is-done-p)
11055 ))
11056 (if (or (string-match org-tr-regexp hd)
11057 (string-match org-ts-regexp hd))
11058 (setq hd (replace-match "" t t hd)))
11059 (if combine
11060 (setq hd (concat hd " (category " category ")")))
11061 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11062 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11063 (princ (format "BEGIN:VEVENT
11064 %s
11065 %s
11066 SUMMARY:%s
11067 END:VEVENT\n"
11068 (org-ical-ts-to-string ts "DTSTART")
11069 (org-ical-ts-to-string ts2 "DTEND" inc)
11070 hd)))
11071 (when org-icalendar-include-todo
11072 (goto-char (point-min))
11073 (while (re-search-forward org-todo-line-regexp nil t)
11074 (setq state (match-string 1))
11075 (unless (equal state org-done-string)
11076 (setq hd (match-string 3))
11077 (if (string-match org-priority-regexp hd)
11078 (setq pri (string-to-char (match-string 2 hd))
11079 hd (concat (substring hd 0 (match-beginning 1))
11080 (substring hd (- (match-end 1)))))
11081 (setq pri org-default-priority))
11082 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11083 (- org-lowest-priority ?A))))))
11084
11085 (princ (format "BEGIN:VTODO
11086 %s
11087 SUMMARY:%s
11088 SEQUENCE:1
11089 PRIORITY:%d
11090 END:VTODO\n"
11091 dts hd pri))))))))
11092
11093 (defun org-start-icalendar-file (name)
11094 "Start an iCalendar file by inserting the header."
11095 (let ((user user-full-name)
11096 (name (or name "unknown"))
11097 (timezone (cadr (current-time-zone))))
11098 (princ
11099 (format "BEGIN:VCALENDAR
11100 VERSION:2.0
11101 X-WR-CALNAME:%s
11102 PRODID:-//%s//Emacs with Org-mode//EN
11103 X-WR-TIMEZONE:%s
11104 CALSCALE:GREGORIAN\n" name user timezone))))
11105
11106 (defun org-finish-icalendar-file ()
11107 "Finish an iCalendar file by inserting the END statement."
11108 (princ "END:VCALENDAR\n"))
11109
11110 (defun org-ical-ts-to-string (s keyword &optional inc)
11111 "Take a time string S and convert it to iCalendar format.
11112 KEYWORD is added in front, to make a complete line like DTSTART....
11113 When INC is non-nil, increase the hour by two (if time string contains
11114 a time), or the day by one (if it does not contain a time)."
11115 (let ((t1 (org-parse-time-string s 'nodefault))
11116 t2 fmt have-time time)
11117 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11118 (setq t2 t1 have-time t)
11119 (setq t2 (org-parse-time-string s)))
11120 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11121 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11122 (when inc
11123 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11124 (setq time (encode-time s mi h d m y)))
11125 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11126 (concat keyword (format-time-string fmt time))))
11127
11128
11129 ;;; Key bindings
11130
11131 ;; - Bindings in Org-mode map are currently
11132 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11133 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11134 ;; e (?) useful from outline-mode
11135 ;; i k @ expendable from outline-mode
11136 ;; 0123456789 ! %^& ()_{} " `' free
11137
11138 ;; Make `C-c C-x' a prefix key
11139 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11140
11141 ;; TAB key with modifiers
11142 (define-key org-mode-map "\C-i" 'org-cycle)
11143 (define-key org-mode-map [(meta tab)] 'org-complete)
11144 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11145 ;; The following line is necessary under Suse GNU/Linux
11146 (unless org-xemacs-p
11147 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11148 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11149
11150 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11151 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11152 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11153 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11154 (define-key org-mode-map [(meta return)] 'org-meta-return)
11155 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11156 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11157
11158 ;; Cursor keys with modifiers
11159 (define-key org-mode-map [(meta left)] 'org-metaleft)
11160 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11161 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11162 (define-key org-mode-map [(meta right)] 'org-metaright)
11163 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11164 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11165 (define-key org-mode-map [(meta up)] 'org-metaup)
11166 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11167 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11168 (define-key org-mode-map [(meta down)] 'org-metadown)
11169 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11170 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11171
11172 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11173 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11174 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11175 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11176 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11177 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11178 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11179 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11180 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11181 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11182 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11183 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11184 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11185 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11186 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11187 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11188
11189 ;; All the other keys
11190 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11191 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11192 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11193 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11194 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11195 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11196 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11197 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11198 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11199 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11200 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11201 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11202 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11203 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11204 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11205 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11206 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11207 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11208 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11209 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11210 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11211 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11212 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11213 (define-key org-mode-map "\C-c]" 'org-remove-file)
11214 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11215 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11216 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11217 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11218 (define-key org-mode-map "\C-m" 'org-return)
11219 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11220 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11221 (define-key org-mode-map "\C-c+" 'org-table-sum)
11222 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11223 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11224 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11225 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11226 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11227 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11228 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11229 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11230 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11231 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11232 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11233 ;; OPML support is only an option for the future
11234 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11235 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11236 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11237 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11238 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11239 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11240 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11241 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11242 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11243 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11244 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11245
11246 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11247 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11248 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11249
11250 (defsubst org-table-p () (org-at-table-p))
11251
11252 (defun org-self-insert-command (N)
11253 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11254 If the cursor is in a table looking at whitespace, the whitespace is
11255 overwritten, and the table is not marked as requiring realignment."
11256 (interactive "p")
11257 (if (and (org-table-p)
11258 (or
11259 (and org-table-auto-blank-field
11260 (member last-command
11261 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11262 (org-table-blank-field))
11263 t)
11264 (eq N 1)
11265 (looking-at "[^|\n]* +|"))
11266 (let (org-table-may-need-update)
11267 (goto-char (1- (match-end 0)))
11268 (delete-backward-char 1)
11269 (goto-char (match-beginning 0))
11270 (self-insert-command N))
11271 (setq org-table-may-need-update t)
11272 (self-insert-command N)))
11273
11274 ;; FIXME:
11275 ;; The following two functions might still be optimized to trigger
11276 ;; re-alignment less frequently.
11277
11278 (defun org-delete-backward-char (N)
11279 "Like `delete-backward-char', insert whitespace at field end in tables.
11280 When deleting backwards, in tables this function will insert whitespace in
11281 front of the next \"|\" separator, to keep the table aligned. The table will
11282 still be marked for re-alignment, because a narrow field may lead to a
11283 reduced column width."
11284 (interactive "p")
11285 (if (and (org-table-p)
11286 (eq N 1)
11287 (string-match "|" (buffer-substring (point-at-bol) (point)))
11288 (looking-at ".*?|"))
11289 (let ((pos (point)))
11290 (backward-delete-char N)
11291 (skip-chars-forward "^|")
11292 (insert " ")
11293 (goto-char (1- pos)))
11294 (backward-delete-char N)))
11295
11296 (defun org-delete-char (N)
11297 "Like `delete-char', but insert whitespace at field end in tables.
11298 When deleting characters, in tables this function will insert whitespace in
11299 front of the next \"|\" separator, to keep the table aligned. The table
11300 will still be marked for re-alignment, because a narrow field may lead to
11301 a reduced column width."
11302 (interactive "p")
11303 (if (and (org-table-p)
11304 (not (bolp))
11305 (not (= (char-after) ?|))
11306 (eq N 1))
11307 (if (looking-at ".*?|")
11308 (let ((pos (point)))
11309 (replace-match (concat
11310 (substring (match-string 0) 1 -1)
11311 " |"))
11312 (goto-char pos)))
11313 (delete-char N)))
11314
11315 ;; How to do this: Measure non-white length of current string
11316 ;; If equal to column width, we should realign.
11317
11318 (defun org-remap (map &rest commands)
11319 "In MAP, remap the functions given in COMMANDS.
11320 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11321 (let (new old)
11322 (while commands
11323 (setq old (pop commands) new (pop commands))
11324 (if (fboundp 'command-remapping)
11325 (define-key map (vector 'remap old) new)
11326 (substitute-key-definition old new map global-map)))))
11327
11328 (when (eq org-enable-table-editor 'optimized)
11329 ;; If the user wants maximum table support, we need to hijack
11330 ;; some standard editing functions
11331 (org-remap org-mode-map
11332 'self-insert-command 'org-self-insert-command
11333 'delete-char 'org-delete-char
11334 'delete-backward-char 'org-delete-backward-char)
11335 (define-key org-mode-map "|" 'org-force-self-insert))
11336
11337 (defun org-shiftcursor-error ()
11338 "Throw an error because Shift-Cursor command was applied in wrong context."
11339 (error "This command is active in special context like tables, headlines or timestamps"))
11340
11341 (defun org-shifttab ()
11342 "Global visibility cycling or move to previous table field.
11343 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11344 See the individual commands for more information."
11345 (interactive)
11346 (cond
11347 ((org-at-table-p) (org-table-previous-field))
11348 (t (org-cycle '(4)))))
11349
11350 (defun org-shiftmetaleft ()
11351 "Promote subtree or delete table column.
11352 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11353 See the individual commands for more information."
11354 (interactive)
11355 (cond
11356 ((org-at-table-p) (org-table-delete-column))
11357 ((org-on-heading-p) (org-promote-subtree))
11358 ((org-at-item-p) (call-interactively 'org-outdent-item))
11359 (t (org-shiftcursor-error))))
11360
11361 (defun org-shiftmetaright ()
11362 "Demote subtree or insert table column.
11363 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11364 See the individual commands for more information."
11365 (interactive)
11366 (cond
11367 ((org-at-table-p) (org-table-insert-column))
11368 ((org-on-heading-p) (org-demote-subtree))
11369 ((org-at-item-p) (call-interactively 'org-indent-item))
11370 (t (org-shiftcursor-error))))
11371
11372 (defun org-shiftmetaup (&optional arg)
11373 "Move subtree up or kill table row.
11374 Calls `org-move-subtree-up' or `org-table-kill-row' or
11375 `org-move-item-up' depending on context. See the individual commands
11376 for more information."
11377 (interactive "P")
11378 (cond
11379 ((org-at-table-p) (org-table-kill-row))
11380 ((org-on-heading-p) (org-move-subtree-up arg))
11381 ((org-at-item-p) (org-move-item-up arg))
11382 (t (org-shiftcursor-error))))
11383 (defun org-shiftmetadown (&optional arg)
11384 "Move subtree down or insert table row.
11385 Calls `org-move-subtree-down' or `org-table-insert-row' or
11386 `org-move-item-down', depending on context. See the individual
11387 commands for more information."
11388 (interactive "P")
11389 (cond
11390 ((org-at-table-p) (org-table-insert-row arg))
11391 ((org-on-heading-p) (org-move-subtree-down arg))
11392 ((org-at-item-p) (org-move-item-down arg))
11393 (t (org-shiftcursor-error))))
11394
11395 (defun org-metaleft (&optional arg)
11396 "Promote heading or move table column to left.
11397 Calls `org-do-promote' or `org-table-move-column', depending on context.
11398 With no specific context, calls the Emacs default `backward-word'.
11399 See the individual commands for more information."
11400 (interactive "P")
11401 (cond
11402 ((org-at-table-p) (org-table-move-column 'left))
11403 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11404 (t (backward-word (prefix-numeric-value arg)))))
11405
11406 (defun org-metaright (&optional arg)
11407 "Demote subtree or move table column to right.
11408 Calls `org-do-demote' or `org-table-move-column', depending on context.
11409 With no specific context, calls the Emacs default `forward-word'.
11410 See the individual commands for more information."
11411 (interactive "P")
11412 (cond
11413 ((org-at-table-p) (org-table-move-column nil))
11414 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11415 (t (forward-word (prefix-numeric-value arg)))))
11416
11417 (defun org-metaup (&optional arg)
11418 "Move subtree up or move table row up.
11419 Calls `org-move-subtree-up' or `org-table-move-row' or
11420 `org-move-item-up', depending on context. See the individual commands
11421 for more information."
11422 (interactive "P")
11423 (cond
11424 ((org-at-table-p) (org-table-move-row 'up))
11425 ((org-on-heading-p) (org-move-subtree-up arg))
11426 ((org-at-item-p) (org-move-item-up arg))
11427 (t (org-shiftcursor-error))))
11428
11429 (defun org-metadown (&optional arg)
11430 "Move subtree down or move table row down.
11431 Calls `org-move-subtree-down' or `org-table-move-row' or
11432 `org-move-item-down', depending on context. See the individual
11433 commands for more information."
11434 (interactive "P")
11435 (cond
11436 ((org-at-table-p) (org-table-move-row nil))
11437 ((org-on-heading-p) (org-move-subtree-down arg))
11438 ((org-at-item-p) (org-move-item-down arg))
11439 (t (org-shiftcursor-error))))
11440
11441 (defun org-shiftup (&optional arg)
11442 "Increase item in timestamp or increase priority of current item.
11443 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11444 See the individual commands for more information."
11445 (interactive "P")
11446 (cond
11447 ((org-at-timestamp-p) (org-timestamp-up arg))
11448 (t (org-priority-up))))
11449
11450 (defun org-shiftdown (&optional arg)
11451 "Decrease item in timestamp or decrease priority of current item.
11452 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11453 See the individual commands for more information."
11454 (interactive "P")
11455 (cond
11456 ((org-at-timestamp-p) (org-timestamp-down arg))
11457 (t (org-priority-down))))
11458
11459 (defun org-shiftright ()
11460 "Next TODO keyword or timestamp one day later, depending on context."
11461 (interactive)
11462 (cond
11463 ((org-at-timestamp-p) (org-timestamp-up-day))
11464 ((org-on-heading-p) (org-todo 'right))
11465 (t (org-shiftcursor-error))))
11466
11467 (defun org-shiftleft ()
11468 "Previous TODO keyword or timestamp one day earlier, depending on context."
11469 (interactive)
11470 (cond
11471 ((org-at-timestamp-p) (org-timestamp-down-day))
11472 ((org-on-heading-p) (org-todo 'left))
11473 (t (org-shiftcursor-error))))
11474
11475 (defun org-copy-special ()
11476 "Copy region in table or copy current subtree.
11477 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11478 See the individual commands for more information."
11479 (interactive)
11480 (call-interactively
11481 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11482
11483 (defun org-cut-special ()
11484 "Cut region in table or cut current subtree.
11485 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11486 See the individual commands for more information."
11487 (interactive)
11488 (call-interactively
11489 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11490
11491 (defun org-paste-special (arg)
11492 "Paste rectangular region into table, or past subtree relative to level.
11493 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11494 See the individual commands for more information."
11495 (interactive "P")
11496 (if (org-at-table-p)
11497 (org-table-paste-rectangle)
11498 (org-paste-subtree arg)))
11499
11500 (defun org-ctrl-c-ctrl-c (&optional arg)
11501 "Call realign table, or recognize a table.el table, or update keywords.
11502 When the cursor is inside a table created by the table.el package,
11503 activate that table. Otherwise, if the cursor is at a normal table
11504 created with org.el, re-align that table. This command works even if
11505 the automatic table editor has been turned off.
11506
11507 If the cursor is in a headline, prompt for tags and insert them into
11508 the current line, aligned to `org-tags-column'. When in a headline and
11509 called with prefix arg, realign all tags in the current buffer.
11510
11511 If the cursor is in one of the special #+KEYWORD lines, this triggers
11512 scanning the buffer for these lines and updating the information.
11513 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11514 (interactive "P")
11515 (let ((org-enable-table-editor t))
11516 (cond
11517 ((org-on-heading-p) (org-set-tags arg))
11518 ((org-at-table.el-p)
11519 (require 'table)
11520 (beginning-of-line 1)
11521 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11522 (table-recognize-table))
11523 ((org-at-table-p)
11524 (org-table-maybe-eval-formula)
11525 (if arg
11526 (org-table-recalculate t)
11527 (org-table-maybe-recalculate-line))
11528 (org-table-align))
11529 ((org-at-item-p)
11530 (org-renumber-ordered-list (prefix-numeric-value arg)))
11531 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11532 (cond
11533 ((equal (match-string 1) "TBLFM")
11534 ;; Recalculate the table before this line
11535 (save-excursion
11536 (beginning-of-line 1)
11537 (skip-chars-backward " \r\n\t")
11538 (if (org-at-table-p) (org-table-recalculate t))))
11539 (t
11540 (org-mode-restart))))
11541 ((org-region-active-p)
11542 (org-table-convert-region (region-beginning) (region-end) arg))
11543 ((condition-case nil
11544 (and (region-beginning) (region-end))
11545 (error nil))
11546 (if (y-or-n-p "Convert inactive region to table? ")
11547 (org-table-convert-region (region-beginning) (region-end) arg)
11548 (error "Abort")))
11549 (t (error "C-c C-c can do nothing useful at this location.")))))
11550
11551 (defun org-mode-restart ()
11552 "Restart Org-mode, to scan again for special lines.
11553 Also updates the keyword regular expressions."
11554 (interactive)
11555 (let ((org-inhibit-startup t)) (org-mode))
11556 (message "Org-mode restarted to refresh keyword and special line setup"))
11557
11558 (defun org-return ()
11559 "Goto next table row or insert a newline.
11560 Calls `org-table-next-row' or `newline', depending on context.
11561 See the individual commands for more information."
11562 (interactive)
11563 (cond
11564 ((org-at-table-p)
11565 (org-table-justify-field-maybe)
11566 (org-table-next-row))
11567 (t (newline))))
11568
11569 (defun org-meta-return (&optional arg)
11570 "Insert a new heading or wrap a region in a table.
11571 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11572 See the individual commands for more information."
11573 (interactive "P")
11574 (cond
11575 ((org-at-table-p)
11576 (org-table-wrap-region arg))
11577 (t (org-insert-heading arg))))
11578
11579 ;;; Menu entries
11580
11581 ;; Define the Org-mode menus
11582 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11583 '("Tbl"
11584 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11585 ["Next Field" org-cycle (org-at-table-p)]
11586 ["Previous Field" org-shifttab (org-at-table-p)]
11587 ["Next Row" org-return (org-at-table-p)]
11588 "--"
11589 ["Blank Field" org-table-blank-field (org-at-table-p)]
11590 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11591 "--"
11592 ("Column"
11593 ["Move Column Left" org-metaleft (org-at-table-p)]
11594 ["Move Column Right" org-metaright (org-at-table-p)]
11595 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11596 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11597 ("Row"
11598 ["Move Row Up" org-metaup (org-at-table-p)]
11599 ["Move Row Down" org-metadown (org-at-table-p)]
11600 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11601 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11602 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11603 "--"
11604 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11605 ("Rectangle"
11606 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11607 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11608 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11609 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11610 "--"
11611 ("Calculate"
11612 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11613 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11614 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11615 "--"
11616 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11617 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11618 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11619 "--"
11620 ["Sum Column/Rectangle" org-table-sum
11621 (or (org-at-table-p) (org-region-active-p))]
11622 ["Which Column?" org-table-current-column (org-at-table-p)])
11623 ["Debug Formulas"
11624 (setq org-table-formula-debug (not org-table-formula-debug))
11625 :style toggle :selected org-table-formula-debug]
11626 "--"
11627 ["Invisible Vlines" org-table-toggle-vline-visibility
11628 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11629 "--"
11630 ["Create" org-table-create (and (not (org-at-table-p))
11631 org-enable-table-editor)]
11632 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11633 ["Import from File" org-table-import (not (org-at-table-p))]
11634 ["Export to File" org-table-export (org-at-table-p)]
11635 "--"
11636 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11637
11638 (easy-menu-define org-org-menu org-mode-map "Org menu"
11639 '("Org"
11640 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11641 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11642 ["Sparse Tree" org-occur t]
11643 ["Show All" show-all t]
11644 "--"
11645 ["New Heading" org-insert-heading t]
11646 ("Navigate Headings"
11647 ["Up" outline-up-heading t]
11648 ["Next" outline-next-visible-heading t]
11649 ["Previous" outline-previous-visible-heading t]
11650 ["Next Same Level" outline-forward-same-level t]
11651 ["Previous Same Level" outline-backward-same-level t]
11652 "--"
11653 ["Jump" org-goto t])
11654 ("Edit Structure"
11655 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11656 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11657 "--"
11658 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11659 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11660 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11661 "--"
11662 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11663 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11664 ["Demote Heading" org-metaright (not (org-at-table-p))]
11665 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11666 "--"
11667 ["Archive Subtree" org-archive-subtree t])
11668 "--"
11669 ("TODO Lists"
11670 ["TODO/DONE/-" org-todo t]
11671 ["Show TODO Tree" org-show-todo-tree t]
11672 ["Global TODO list" org-todo-list t]
11673 "--"
11674 ["Set Priority" org-priority t]
11675 ["Priority Up" org-shiftup t]
11676 ["Priority Down" org-shiftdown t])
11677 ("Dates and Scheduling"
11678 ["Timestamp" org-time-stamp t]
11679 ["Timestamp (inactive)" org-time-stamp-inactive t]
11680 ("Change Date"
11681 ["1 Day Later" org-timestamp-up-day t]
11682 ["1 Day Earlier" org-timestamp-down-day t]
11683 ["1 ... Later" org-shiftup t]
11684 ["1 ... Earlier" org-shiftdown t])
11685 ["Compute Time Range" org-evaluate-time-range t]
11686 ["Schedule Item" org-schedule t]
11687 ["Deadline" org-deadline t]
11688 "--"
11689 ["Goto Calendar" org-goto-calendar t]
11690 ["Date from Calendar" org-date-from-calendar t])
11691 "--"
11692 ["Agenda Command" org-agenda t]
11693 ("File List for Agenda")
11694 ("Special views current file"
11695 ["TODO Tree" org-show-todo-tree t]
11696 ["Check Deadlines" org-check-deadlines t]
11697 ["Timeline" org-timeline t]
11698 ["Tags Tree" org-tags-sparse-tree t])
11699 "--"
11700 ("Hyperlinks"
11701 ["Store Link (Global)" org-store-link t]
11702 ["Insert Link" org-insert-link t]
11703 ["Follow Link" org-open-at-point t])
11704 "--"
11705 ("Export"
11706 ["ASCII" org-export-as-ascii t]
11707 ["Extract Visible Text" org-export-copy-visible t]
11708 ["HTML" org-export-as-html t]
11709 ["HTML and Open" org-export-as-html-and-open t]
11710 ; ["OPML" org-export-as-opml nil]
11711 "--"
11712 ["iCalendar this file" org-export-icalendar-this-file t]
11713 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11714 :active t :keys "C-c C-x C-i"]
11715 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11716 "--"
11717 ["Option Template" org-insert-export-options-template t]
11718 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11719 "--"
11720 ("Documentation"
11721 ["Show Version" org-version t]
11722 ["Info Documentation" org-info t])
11723 ("Customize"
11724 ["Browse Org Group" org-customize t]
11725 "--"
11726 ["Build Full Customize Menu" org-create-customize-menu
11727 (fboundp 'customize-menu-create)])
11728 "--"
11729 ["Refresh setup" org-mode-restart t]
11730 ))
11731
11732 (defun org-info (&optional node)
11733 "Read documentation for Org-mode in the info system.
11734 With optional NODE, go directly to that node."
11735 (interactive)
11736 (require 'info)
11737 (Info-goto-node (format "(org)%s" (or node ""))))
11738
11739 (defun org-install-agenda-files-menu ()
11740 (easy-menu-change
11741 '("Org") "File List for Agenda"
11742 (append
11743 (list
11744 ["Edit File List" (customize-variable 'org-agenda-files) t]
11745 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11746 ["Remove Current File from List" org-remove-file t]
11747 ["Cycle through agenda files" org-cycle-agenda-files t]
11748 "--")
11749 (mapcar 'org-file-menu-entry org-agenda-files))))
11750
11751 ;;; Documentation
11752
11753 (defun org-customize ()
11754 "Call the customize function with org as argument."
11755 (interactive)
11756 (customize-browse 'org))
11757
11758 (defun org-create-customize-menu ()
11759 "Create a full customization menu for Org-mode, insert it into the menu."
11760 (interactive)
11761 (if (fboundp 'customize-menu-create)
11762 (progn
11763 (easy-menu-change
11764 '("Org") "Customize"
11765 `(["Browse Org group" org-customize t]
11766 "--"
11767 ,(customize-menu-create 'org)
11768 ["Set" Custom-set t]
11769 ["Save" Custom-save t]
11770 ["Reset to Current" Custom-reset-current t]
11771 ["Reset to Saved" Custom-reset-saved t]
11772 ["Reset to Standard Settings" Custom-reset-standard t]))
11773 (message "\"Org\"-menu now contains full customization menu"))
11774 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11775
11776 ;;; Miscellaneous stuff
11777
11778 (defun org-move-line-down (arg)
11779 "Move the current line down. With prefix argument, move it past ARG lines."
11780 (interactive "p")
11781 (let ((col (current-column))
11782 beg end pos)
11783 (beginning-of-line 1) (setq beg (point))
11784 (beginning-of-line 2) (setq end (point))
11785 (beginning-of-line (+ 1 arg))
11786 (setq pos (move-marker (make-marker) (point)))
11787 (insert (delete-and-extract-region beg end))
11788 (goto-char pos)
11789 (move-to-column col)))
11790
11791 (defun org-move-line-up (arg)
11792 "Move the current line up. With prefix argument, move it past ARG lines."
11793 (interactive "p")
11794 (let ((col (current-column))
11795 beg end pos)
11796 (beginning-of-line 1) (setq beg (point))
11797 (beginning-of-line 2) (setq end (point))
11798 (beginning-of-line (- arg))
11799 (setq pos (move-marker (make-marker) (point)))
11800 (insert (delete-and-extract-region beg end))
11801 (goto-char pos)
11802 (move-to-column col)))
11803
11804 ;; Paragraph filling stuff.
11805 ;; We want this to be just right, so use the full arsenal.
11806 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11807 ;; filladapt package works slightly differently.
11808
11809 (defun org-set-autofill-regexps ()
11810 (interactive)
11811 ;; In the paragraph separator we include headlines, because filling
11812 ;; text in a line directly attached to a headline would otherwise
11813 ;; fill the headline as well.
11814 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11815 ;; The paragraph starter includes hand-formatted lists.
11816 (set (make-local-variable 'paragraph-start)
11817 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11818 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11819 ;; But only if the user has not turned off tables or fixed-width regions
11820 (set (make-local-variable 'auto-fill-inhibit-regexp)
11821 (concat "\\*\\|#"
11822 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11823 (concat
11824 "\\|[ \t]*["
11825 (if org-enable-table-editor "|" "")
11826 (if org-enable-fixed-width-editor ":" "")
11827 "]"))))
11828 ;; We use our own fill-paragraph function, to make sure that tables
11829 ;; and fixed-width regions are not wrapped. That function will pass
11830 ;; through to `fill-paragraph' when appropriate.
11831 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11832 ;; Adaptive filling: To get full control, first make sure that
11833 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11834 (setq adaptive-fill-regexp "\000")
11835 (setq adaptive-fill-function 'org-adaptive-fill-function))
11836
11837 (defun org-fill-paragraph (&optional justify)
11838 "Re-align a table, pass through to fill-paragraph if no table."
11839 (let ((table-p (org-at-table-p))
11840 (table.el-p (org-at-table.el-p)))
11841 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11842 (table.el-p t) ; skip table.el tables
11843 (table-p (org-table-align) t) ; align org-mode tables
11844 (t nil)))) ; call paragraph-fill
11845
11846 ;; For reference, this is the default value of adaptive-fill-regexp
11847 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11848
11849 (defun org-adaptive-fill-function ()
11850 "Return a fill prefix for org-mode files.
11851 In particular, this makes sure hanging paragraphs for hand-formatted lists
11852 work correctly."
11853 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11854 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11855
11856 ;; Functions needed for Emacs/XEmacs region compatibility
11857
11858 (defun org-region-active-p ()
11859 "Is `transient-mark-mode' on and the region active?
11860 Works on both Emacs and XEmacs."
11861 (if org-ignore-region
11862 nil
11863 (if org-xemacs-p
11864 (and zmacs-regions (region-active-p))
11865 (and transient-mark-mode mark-active))))
11866
11867 (defun org-add-to-invisibility-spec (arg)
11868 "Add elements to `buffer-invisibility-spec'.
11869 See documentation for `buffer-invisibility-spec' for the kind of elements
11870 that can be added."
11871 (cond
11872 ((fboundp 'add-to-invisibility-spec)
11873 (add-to-invisibility-spec arg))
11874 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11875 (setq buffer-invisibility-spec (list arg)))
11876 (t
11877 (setq buffer-invisibility-spec
11878 (cons arg buffer-invisibility-spec)))))
11879
11880 (defun org-remove-from-invisibility-spec (arg)
11881 "Remove elements from `buffer-invisibility-spec'."
11882 (if (fboundp 'remove-from-invisibility-spec)
11883 (remove-from-invisibility-spec arg)
11884 (if (consp buffer-invisibility-spec)
11885 (setq buffer-invisibility-spec
11886 (delete arg buffer-invisibility-spec)))))
11887
11888 (defun org-in-invisibility-spec-p (arg)
11889 "Is ARG a member of `buffer-invisibility-spec'?."
11890 (if (consp buffer-invisibility-spec)
11891 (member arg buffer-invisibility-spec)
11892 nil))
11893
11894 (defun org-image-file-name-regexp ()
11895 "Return regexp matching the file names of images."
11896 (if (fboundp 'image-file-name-regexp)
11897 (image-file-name-regexp)
11898 (let ((image-file-name-extensions
11899 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11900 "xbm" "xpm" "pbm" "pgm" "ppm")))
11901 (concat "\\."
11902 (regexp-opt (nconc (mapcar 'upcase
11903 image-file-name-extensions)
11904 image-file-name-extensions)
11905 t)
11906 "\\'"))))
11907
11908 ;; Functions needed for compatibility with old outline.el.
11909
11910 ;; Programming for the old outline.el (that uses selective display
11911 ;; instead of `invisible' text properties) is a nightmare, mostly
11912 ;; because regular expressions can no longer be anchored at
11913 ;; beginning/end of line. Therefore a number of function need special
11914 ;; treatment when the old outline.el is being used.
11915
11916 ;; The following functions capture almost the entire compatibility code
11917 ;; between the different versions of outline-mode. The only other
11918 ;; places where this is important are the font-lock-keywords, and in
11919 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
11920
11921 ;; C-a should go to the beginning of a *visible* line, also in the
11922 ;; new outline.el. I guess this should be patched into Emacs?
11923 (defun org-beginning-of-line ()
11924 "Go to the beginning of the current line. If that is invisible, continue
11925 to a visible line beginning. This makes the function of C-a more intuitive."
11926 (interactive)
11927 (beginning-of-line 1)
11928 (if (bobp)
11929 nil
11930 (backward-char 1)
11931 (if (org-invisible-p)
11932 (while (and (not (bobp)) (org-invisible-p))
11933 (backward-char 1)
11934 (beginning-of-line 1))
11935 (forward-char 1))))
11936
11937 (when org-noutline-p
11938 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11939 ;; FIXME: should I use substitute-key-definition to reach other bindings
11940 ;; of beginning-of-line?
11941
11942 (defun org-invisible-p ()
11943 "Check if point is at a character currently not visible."
11944 (if org-noutline-p
11945 ;; Early versions of noutline don't have `outline-invisible-p'.
11946 (if (fboundp 'outline-invisible-p)
11947 (outline-invisible-p)
11948 (get-char-property (point) 'invisible))
11949 (save-excursion
11950 (skip-chars-backward "^\r\n")
11951 (equal (char-before) ?\r))))
11952
11953 (defun org-back-to-heading (&optional invisible-ok)
11954 "Move to previous heading line, or beg of this line if it's a heading.
11955 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11956 (if org-noutline-p
11957 (outline-back-to-heading invisible-ok)
11958 (if (and (memq (char-before) '(?\n ?\r))
11959 (looking-at outline-regexp))
11960 t
11961 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11962 outline-regexp)
11963 nil t)
11964 (if invisible-ok
11965 (progn (goto-char (match-end 1))
11966 (looking-at outline-regexp)))
11967 (error "Before first heading")))))
11968
11969 (defun org-on-heading-p (&optional invisible-ok)
11970 "Return t if point is on a (visible) heading line.
11971 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
11972 (if org-noutline-p
11973 (outline-on-heading-p 'invisible-ok)
11974 (save-excursion
11975 (skip-chars-backward "^\n\r")
11976 (and (looking-at outline-regexp)
11977 (or invisible-ok
11978 (bobp)
11979 (equal (char-before) ?\n))))))
11980
11981 (defun org-up-heading-all (arg)
11982 "Move to the heading line of which the present line is a subheading.
11983 This function considers both visible and invisible heading lines.
11984 With argument, move up ARG levels."
11985 (if org-noutline-p
11986 (if (fboundp 'outline-up-heading-all)
11987 (outline-up-heading-all arg) ; emacs 21 version of outline.el
11988 (outline-up-heading arg t)) ; emacs 22 version of outline.el
11989 (org-back-to-heading t)
11990 (looking-at outline-regexp)
11991 (if (<= (- (match-end 0) (match-beginning 0)) arg)
11992 (error "Cannot move up %d levels" arg)
11993 (re-search-backward
11994 (concat "[\n\r]" (regexp-quote
11995 (make-string (- (match-end 0) (match-beginning 0) arg)
11996 ?*))
11997 "[^*]"))
11998 (forward-char 1))))
11999
12000 (defun org-show-hidden-entry ()
12001 "Show an entry where even the heading is hidden."
12002 (save-excursion
12003 (if (not org-noutline-p)
12004 (progn
12005 (org-back-to-heading t)
12006 (org-flag-heading nil)))
12007 (org-show-entry)))
12008
12009 (defun org-check-occur-regexp (regexp)
12010 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12011 Of course, only for the old outline mode."
12012 (if org-noutline-p
12013 regexp
12014 (if (string-match "^\\^" regexp)
12015 (concat "[\n\r]" (substring regexp 1))
12016 regexp)))
12017
12018 (defun org-flag-heading (flag &optional entry)
12019 "Flag the current heading. FLAG non-nil means make invisible.
12020 When ENTRY is non-nil, show the entire entry."
12021 (save-excursion
12022 (org-back-to-heading t)
12023 (if (not org-noutline-p)
12024 ;; Make the current headline visible
12025 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12026 ;; Check if we should show the entire entry
12027 (if entry
12028 (progn
12029 (org-show-entry)
12030 (save-excursion ;; FIXME: Is this the fix for points in the -|
12031 ;; middle of text? |
12032 (and (outline-next-heading) ;; |
12033 (org-flag-heading nil)))) ; show the next heading _|
12034 (outline-flag-region (max 1 (1- (point)))
12035 (save-excursion (outline-end-of-heading) (point))
12036 (if org-noutline-p
12037 flag
12038 (if flag ?\r ?\n))))))
12039
12040 (defun org-end-of-subtree (&optional invisible-OK)
12041 ;; This is an exact copy of the original function, but it uses
12042 ;; `org-back-to-heading', to make it work also in invisible
12043 ;; trees. And is uses an invisible-OK argument.
12044 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12045 (org-back-to-heading invisible-OK)
12046 (let ((opoint (point))
12047 (first t)
12048 (level (funcall outline-level)))
12049 (while (and (not (eobp))
12050 (or first (> (funcall outline-level) level)))
12051 (setq first nil)
12052 (outline-next-heading))
12053 (if (memq (preceding-char) '(?\n ?\^M))
12054 (progn
12055 ;; Go to end of line before heading
12056 (forward-char -1)
12057 (if (memq (preceding-char) '(?\n ?\^M))
12058 ;; leave blank line before heading
12059 (forward-char -1))))))
12060
12061 (defun org-show-subtree ()
12062 "Show everything after this heading at deeper levels."
12063 (outline-flag-region
12064 (point)
12065 (save-excursion
12066 (outline-end-of-subtree) (outline-next-heading) (point))
12067 (if org-noutline-p nil ?\n)))
12068
12069 (defun org-show-entry ()
12070 "Show the body directly following this heading.
12071 Show the heading too, if it is currently invisible."
12072 (interactive)
12073 (save-excursion
12074 (org-back-to-heading t)
12075 (outline-flag-region
12076 (1- (point))
12077 (save-excursion
12078 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12079 (or (match-beginning 1) (point-max)))
12080 (if org-noutline-p nil ?\n))))
12081
12082
12083 (defun org-make-options-regexp (kwds)
12084 "Make a regular expression for keyword lines."
12085 (concat
12086 (if org-noutline-p "^" "[\n\r]")
12087 "#?[ \t]*\\+\\("
12088 (mapconcat 'regexp-quote kwds "\\|")
12089 "\\):[ \t]*"
12090 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12091
12092 ;; Make `bookmark-jump' show the jump location if it was hidden.
12093 (eval-after-load "bookmark"
12094 '(if (boundp 'bookmark-after-jump-hook)
12095 ;; We can use the hook
12096 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12097 ;; Hook not available, use advice
12098 (defadvice bookmark-jump (after org-make-visible activate)
12099 "Make the position visible."
12100 (org-bookmark-jump-unhide))))
12101
12102 (defun org-bookmark-jump-unhide ()
12103 "Unhide the current position, to show the bookmark location."
12104 (and (eq major-mode 'org-mode)
12105 (or (org-invisible-p)
12106 (save-excursion (goto-char (max (point-min) (1- (point))))
12107 (org-invisible-p)))
12108 (org-show-hierarchy-above)))
12109
12110 ;;; Finish up
12111
12112 (provide 'org)
12113
12114 (run-hooks 'org-load-hook)
12115
12116 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12117 ;;; org.el ends here
12118